omega-rosetta
aien-dev/omega-rosetta
Brought by drakestapleton
omega-rosetta / tasks / pascals-triangle / pascals-triangle.om
| 1 | note Rosetta Code task "Pascal's triangle": https://rosettacode.org/wiki/Pascal's_triangle |
| 2 | note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 3 | om2 |
| 4 | text nl "\n" |
| 5 | text sp " " |
| 6 | text minus "-" |
| 7 | global row ulong 16 |
| 8 | note emit writes every byte of a to stdout; a short write is retried, an error exits 1 |
| 9 | fn emit a view uchar * to void |
| 10 | o = ulong 0 |
| 11 | while lt o len a bound 4096 |
| 12 | k = write 1 a o sub len a o |
| 13 | if le k 0 |
| 14 | exit 1 |
| 15 | end |
| 16 | o = add o ulong k |
| 17 | end |
| 18 | end |
| 19 | note emitu writes n in decimal; 20 digits hold every ulong |
| 20 | fn emitu n ulong to void |
| 21 | d = new uchar 20 0 |
| 22 | i = ulong 20 |
| 23 | v = n |
| 24 | while true bound 20 |
| 25 | i = sub i 1 |
| 26 | put d i uchar add rem v 10 48 |
| 27 | v = div v 10 |
| 28 | if eq v 0 |
| 29 | break |
| 30 | end |
| 31 | end |
| 32 | emit part d i sub 20 i |
| 33 | end |
| 34 | note each row comes from the one above in place, right to left: row[j] += row[j-1]; each row is |
| 35 | note indented so the triangle is centred, two columns per level |
| 36 | fn pascal n ulong to void |
| 37 | put row 0 1 |
| 38 | for r ulong n |
| 39 | for x ulong mul 2 sub sub n r 1 |
| 40 | emit sp |
| 41 | end |
| 42 | for j ulong add r 1 |
| 43 | if gt j 0 |
| 44 | emit sp |
| 45 | end |
| 46 | emitu get row j |
| 47 | end |
| 48 | emit nl |
| 49 | put row add r 1 1 |
| 50 | for x ulong r |
| 51 | j = sub r x |
| 52 | put row j add get row j get row sub j 1 |
| 53 | end |
| 54 | end |
| 55 | end |
| 56 | fn main to int |
| 57 | pascal 10 |
| 58 | ret 0 |
| 59 | end |