Guess the number/With feedback: Difference between revisions
Content added Content deleted
Line 2,153: | Line 2,153: | ||
Your guess: 57 |
Your guess: 57 |
||
You got it in 6 tries. |
You got it in 6 tries. |
||
=={{header|jq}}== |
|||
{{works with|jq}} |
|||
'''Also works with gojq, the Go implementation of jq.''' |
|||
In the following, a time-based PRNG is used as that is sufficient for |
|||
the task. For a different PRNG, see e.g. [[Guess_the_number#jq]] |
|||
<syntaxhighlight lang=jq> |
|||
# $min and $max can be specified on the command line but for illustrative purposes: |
|||
def minmax: [0, 20]; |
|||
# low-entropy PRNG in range($a;$b) i.e. $a <= prng < $b |
|||
# (no checking) |
|||
def prng($a;$b): $a + ((now * 1000000 | trunc) % ($b - $a) ); |
|||
def play: |
|||
# extract a number if possible |
|||
def str2num: |
|||
try tonumber catch null; |
|||
minmax as [$min, $max] |
|||
| prng($min; $max) as $number |
|||
| "The computer has chosen a whole number between \($min) and \($max) inclusive.", |
|||
"Please guess the number or type q to quit:", |
|||
(label $out |
|||
| foreach inputs as $guess (null; |
|||
if $guess == "q" then null, break $out |
|||
else ($guess|str2num) as $g |
|||
| if $g == null or $g < 0 then "Please enter a non-negative integer or q to quit" |
|||
elif $g < $min or $g > $max then "That is out of range. Try again" |
|||
elif $g > $number then "Too high" |
|||
elif $g < $number then "Too low" |
|||
else true, break $out |
|||
end |
|||
end) |
|||
| if type == "string" then . |
|||
elif . == true then "Spot on!", "Let's start again.\n", play |
|||
else empty |
|||
end ); |
|||
play |
|||
</syntaxhighlight> |
|||
'''Transcript:''' |
|||
<pre> |
|||
$ jq -nRr -f guess-the-number-with-feedback.jq |
|||
The computer has chosen a whole number between 0 and 20 inclusive. |
|||
Please guess the number or type q to quit: |
|||
10 |
|||
Too low |
|||
16 |
|||
Too high |
|||
14 |
|||
Too high |
|||
12 |
|||
Too high |
|||
11 |
|||
Spot on! |
|||
Let's start again. |
|||
The computer has chosen a whole number between 0 and 20 inclusive. |
|||
Please guess the number or type q to quit: |
|||
19 |
|||
Too high |
|||
q |
|||
Please enter a non-negative integer or q to quit |
|||
q |
|||
$</pre> |
|||
=={{header|Julia}}== |
=={{header|Julia}}== |