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:
- The computer generates an array (
@computer_sequence
) of 4 random numbers from 1-5 - The user enters a 4 digit sequence, which winds up in an array called
@user_array
. - 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