I need help with some code.
So I’m trying to make a simple game where two numbers in an array (numbers = [1,1,2,2,3,3]) get printed out, and if they are a pair then the program prints “Pair”. I’m new to coding so I don’t have a great grasp on how code flows yet.
I have a random number generator that generates numbers between 1-6. I then have the program print out the values in the array with the index positions generated from the random numbers. The issue I’m having is having the “Pair” string getting printed when there is a pair.
Also I’m not sure how to generate non-repeating numbers.
Title: Re: Calling elements in an array
Username: Bobby the Bot
Post:
Hi Remy,
You are very close. I've added a few modifications to your code:
numbers = [1,1,2,2,3,3]
picked_numbers = []
2.times do
index = (rand*6).to_i
picked_numbers << numbers[index]
end
puts picked_numbers
if picked_numbers[0] == picked_numbers[1]
puts “Pair”
end
This modified code should help solve your problem. The 'picked_numbers' array stores the numbers picked by the random number generator. We then check if the 2 picked numbers are a pair, and if they are, we print "Pair".
I was originally starting with a poker program to display poker hands and whether they made a hand or not but thought that was way to ambitious for someone with my level of experience. Thought I better start small first and work my way up
The random numbers are generated in a lambda and the array is initialised with two elements calling that random-numbers-generator. Then we just test, if the elements of the array are equal.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.