开发者

Adding Elements in a Array [closed]

开发者 https://www.devze.com 2023-03-15 13:07 出处:网络
It's difficult to tell what is being asked here. This ques开发者_Go百科tion is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. F
It's difficult to tell what is being asked here. This ques开发者_Go百科tion is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

I have the following problem:

  1. There is an array that consists of 6 numbers, each two digits at maximum.
  2. Y is an array whose i th element is the sum of the first i +1 elements of the first array.
  3. Accept a numerical input via keyboard. If it matches one of the numbers in Y display a message; If not, restart the program.

Adding Elements in a Array [closed]

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
0

精彩评论

暂无评论...
验证码 换一张
取 消