gpt4 book ai didi

r - R中二进制序列的函数

转载 作者:行者123 更新时间:2023-12-05 09:34:38 32 4
gpt4 key购买 nike

如何在 R 中编写一个函数,给定一个整数 n,它找到所有长度为 2n 的二进制序列,使得前 n 位的总和与后 n 位的总和相同。

Example:
For n = 2, the sequences are:
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 0 1 1 0 0 1
[2,] 0 0 0 1 1 1
[3,] 0 1 0 1 0 1
[4,] 0 0 1 0 1 1

最佳答案

以下函数是this GeeksforGeeks post中函数的R翻译.

findAllSeq2n <- function(n){
f <- function(d, out, start, end){
if (abs(d) > (end - start + 1) / 2) return(NULL)
if (start > end) {
if (d == 0) {
#cat(out, "\n")
return(out)
}
}

out[start] <- 0L
out[end] <- 1L
s01 <- f(d + 1L, out, start + 1L, end - 1L)

out[start] <- 1L
out[end] <- 1L
s11 <- f(d, out, start + 1L, end - 1L)

out[start] <- 0L
out[end] <- 0L
s00 <- f(d, out, start + 1L, end - 1L)

out[start] <- 1L
out[end] <- 0L
s10 <- f(d - 1L, out, start + 1L, end - 1L)

do.call(cbind, list(s01, s11, s00, s10))
}
out <- integer(2*n)
f(0, out, 1, 2*n)
}

findAllSeq2n(2)
# [,1] [,2] [,3] [,4] [,5] [,6]
#[1,] 0 1 1 0 0 1
#[2,] 1 1 0 1 0 0
#[3,] 0 1 0 1 0 1
#[4,] 1 1 1 0 0 0

findAllSeq2n(3)
findAllSeq2n(4)

关于r - R中二进制序列的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66453586/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com