将两个数组相互比较

时间:2018-05-31 16:21:51

标签: ruby

我正在尝试解决ruby中的一些问题。 我正在尝试将两个阵列相互比较。

Array1 = [1,0,1,0,1,1]
Array2=  [0,0,1,0,1,0]

我从用户那里得到了这个输入。然后我比较投票。如果两个人都在相同的索引上投票1,我正在尝试将空数组增加1.

def count_votes
  bob_votes = gets.chomp
  alice_votes = gets.chomp
  bvotes = bob_votes.split('')
  avotes = alice_votes.split('')
  common_upvotes = []
  bvotes.each.with_index(0) do |el, i|
    if bvotes[i] == 1
    common_upvotes << 1
  end
end

我实际上想要将avotesbvotes进行比较,然后将空数组增加1.我需要一点帮助

3 个答案:

答案 0 :(得分:4)

您可以使用Array#zipEnumerable#count

array1 = [1,0,1,0,1,1]
array2=  [0,0,1,0,1,0]
array1.zip(array2)
#⇒ [[1, 0], [0, 0], [1, 1], [0, 0], [1, 1], [1, 0]]
array1.zip(array2).count { |v1, v2| v1 == v2 && v1 == 1 }
#⇒ 2

或(@engineersmnky的信用):

array1.zip(array2).count { |v1, v2| v1 & v2 == 1 }

甚至更好(归功于@Stefan):

array1.zip(array2).count { |values| values.all?(1) }

array1.
  zip(array2).
  reject { |v1, v2| v1 == 0 || v2 == 0 }.
  count
#⇒ 2

旁注:大写Array1声明常量。要声明变量,请改用array1

答案 1 :(得分:1)

i

的索引Array1[i] == 1 && Array2[i] == 1的数量
Array1.each_index.count { |i| Array1[i] == 1 && Array2[i] == 1  }
  #=> 2

i

的索引数组Array1[i] == 1 && Array2[i] == 1
Array1.each_index.select { |i| Array1[i] == 1 && Array2[i] == 1  }
  #=> [2, 4]

i

的索引Array1[i] == Array2[i]的数量
Array1.each_index.count { |i| Array1[i] == Array2[i] }
  #=> 4

答案 2 :(得分:0)

如果你想建立一个新的数组来跟踪一个匹配upvotes的索引:

a1 = [1,0,1,0,1,1]
a2=  [0,0,1,0,1,0]
p [a1, a2].transpose.map {|x| x.reduce(:&)}

#=> [0, 0, 1, 0, 1, 0]

仅计算,这是另一种方式:

a1 = [1,0,1,0,1,1]
a2=  [0,0,1,0,1,0]

votes = 0
a1.each_with_index do |a1, idx|
  votes +=1 if (a1 + a2[idx]) == 2
end

p votes #=> 2

在一行中:

a1.each_with_index { |a1, idx| votes += 1 if (a1 + a2[idx]) == 2 }
相关问题