omega-rosetta
aien-dev/omega-rosetta
Brought by drakestapleton
omega-rosetta / tasks / population-count / population-count.om
| 1 | note Rosetta Code task "Population count": https://rosettacode.org/wiki/Population_count |
| 2 | note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 3 | om2 |
| 4 | text nl "\n" |
| 5 | text sp " " |
| 6 | text pw "popcount of 3^0 .. 3^29:" |
| 7 | text evil "first 30 evil numbers: " |
| 8 | text odious "first 30 odious numbers:" |
| 9 | note emit writes every byte of a to stdout; a short write is retried, an error exits 1 |
| 10 | fn emit a view uchar * to void |
| 11 | o = ulong 0 |
| 12 | while lt o len a bound 4096 |
| 13 | k = write 1 a o sub len a o |
| 14 | if le k 0 |
| 15 | exit 1 |
| 16 | end |
| 17 | o = add o ulong k |
| 18 | end |
| 19 | end |
| 20 | note emitu writes n in decimal; 20 digits hold every ulong |
| 21 | fn emitu n ulong to void |
| 22 | d = new uchar 20 0 |
| 23 | i = ulong 20 |
| 24 | v = n |
| 25 | while true bound 20 |
| 26 | i = sub i 1 |
| 27 | put d i uchar add rem v 10 48 |
| 28 | v = div v 10 |
| 29 | if eq v 0 |
| 30 | break |
| 31 | end |
| 32 | end |
| 33 | emit part d i sub 20 i |
| 34 | end |
| 35 | note Kernighan: n & (n - 1) clears the lowest set bit |
| 36 | fn popc n ulong to ulong |
| 37 | c = ulong 0 |
| 38 | v = n |
| 39 | while gt v 0 bound 64 |
| 40 | v = and v sub v 1 |
| 41 | c = add c 1 |
| 42 | end |
| 43 | ret c |
| 44 | end |
| 45 | note evil numbers have an even population count, odious ones an odd count |
| 46 | fn list want ulong to void |
| 47 | c = ulong 0 |
| 48 | n = ulong 0 |
| 49 | while lt c 30 bound 100 |
| 50 | if eq rem popc n 2 want |
| 51 | emit sp |
| 52 | emitu n |
| 53 | c = add c 1 |
| 54 | end |
| 55 | n = add n 1 |
| 56 | end |
| 57 | emit nl |
| 58 | end |
| 59 | fn main to int |
| 60 | emit pw |
| 61 | p = ulong 1 |
| 62 | for i ulong 30 |
| 63 | emit sp |
| 64 | emitu popc p |
| 65 | p = mul p 3 |
| 66 | end |
| 67 | emit nl |
| 68 | emit evil |
| 69 | list 0 |
| 70 | emit odious |
| 71 | list 1 |
| 72 | ret 0 |
| 73 | end |