如何用偏移量计算XOR?

我想在计算中列出具有不同偏移量的XOR计算。

示例:

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

XOR计算:

 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] ; 

这该怎么做 ?

您可以使用Array#cycle方法根据需要“循环”您的密钥:

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

Ruby 1.9有.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]