Boustrophedon transform

func boustrophedon_transform(seq) {
    func T(k,n) is cached {
        return seq[k] if (n == 0)
        T(k, n-1) + T(k-1, k-n)
    }
    var bt = seq.range.map {|n| T(n,n) }
    T.uncache
    return bt
}

const N = 100   # n terms

[
    '1 followed by 0\'s A000111', Math.seq(1,{0}),
    'All-1\'s           A000667', Math.seq({1}),
    '(-1)^n             A062162', Math.seq({|_,k| (-1)**(k+1) }),
    'Primes             A000747', Math.seq(2,{ .tail.next_prime }),
    'Fibbonaccis        A000744', Math.seq(1,1,{ .last(2).sum }),
    'Factorials         A230960', Math.seq(1,{|a,k| a.last * (k-1) }),
].each_slice(2, {|name, seq|
    var bt = boustrophedon_transform(seq.first(N))
    say "\n#{name}:\n#{bt.first(15).join(' ')}"
    var v = bt[N-1]
    say ("#{N}th term: ", Str(v).first(20), '..', Str(v).last(20), " (%s digits)" % v.len)
})

Output:

Last updated

Was this helpful?