]> gitweb.factorcode.org Git - factor.git/blob - extra/rosetta-code/look-and-say/look-and-say.factor
Switch to https urls
[factor.git] / extra / rosetta-code / look-and-say / look-and-say.factor
1 ! Copyright (c) 2012 Anonymous
2 ! See https://factorcode.org/license.txt for BSD license.
3 USING: kernel make math math.parser sequences ;
4 IN: rosetta-code.look-and-say
5
6 ! https://rosettacode.org/wiki/Look-and-say_sequence
7
8 ! Sequence Definition
9 ! * Take a decimal number
10 ! * Look at the number, visually grouping consecutive runs of
11 !   the same digit.
12 ! * Say the number, from left to right, group by group; as how
13 !   many of that digit there are - followed by the digit grouped.
14 !   This becomes the next number of the sequence.
15
16 ! The sequence is from John Conway, of Conway's Game of Life fame.
17
18 ! An example:
19 ! * Starting with the number 1, you have one 1 which produces 11.
20 ! * Starting with 11, you have two 1's i.e. 21
21 ! * Starting with 21, you have one 2, then one 1 i.e. (12)(11) which becomes 1211
22 ! * Starting with 1211 you have one 1, one 2, then two 1's i.e. (11)(12)(21) which becomes 111221
23
24 ! Task description
25
26 ! Write a program to generate successive members of the look-and-say sequence.
27
28 : (look-and-say) ( str -- )
29     unclip-slice swap [ 1 ] 2dip [
30         2dup = [ drop [ 1 + ] dip ] [
31             [ [ number>string % ] dip , 1 ] dip
32         ] if
33     ] each [ number>string % ] [ , ] bi* ;
34
35 : look-and-say ( str -- str' )
36     [ (look-and-say) ] "" make ;