How to calculate XOR with offset?

I want to perform an XOR calculation with a different offset to be displayed in the calculation.

Example:

key = [0, 1, 0]
text = ["0", "1", "0", "1", "0", "1", "0", "1", "1", "1"]

XOR calculation:

key[0] ^ text[0] ; 
key[1] ^ text[1] ; 
key[2] ^ text[2] ; 
key[0] ^ text[3] ; 
key[1] ^ text[4] ; 
key[2] ^ text[5] ; 
key[0] ^ text[6] ; 
key[1] ^ text[7] ; 
key[2] ^ text[8] ;
key[0] ^ text[9] ;

How to do it?

+2
source share
2 answers

You can use the method Array#cycleto “cyclize” your key as much as necessary:

text.zip(key.cycle).map{|t,k| t.to_i ^ k}
# => [0, 0, 0, 1, 1, 1, 0, 0, 1, 1]
+3
source

Ruby 1.9 has a .cycle:

key = [0, 1, 0]
text = ["0", "1", "0", "1", "0", "1", "0", "1", "1", "1"]
key_looper = key.cycle
p text.map{|el|key_looper.next ^ el.to_i} #=> [0, 0, 0, 1, 1, 1, 0, 0, 1, 1]
+2
source

All Articles