Sam*_*m P 0 ruby arrays methods unique
有一个包含一些数字的数组。除了 1 之外,所有数字都相等。我正在尝试得到这种类型的东西:
find_uniq([ 1, 1, 1, 2, 1, 1 ]) == 2
find_uniq([ 0, 0, 0.55, 0, 0 ]) == 0.55
Run Code Online (Sandbox Code Playgroud)
我试过这个:
def find_uniq(arr)
arr.uniq.each{|e| arr.count(e)}
end
Run Code Online (Sandbox Code Playgroud)
它为我提供了数组中的两个不同值,但我不确定如何选择唯一的值。我可以使用某种计数吗?谢谢!
这有效:
def find_uniq(arr)
return nil if arr.size < 3
if arr[0] != arr[1]
return arr[1] == arr[2] ? arr[0] : arr[1]
end
arr.each_cons(2) { |x, y| return y if y != x }
end
Run Code Online (Sandbox Code Playgroud)
谢谢 pjs 和卡里·斯沃夫兰。
我会这样做:
[ 1, 1, 1, 2, 1, 1 ]
.tally # { 1=>5, 2=>1 }
.find { |_, v| v == 1 } # [2, 1]
.first # 2
Run Code Online (Sandbox Code Playgroud)
或者如 3limin4t0r 建议的那样:
[ 1, 1, 1, 2, 1, 1 ]
.tally # { 1=>5, 2=>1 }
.invert[1] # { 5=>1, 1=>2 } => 2
Run Code Online (Sandbox Code Playgroud)