Motzkin numbers

Built-in:

say 50.of { .motzkin }

Motzkin's triangle (the Motzkin numbers are on the hypotenuse of the triangle):

func motzkin_triangle(num, callback) {
    var row = []
    { |n|
        row = [0, 1, {|i| row[i+2] + row[i] + row[i+1] }.map(0 .. n-3)..., 0]
        callback(row.grep{ .> 0 })
    } << 2..(num+1)
}

motzkin_triangle(10, {|row|
    row.map { "%4s" % _ }.join(' ').say
})

Output:

   1
   1    1
   1    2    2
   1    3    5    4
   1    4    9   12    9
   1    5   14   25   30   21
   1    6   20   44   69   76   51
   1    7   27   70  133  189  196  127
   1    8   35  104  230  392  518  512  323
   1    9   44  147  369  726 1140 1422 1353  835

Task:

Output:

Last updated

Was this helpful?