如果使computer
字符串數組,可以freeze
,以防止進一步的修改,然後replace
在計算機中的內容時,它不匹配索引:
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
,然後當你運行腳本時:
$ echo 3654 | ruby example.rb
# ["3", "6", "5", "4"] has 4 correct numbers
# won ["3", "6", "5", "4"] in 1 tries
$ echo 3644 | ruby example.rb
# ["3", "6", "5", "4"] has 3 correct numbers
# ["3", "6", "4", "4"] has 4 correct numbers
# won ["3", "6", "4", "4"] in 2 tries
$ echo 3555 | ruby example.rb
# ["3", "6", "5", "4"] has 2 correct numbers
# ["3", "4", "5", "0"] has 2 correct numbers
# ["3", "1", "5", "1"] has 2 correct numbers
# ["3", "1", "5", "2"] has 2 correct numbers
# ["3", "6", "5", "3"] has 2 correct numbers
# ["3", "6", "5", "4"] has 2 correct numbers
# ["3", "4", "5", "2"] has 2 correct numbers
# ["3", "6", "5", "2"] has 2 correct numbers
# ["3", "0", "5", "0"] has 2 correct numbers
# ["3", "4", "5", "5"] has 3 correct numbers
# ["3", "0", "5", "5"] has 3 correct numbers
# ["3", "1", "5", "5"] has 3 correct numbers
這似乎是一個猜謎遊戲。上面的代碼應該做什麼?什麼可行,什麼不行?你可以用用戶輸入和期望的輸出顯示示例會話嗎? – Stefan