Guess the number/With feedback (player): Difference between revisions
Content added Content deleted
(→{{header|Ruby}}: Added example using bsearch, the binary search method.) |
|||
Line 1,826: | Line 1,826: | ||
guessing 29 too low |
guessing 29 too low |
||
guessing 30 found the number in 7 turns.</pre> |
guessing 30 found the number in 7 turns.</pre> |
||
Since Ruby 2.0 it can be done actually using a binary search (output as above): |
|||
<lang ruby>r = (1..100) |
|||
secret = rand(r) |
|||
turns = 0 |
|||
puts "Guess a number between #{r.min} ans #{r.max}" |
|||
r.bsearch do |guess| # bsearch works on ranges |
|||
turns += 1 |
|||
low_high = secret <=> guess # -1, 0, or 1 |
|||
msg = ["found the number in #{turns} turns","too low", "too high"][low_high] |
|||
puts "Guessing #{guess} \t #{msg}" |
|||
low_high |
|||
end |
|||
<lang> |
|||
=={{header|Rust}}== |
=={{header|Rust}}== |