![](/img/trans.png)
[英]Finding all sum of 2 power value combination values of a given number in R
[英]Finding all sum of 2 power value combination values of a given number in R
R数据框1:
指数 | 力值 |
---|---|
0 | 1个 |
1个 | 2个 |
2个 | 4个 |
3个 | 8个 |
4个 | 16 |
5个 | 32 |
R 数据框 2:
合并值 |
---|
20 |
50 |
附上预期的输出图像。
下面的代码提供了 stackoverflow mate 之一。 我正在寻找如何修复
直到第 31 次方的列,如附图所示。 这些列与可能的代码匹配,然后为其余列放置 1 和 0,否则为 0。 请帮忙。
toCodes <- function(x) {
n <- floor(log2(x))
pow <- rev(seq.int(max(n)))
# 'y' is the matrix of codes
y <- t(sapply(x, \(.x) (.x %/% 2^pow) %% 2L))
i_cols <- apply(y, 2, \(.y) any(.y != 0L))
colnames(y) <- sprintf("code_%d", 2^pow)
#
possiblecodes <- apply(y, 1, \(p) {
codes <- 2^pow[as.logical(p)]
paste(rev(codes), collapse = ",")
})
data.frame(combinedvalue = x, possiblecodes, y[, i_cols])
}
x <- c(20L, 50L)
toCodes(x)
这是一个使用intToBits
转换为二进制和 tidyverse 库以进行后续数据操作的解决方案。
x <- c(20L, 50L)
map_dfr(x, ~{
bin <- intToBits(.x)
n <- 2^(seq_len(32) - 1)
possible <- paste(n[as.logical(bin)], collapse = ", ")
data.frame(combinevalue = .x,
possiblecodes = possible,
y = rev(as.integer(bin)),
n = rev(paste0("code_", n)))
}) |>
pivot_wider(names_from = n, values_from = y)
##> # A tibble: 2 × 34
##> combinevalue possiblecodes code_2147483648 code_1073741824 code_536870912
##> <int> <chr> <int> <int> <int>
##> 1 20 4, 16 0 0 0
##> 2 50 2, 16, 32 0 0 0
##> # … with 29 more variables: code_268435456 <int>, code_134217728 <int>,
##> # code_67108864 <int>, code_33554432 <int>, code_16777216 <int>,
##> # code_8388608 <int>, code_4194304 <int>, code_2097152 <int>,
##> # code_1048576 <int>, code_524288 <int>, code_262144 <int>,
##> # code_131072 <int>, code_65536 <int>, code_32768 <int>, code_16384 <int>,
##> # code_8192 <int>, code_4096 <int>, code_2048 <int>, code_1024 <int>,
##> # code_512 <int>, code_256 <int>, code_128 <int>, code_64 <int>, …
尝试以下递归
f <- function(n) {
if (n == 0) {
return(NULL)
}
v <- 2^floor(log2(n))
c(Recall(n - v), v)
}
你会得到
> f(50)
[1] 2 16 32
> f(20)
[1] 4 16
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.