Download code

Jump to: navigation, search

Back to Look_and_say_sequence_(Lua)

Download for Windows: single file, zip

Download for UNIX: single file, zip, tar.gz, tar.bz2

look_and_say.lua

 1 -- The authors of this work have released all rights to it and placed it
 2 -- in the public domain under the Creative Commons CC0 1.0 waiver
 3 -- (http://creativecommons.org/publicdomain/zero/1.0/).
 4 -- 
 5 -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 6 -- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 7 -- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 8 -- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 9 -- CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
10 -- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11 -- SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12 -- 
13 -- Retrieved from: http://en.literateprograms.org/Look_and_say_sequence_(Lua)?oldid=12892
14 
15 function look_and_say(seed, reps)
16 
17   local function make_next(s)
18     local d = s:sub(1,1)
19     local say = ""
20     local count = 0
21 
22     for i=1,s:len()+1 do
23 
24       if s:sub(i,i) ~= d then
25         say = say .. count .. d
26         count = 0
27         d = s:sub(i,i) 
28       end
29 
30       count = count + 1
31     end
32 
33     return say 
34   end
35 
36   local seq = tostring(seed)
37   local last = seq
38 
39   for i=2,reps do
40     local next = make_next(last)
41     last = next
42     seq = seq .. "," .. next
43   end
44 
45   return seq
46 end
47 
48 function look_and_say_pat(seed, reps)
49   local seq = tostring(seed)
50   local last = seq
51 
52   for i=2,reps do
53 
54     local next = ""
55     while last:len() > 0 do
56       local c = last:sub(1, 1)
57       local match = last:match(c.."+")
58       next = next .. match:len() .. c
59       last = last:sub(match:len()+1, -1)
60     end
61 
62     last = next
63     seq = seq .. "," .. next
64   end
65 
66   return seq
67 end
68 function test(expected, actual)
69   return ((expected == actual) and "pass: "..expected or "fail: "..actual).."\n"
70 end
71 
72 io.write(test("1,11,21,1211,111221,312211,13112221,1113213211", look_and_say(1,8)))
73 io.write(test("3,13,1113,3113,132113,1113122113,311311222113", look_and_say(3,7)))
74 io.write(test("1,11,21,1211,111221,312211,13112221,1113213211", look_and_say_pat(1,8)))
75 io.write(test("3,13,1113,3113,132113,1113122113,311311222113", look_and_say_pat(3,7)))
76 


hijacker
hijacker
hijacker
hijacker