solve_sequence.sf 549 B

12345678910111213141516171819202122232425
  1. #!/usr/bin/ruby
  2. # Encode a sequence of n numbers into a polynomial of, at most, degree n-1.
  3. # See also:
  4. # https://yewtu.be/watch?v=4AuV93LOPcE
  5. # https://en.wikipedia.org/wiki/Polynomial_interpolation
  6. func solve_seq(arr, offset=0) {
  7. var poly = Poly()
  8. var x = Poly(1)-offset
  9. Inf.times {|k|
  10. poly += (arr[0] * binomial(x, k))
  11. arr = arr.diffs
  12. break if arr.all { .is_zero }
  13. }
  14. poly
  15. }
  16. say solve_seq(20.of { _**2 }) # x^2
  17. say solve_seq(20.of { _**2 }.acc) # 1/3*x^3 + 1/2*x^2 + 1/6*x