编程介的小学生 2019-09-09 18:14 采纳率: 0.4%
浏览 49

Card Trick 代码的设计的方式

Problem Description
The magician shuffles a small pack of cards, holds it face down and performs the following procedure:

1.The top card is moved to the bottom of the pack. The new top card is dealt face up onto the table. It is the Ace of Spades.
2.Two cards are moved one at a time from the top to the bottom. The next card is dealt face up onto the table. It is the Two of Spades.
3.Three cards are moved one at a time…
4.This goes on until the nth and last card turns out to be the n of Spades.
This impressive trick works if the magician knows how to arrange the cards beforehand (and knows how to give a false shuffle). Your program has to determine the initial order of the cards for a given number of cards, 1 ≤ n ≤ 13.

Input
On the first line of the input is a single positive integer, telling the number of test cases to follow. Each case consists of one line containing the integer n.

Output
For each test case, output a line with the correct permutation of the values 1 to n, space separated. The first number showing the top card of the pack, etc…

Sample Input
2
4
5

Sample Output
2 1 4 3
3 1 4 5 2

  • 写回答

1条回答 默认 最新

  • 你知我知皆知 2024-07-30 22:37
    关注

    以下回答参考 皆我百晓生券券喵儿 等免费微信小程序相关内容作答,并由本人整理回复。

    # 读取数据
    input_file <- "card_trick.txt"
    output_file <- "output_card_trick.txt"
    
    # 打开文件并读取数据
    data <- readLines(input_file)
    
    # 定义函数来计算卡牌顺序
    calculate_order <- function(n) {
      # 初始化变量
      result <- c()
      
      # 将数字转换为字符以便于处理
      numbers <- as.character(1:n)
      
      # 对每个数字进行循环,并将其添加到结果列表中
      for (i in 1:length(numbers)) {
        # 获取当前数字对应的索引值
        index <- which(numbers == i)
        
        # 如果索引值是偶数,则将索引值减半(因为每次移动一个位置)
        if (index %% 2 == 0) {
          result[i] <- result[index/2]
        } else {
          result[i] <- result[(index - 1) / 2 + 1]
        }
      }
      
      # 返回结果列表
      return(result)
    }
    
    # 遍历测试数据集,并输出结果
    for (i in 1:2) {
      # 每次迭代时,使用不同的输入值
      n <- data[[i]]
      print(paste("Case ", i+1, ": ", paste(calculate_order(n), collapse = " ")))
    }
    

    请注意,这段代码中的readLines()函数用于从指定的文本文件中读取数据。在实际应用中,请确保替换为正确的路径或文件名。此外,根据您的需求和环境可能需要调整代码以适应特定的数据格式。

    评论

报告相同问题?