Reputation: 1425
I am trying to solve some problems in ruby get a hold. I am trying compare two arrays with each other.
Array1 = [1,0,1,0,1,1]
Array2= [0,0,1,0,1,0]
I am getting this input from the user. Then I am comparing the votes. If both persons have upvoted 1
at same index, I am trying increment an empty array by 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
I actually want to compare avotes
with bvotes
and then increment empty array by 1. I need a little help
Upvotes: 0
Views: 147
Reputation: 121000
You can use Array#zip
and Enumerable#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
or (credits to @engineersmnky):
array1.zip(array2).count { |v1, v2| v1 & v2 == 1 }
or even better (credits to @Stefan):
array1.zip(array2).count { |values| values.all?(1) }
or
array1.
zip(array2).
reject { |v1, v2| v1 == 0 || v2 == 0 }.
count
#⇒ 2
Sidenote: capitalized Array1
declares a constant. To declare a variable, use array1
instead.
Upvotes: 4
Reputation: 110675
The number of indices i
for which Array1[i] == 1 && Array2[i] == 1
is
Array1.each_index.count { |i| Array1[i] == 1 && Array2[i] == 1 }
#=> 2
The array of indices i
for which Array1[i] == 1 && Array2[i] == 1
is
Array1.each_index.select { |i| Array1[i] == 1 && Array2[i] == 1 }
#=> [2, 4]
The number of indices i
for which Array1[i] == Array2[i]
is
Array1.each_index.count { |i| Array1[i] == Array2[i] }
#=> 4
Upvotes: 1
Reputation: 11193
If you want to build a new array tracking the index where there is a match of 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]
For just counting, this is another way:
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
In one line:
a1.each_with_index { |a1, idx| votes += 1 if (a1 + a2[idx]) == 2 }
Upvotes: 0