我的朋友给了我一个脑筋急转弯,我想试试R。
想象一下,100枚硬币排成一排,所有硬币的头都朝上。现在每2枚硬币就被抛出一次(因此变成了反面)。
为了创建向量,我从以下内容开始:
flips <- rep('h', 100)
levels(flips) <- c("h", "t")任何帮助都将不胜感激。
发布于 2017-01-06 15:38:20
试试这个:
coins <- rep(1, 100) # 1 = Head, 0 = Tail
n = 3 # run till the time when you flip every 3rd coin
invisible(sapply(2:n function(i) {indices <- seq(i, 100, i); coins[indices] <<- (coins[indices] + 1) %% 2}) )
which(coins == 1)
# [1] 1 5 6 7 11 12 13 17 18 19 23 24 25 29 30 31 35 36 37 41 42 43 47 48 49 53 54 55 59 60 61 65 66 67 71 72 73 77 78 79 83 84 85 89 90 91 95 96 97
sum(coins==1)
#[1] 49如果你运行到n= 100,只有完美正方形位置的硬币才会显示正面。
coins <- rep(1, 100) # 1 = Head, 0 = Tail
n <- 100
invisible(sapply(2:n, function(i) {indices <- seq(i, 100, i); coins[indices] <<- (coins[indices] + 1) %% 2}) )
which(coins == 1)
# [1] 1 4 9 16 25 36 49 64 81 100
sum(coins==1)
# [1] 10https://stackoverflow.com/questions/41500789
复制相似问题