I have the following problem:
- There is an array that consists of 6 numbers, each two digits at maximum.
- Y is an array whose i th element is the sum of the first i +1 elements of the first array.
- Accept a numerical input via keyboard. If it matches one of the numbers in Y display a message; If not, restart the program.
This is the algorithm that I am thinking:
- Initialize empty array [x] & [y]
- 6.times.map{ Random.rand(1..99) }
- Add numbers using each do?
- Store in array [y ]
- Compare input to == array [y]
- If any instance matches display msg else restart
I would be really grateful for any guidance or help with this problem.
loop do
x = Array.new(6){rand(99)}
y = []
x.each{|k| y.push(k + y.last.to_i)}
y.shift
break if y.include?(gets.to_i)
end
puts 'message'
Here's a quick stab at your problem.
def check_number_in_array
x = Array.new(6)
y = []
begin
x.collect! { rand(99) }
y.clear
sum = 0
x.each do |i|
sum = sum+i
y << sum
end
gets
# The following lines are just for "debugging"
print "x = [ "
x.each {|i| print i, " "}
print "]\ny = [ "
y.each {|i| print i, " "}
print "]\n"
end while !y.include?($_.to_i)
puts "Good guess!"
end
精彩评论