Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env lua
- ------------------------------------------------------------------------
- -- $Id: guessseq,v 1.3 2022/07/16 12:40:36 elias Exp $
- -- Try to guess next number in a sequence
- ------------------------------------------------------------------------
- function checkrow(row)
- -- Check if all numbers in a sequences are equal
- local first = row[1]
- for i = 2, #row do
- if row[i] ~= first then return false end
- end
- return true
- end
- function diffrow(row)
- -- Calculate difference sequence
- local next = {}
- for i = 1, #row-1 do
- next[#next+1] = row[i+1] - row[i]
- end
- return next
- end
- function copyrow(row)
- -- Helper function: copy sequence to a new sequence
- -- Convery everything to an interger
- local cpy = {}
- for k, v in ipairs(row) do
- cpy[k] = math.tointeger(v)
- end
- return cpy
- end
- function guessseq(row)
- -- Guess the next number in the sequence
- -- This works for all polynomial sequences
- local rows = {}
- row = copyrow(row)
- repeat
- rows[#rows+1] = copyrow(row)
- row = diffrow(row)
- until checkrow(rows[#rows])
- local power = #rows
- rows[power][#rows[power]+1] = rows[power][1]
- for i = power - 1, 1, -1 do
- rows[i][#rows[i]+1] = rows[i][#rows[i]] + rows[i+1][#rows[i+1]]
- end
- return rows[1], rows[1][#rows[1]]
- end
- function fromarg()
- -- Sequence is given as command line arguments
- local guess, num = guessseq(copyrow(arg))
- print(table.concat(guess, " "))
- end
- function interactive()
- -- Interactive mode
- while true do
- -- Give a prompt and read sequence
- io.output():write("guessseq> ")
- local line = io.input():read("l")
- -- Exit on EOF
- if not line then break end
- -- Parse numbers in the line
- local numbers = {}
- for n in string.gmatch(line, "(-?%d+)") do
- numbers[#numbers+1] = math.tointeger(n)
- end
- -- Give solution
- print(table.concat(guessseq(numbers), " "))
- end
- end
- -- Main program
- if #arg > 0 then
- fromarg()
- else
- interactive()
- print()
- end
- -- Code is prosa, not poetry.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement