Home > Back-end >  check if the index of similar elements in two arrays are different
check if the index of similar elements in two arrays are different

Time:09-28

This is my first question on StackOverFlow! Please let me know if my question is not clear.

Here is what I have so far:

code = ["4", "4", "1", "1"]
guess = ["4", "4", "4", "1"]

@A = 0
@B = 0

code.each_with_index do |item, index|
  if item == guess[index]
    @A  = 1 
  elsif code.include?(guess[index]) 
    @B  = 1
  end
 print "\nA:#{@A} B:#{@B}"
end

I would like to increase @A by 1 if a number is in both arrays and in the same position (index). If the number is in both arrays but in different positions (index), increase @B by 1.

I should've gotten A:3 B:0 but I am getting A:3 B:1. In the code array, there is no third "4" so B shouldn't have increased by 1.

Is it because .include? doesn't work with duplicates in arrays? How can I fix this?

CodePudding user response:

This should work:

code = ["4", "4", "1", "1"]
guess = ["4", "4", "4", "1"]

visited = Array.new(guess.length) { false }

@A = 0
@B = 0

code.each_with_index do |item, index|
  if item == guess[index]
    @A  = 1
    @B -= 1 if visited[index]
    visited[index] = true
  elsif guess.each_index.any? { |idx| guess[idx] == item && !visited[idx] && visited[idx] = true  }
    @B  = 1
  end
end
print "\nA:#{@A} B:#{@B}"

Here, I am keeping track of already visited indexes in the guess array so that I don't count the same element in both @A and @B count.

CodePudding user response:

After each successful (individual) match between the code and guess, we must remove the matched elements from the equation.

For example, code = ['1', 2'] and guess = ['1', '1']. We get an exact match at index 0. If we remove the matched elements: code = ['2'] and guess = ['1'], we can clearly see that there is no further match.

If we had not removed the elements, then (in addition to the exact match) index 0 of code would match with index 1 of guess... which would wrongly result in @A = 1 and @B = 1. We do not want to use an already matched code element to match with a different guess element.

code = ["4", "4", "1", "1"]
guess = ["4", "4", "4", "1"]

unmatched_code = []
unmatched_guess = []

@A = 0
@B = 0

code.size.times do |i|
  if code[i] == guess[i]
    @A  = 1
  else
    unmatched_code << code[i]
    unmatched_guess << guess[i]
  end
end

unmatched_guess.each do |g|
  matched_at_index = unmatched_code.index(g)
  if matched_at_index
    @B  = 1
    unmatched_code.delete_at(matched_at_index)
  end
end
  •  Tags:  
  • ruby
  • Related