Ruby,无法解释的减少行为
Ruby, unexplainable reduce behavior
美好的一天。在不同的编程竞赛中解决一类 'find unique value' 问题的常见做法是使用此代码 arr.reduce(:^)
:
例如像这样的任务 你得到一个奇数长度的整数数组,除了一个数字外,所有数组都相同。求这个数 通常这样解决:
[8,8,8,5,8,8,8].reduce(:^) # 5
我开始做实验,发现这个解决方案有一个差距,就是:
p [8,2,2].reduce(:^) # 8
p [8,2,2,2].reduce(:^) # 10 !!!!!!!!
p [8,2,2,2,2].reduce(:^) # 8
我发现在任何数组格式 [x,y,y,y]
中 x
都不能被 reduce(:^)
找到:
p x = rand(1..100)
p y = rand(1..100)
p [x, y, y, y].reduce(:^) == x # FALSE (!)
puts "But!"
p [x, y, y ].reduce(:^) == x # true
p [x, y, y, y, y ].reduce(:^) == x # true
为什么会这样? (我的 ruby 是 MRI 2.3.0)
You are given an odd-length array of integers, ...
[8, 2, 2, 2]
odd-length怎么样?
第三个 2
永远不会异或。人们可能会一步一步检查:
8 ^ 2
#⇒ 10
8 ^ 2 ^ 2
#⇒ 8 # because 2 and 2 are XOR’ed out
8 ^ 2 ^ 2 ^ 2
#⇒ 10 # because it’s the same as 8 ^ 2
还有:
2 ^ 2 ^ 2
#⇒ 2
@mudasobwa 回答正确。然而,为了获得更多见解,您可能想看看:
https://www.calleerlandsson.com/rubys-bitwise-operators/
对于您的用例,您最好使用:
[8,2,2,2].inject{|i,n| i > n ? i : n}
让我们看看幕后发生了什么:
def max_array_int(arr)
arr.inject do |i,n|
check = i > n ? i : n
puts "evaluated #{i} > #{n}. result: #{check}"
check
end
end
max_array_int [10,3,15,7]
美好的一天。在不同的编程竞赛中解决一类 'find unique value' 问题的常见做法是使用此代码 arr.reduce(:^)
:
例如像这样的任务 你得到一个奇数长度的整数数组,除了一个数字外,所有数组都相同。求这个数 通常这样解决:
[8,8,8,5,8,8,8].reduce(:^) # 5
我开始做实验,发现这个解决方案有一个差距,就是:
p [8,2,2].reduce(:^) # 8
p [8,2,2,2].reduce(:^) # 10 !!!!!!!!
p [8,2,2,2,2].reduce(:^) # 8
我发现在任何数组格式 [x,y,y,y]
中 x
都不能被 reduce(:^)
找到:
p x = rand(1..100)
p y = rand(1..100)
p [x, y, y, y].reduce(:^) == x # FALSE (!)
puts "But!"
p [x, y, y ].reduce(:^) == x # true
p [x, y, y, y, y ].reduce(:^) == x # true
为什么会这样? (我的 ruby 是 MRI 2.3.0)
You are given an odd-length array of integers, ...
[8, 2, 2, 2]
odd-length怎么样?
第三个 2
永远不会异或。人们可能会一步一步检查:
8 ^ 2
#⇒ 10
8 ^ 2 ^ 2
#⇒ 8 # because 2 and 2 are XOR’ed out
8 ^ 2 ^ 2 ^ 2
#⇒ 10 # because it’s the same as 8 ^ 2
还有:
2 ^ 2 ^ 2
#⇒ 2
@mudasobwa 回答正确。然而,为了获得更多见解,您可能想看看:
https://www.calleerlandsson.com/rubys-bitwise-operators/
对于您的用例,您最好使用:
[8,2,2,2].inject{|i,n| i > n ? i : n}
让我们看看幕后发生了什么:
def max_array_int(arr)
arr.inject do |i,n|
check = i > n ? i : n
puts "evaluated #{i} > #{n}. result: #{check}"
check
end
end
max_array_int [10,3,15,7]