Apologize for the title. Here is my problem. I need to generate a L-length binary code permutation. For L = 2, its like: 00 01 10 11
My idea is to divide the problem into two part:
- write a function f that transform an integer to its binary form
- loop 1:2^L
Here is my function for step 1:
kbitpermute <- function(input = 2^16 - 1, k = 16){
ret = matrix(0, ncol = k, nrow = 1)
for(i in 1:k){
ret[1,k-i+1] = input & 1
input = bitwShiftR(input, 1)
}
return(ret)
}
And then I use lapply()
to obtain the permutation, like:
temp3 = lapply(1:2^2 - 1, kbitpermute, k = 2)
temp3
[[1]]
[,1] [,2]
[1,] 0 0
[[2]]
[,1] [,2]
[1,] 0 1
[[3]]
[,1] [,2]
[1,] 1 1
[[4]]
[,1] [,2]
[1,] 1 1
It seems works, but how to transform the output of lapply
to its matrix form? And, is there any easy way to do the whole task?
=== update ===
I find a way to use unlist
to do the transformation, like
temp3 = t(matrix(unlist(lapply(1:2^2 - 1, kbitpermute, k = 2)), nrow = 2, ncol=2^2))
.
But is there any easy way?
=== update ===
right version of kbitpermute, and special thanks to @Batanichek
kbitpermute <- function(input = 2^16 - 1, k = 16){
ret = matrix(0, ncol = k, nrow = 1)
for(i in 1:k){
ret[1,k-i+1] = bitwAnd(input, 1)
input = bitwShiftR(input, 1)
}
return(ret)
}
> t(sapply(1:2^2 - 1, kbitpermute, k = 2))
[,1] [,2]
[1,] 0 0
[2,] 0 1
[3,] 1 0
[4,] 1 1