我试图创建一个循环,当随机数匹配输入的相同索引时,值会发生变化,并为每个后续循环保持这种状态。
input = gets.chomp
tries_left = 12
while(tries_left > 0)
tries_left -= 1
computer = 4.times.map do rand(0..6) end.join
if computer[0] == input[0]
computer[0] = input[0]
end
end
在第一个循环之后的代码中,存储到input [0]的值重置。
computer = 4.times.map do rand(0..6) end.join
input = gets.chomp
tries_left = 12
while(tries_left > 0)
tries_left -= 1
if computer[0] == input[0]
computer[0] = input[0]
end
如果我将计算机带出这样的循环,它每次都会生成相同的随机数。除了已经匹配的东西之外,我每次都需要它来生成新的数字。
答案 0 :(得分:1)
如果你使myEARApp.ear
- myWarApp.war
-- a lot of libs from the war module
-- myEJBmodule.jar
-- myAdditionalJarModule.jar
- lib/
-- only a few extra jar modules referenced in ear/pom.xml
-- missing: logback, ehcache, etc.
- myEJBmodule.jar
- myAdditionalJarModule.jar
- otherDependencyOfmyAdditionalJarModule.jar
成为一个字符串数组,你可以freeze
来防止它进一步修改,然后replace
计算机中的内容与它不匹配时指数:
computer
然后当你运行脚本时:
input = gets.chomp
tries_left = 12
computer = Array.new(4) { '' }
# setting the srand to 1234, the next 48 calls to 'rand(0..6)' will always
# result in the following sequence:
# 3, 6, 5, 4, 4, 0, 1, 1, 1, 2, 6, 3, 6, 4, 4, 2, 6, 2, 0, 0, 4, 5, 0, 1,
# 6, 6, 2, 0, 3, 4, 5, 2, 6, 2, 3, 3, 0, 1, 3, 0, 3, 2, 3, 4, 1, 3, 3, 3
# this is useful for testing things are working correctly,
# but take it out for 'live' code
srand 1234
while tries_left > 0
# no need to keep iterating if we've generated all the correct values
if computer.all?(&:frozen?)
puts "won #{computer.inspect} in #{12 - tries_left} tries"
break
end
tries_left -= 1
computer.each.with_index do |random, index|
# generate a new random number here unless they guessed correctly previously
random.replace(rand(0..6).to_s) unless random.frozen?
# if they've guessed the new random number, mark the string so they we
# don't update it
random.freeze if random == input[index]
end
puts "#{computer.inspect} has #{computer.count(&:frozen?)} correct numbers"
end