Calling elements in an array

Hey everyone

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.

Any ideas?

Here is my code

numbers = [1,2,3,4,5,6]

2.times do
(rand*6).to_i

puts numbers [rand*6]

end

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".

Awesome, thank you so much :grin:

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

That approach solves the question.
However, as we are dealing with ruby, it can be written much more elegant.

numbers = [1,2,3,4,5,6]

random_number = -> { numbers[rand*6] }

picked_numbers =  Array.new(2){ random_number[] }

if picked_numbers.uniq.size == 1 
      print   "Pair  "
else
      print    "You Lost  "
end 
puts  "--> #{ picked_numbers } "

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.