]> gitweb.factorcode.org Git - factor.git/blob - extra/rosetta-code/number-reversal/number-reversal.factor
factor: Move math.ranges => ranges.
[factor.git] / extra / rosetta-code / number-reversal / number-reversal.factor
1 ! Copyright (c) 2012 Anonymous
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: formatting io kernel math math.parser ranges
4 namespaces random sequences strings ;
5 IN: rosetta-code.number-reversal
6
7 ! http://rosettacode.org/wiki/Number_reversal_game
8
9 ! Given a jumbled list of the numbers 1 to 9 that are definitely
10 ! not in ascending order, show the list then ask the player how
11 ! many digits from the left to reverse. Reverse those digits, then
12 ! ask again, until all the digits end up in ascending order.
13
14 ! The score is the count of the reversals needed to attain the
15 ! ascending order.
16
17 ! Note: Assume the players input does not need extra validation.
18
19 : make-jumbled-array ( -- sorted jumbled )
20     CHAR: 1 CHAR: 9 [a..b] [ 1string ] map dup clone randomize
21     [ 2dup = ] [ randomize ] while ;
22
23 SYMBOL: trials
24
25 : prompt ( jumbled -- n )
26     trials get "#%2d: " printf
27     ", " join write
28     "   Flip how many? " write flush
29     readln string>number ;
30
31 : game-loop ( sorted jumbled -- )
32     2dup = [
33         2drop trials get
34         "\nYou took %d attempts to put the digits in order!\n" printf
35         flush
36     ] [
37         trials [ 1 + ] change
38         dup dup prompt head-slice reverse! drop
39         game-loop
40     ] if ;
41
42 : play ( -- )
43     0 trials set
44     make-jumbled-array game-loop ;