Advertisement
goebelmasse

Nächste Zahl einer gegebenen Zahlreihe erraten…

May 25th, 2023
1,168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.12 KB | None | 0 0
  1. #!/usr/bin/env lua
  2. ------------------------------------------------------------------------
  3. -- $Id: guessseq,v 1.3 2022/07/16 12:40:36 elias Exp $
  4. -- Try to guess next number in a sequence
  5. ------------------------------------------------------------------------
  6.  
  7.  
  8. function checkrow(row)
  9.    -- Check if all numbers in a sequences are equal
  10.    local first = row[1]
  11.    for i = 2, #row do
  12.       if row[i] ~= first then return false end
  13.    end
  14.    return true
  15. end
  16.  
  17.  
  18. function diffrow(row)
  19.    -- Calculate difference sequence
  20.    local next = {}
  21.    for i = 1, #row-1 do
  22.       next[#next+1] = row[i+1] - row[i]
  23.    end
  24.    return next
  25. end
  26.  
  27.  
  28. function copyrow(row)
  29.    -- Helper function: copy sequence to a new sequence
  30.    -- Convery everything to an interger
  31.    local cpy = {}
  32.    for k, v in ipairs(row) do
  33.       cpy[k] = math.tointeger(v)
  34.    end
  35.    return cpy
  36. end
  37.  
  38.  
  39. function guessseq(row)
  40.    -- Guess the next number in the sequence
  41.    -- This works for all polynomial sequences
  42.    local rows = {}
  43.    row = copyrow(row)
  44.    repeat
  45.       rows[#rows+1] = copyrow(row)
  46.       row = diffrow(row)
  47.    until checkrow(rows[#rows])
  48.    local power = #rows
  49.    rows[power][#rows[power]+1] = rows[power][1]
  50.    for i = power - 1, 1, -1 do
  51.       rows[i][#rows[i]+1] = rows[i][#rows[i]] + rows[i+1][#rows[i+1]]
  52.    end
  53.    return rows[1], rows[1][#rows[1]]
  54. end
  55.  
  56.  
  57. function fromarg()
  58.    -- Sequence is given as command line arguments
  59.    local guess, num = guessseq(copyrow(arg))
  60.    print(table.concat(guess, " "))
  61. end
  62.  
  63.  
  64. function interactive()
  65.    -- Interactive mode
  66.    while true do
  67.       -- Give a prompt and read sequence
  68.       io.output():write("guessseq> ")
  69.       local line = io.input():read("l")
  70.       -- Exit on EOF
  71.       if not line then break end
  72.       -- Parse numbers in the line
  73.       local numbers = {}
  74.       for n in string.gmatch(line, "(-?%d+)") do
  75.      numbers[#numbers+1] = math.tointeger(n)
  76.       end
  77.       -- Give solution
  78.       print(table.concat(guessseq(numbers), " "))
  79.    end
  80. end
  81.  
  82.  
  83. -- Main program
  84. if #arg > 0 then
  85.    fromarg()
  86. else
  87.    interactive()
  88.    print()
  89. end
  90.  
  91.  
  92. -- Code is prosa, not poetry.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement