2

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:

    1. write a function f that transform an integer to its binary form
    1. 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
Dylan
  • 1,315
  • 3
  • 12
  • 19
  • 1
    I believe your question has everything to do with r language and nothing with algorithm. Please correct me if I am wrong, else that remove algorithm tag. – Rohit Rawat Dec 28 '15 at 12:14
  • 1
    a bit shorter and pretty use `t(sapply(1:2^2 - 1, kbitpermute, k = 2))` unstead of `t(matrix(unlist(lapply(...` – Batanichek Dec 28 '15 at 12:21
  • 1
    You have different result in `temp3 = lapply(1:2^2 - 1, kbitpermute, k = 2)` and "For L = 2, its like: 00 00 01 11" may be typo error – Batanichek Dec 28 '15 at 12:25

1 Answers1

2

Try something like ( from here)

test=function(x,k){
  a=rev(as.integer(intToBits(x))[1:k])
  return(a)
}
x=2  
t(sapply(1:2^x - 1, test,k=x))
#     [,1] [,2]
#[1,]    0    0
#[2,]    0    1
#[3,]    1    0
#[4,]    1    1

Time comparison

x=15
system.time(t(sapply(1:2^x - 1, test,k=x)))
#пользователь      система       прошло 
#    0.62         0.21         1.35
system.time(t(sapply(1:2^x - 1, kbitpermute,k=x)))
#пользователь      система       прошло 
#    1.84         0.35         2.48  

(P.S.have not english local )

Community
  • 1
  • 1
Batanichek
  • 7,761
  • 31
  • 49