equator.bear equator.bear - 7 months ago 9
Ruby Question

How do I compare integer indexes in arrays when there are duplicate values?

First, some necessary background. I'm trying to make a number-based version of the game Mastermind as a way of learning to code in Ruby. My code basically works like this:


  1. The computer generates an array (
    @computer_sequence
    ) of 4 random numbers from 1-5

  2. The user enters a 4 digit sequence, which winds up in an array called
    @user_array
    .

  3. A method, called
    compare
    , iterates through
    @user_array
    , comparing the value and index of each number to those in
    @computer_sequence.
    The program then tells the user how many of their numbers have the correct value and the correct position, or how many numbers have the correct value only.



The problem: If there are multiple instances of a number in an array, they get the same index, right? Like if I have the array
[1, 3, 3, 4]
, the number three has an index of 1, even though there are two 3s. For this program to work, though, each number has to have a unique position (is index even the word I want here?) in the array, even if the number occurs multiple times. Does that make sense?

Also, here's the code for the
compare
method:

def compare
value_only = 0
value_and_place = 0
puts "The computer's values are: #{@computer_sequence}"
puts "The user's values are: #{@user_array}"


@user_array.each do |candidate|
@computer_sequence.each do |computer_number|
if candidate == computer_number && @user_array.index(candidate) == @computer_sequence.index(computer_number)
value_and_place +=1
elsif candidate == computer_number && @user_array.index(candidate) != @computer_sequence.index(computer_number)
value_only +=1
end
end
end

Answer

You can pass in the index value to your loop for each candidate using the each_with_index method. So when the first 3 is passed in, index will be 1 and when the second 3 is passed in, index will be 2.

The problem with using .index(candidate) is it returns the first index.

Try this:

@user_array.each_with_index do |candidate, index|
    @computer_sequence.each do |computer_number|
        if candidate == computer_number && candidate == @computer_sequence[index]
            value_and_place +=1
        elsif candidate == computer_number && candidate != @computer_sequence[index]
            value_only +=1
        end
    end
end
Comments