interplane.Get Omega
Read in your language

omega-rosetta

aien-dev/omega-rosetta

Brought by drakestapleton

branch main Branches Tags History

omega-rosetta / tasks / combinations-with-repetitions / combinations-with-repetitions.om

90 lines · 1690 bytes Raw Blame History
1note Rosetta Code task "Combinations with repetitions": https://rosettacode.org/wiki/Combinations_with_repetitions
2note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3om2
4text nl "\n"
5text sp " "
6text minus "-"
7text t0 "iced"
8text t1 "jam"
9text t2 "plain"
10text tcount "choices of 3 from 10 kinds: "
11global pick ulong 4
12note emit writes every byte of a to stdout; a short write is retried, an error exits 1
13fn emit a view uchar * to void
14o = ulong 0
15while lt o len a bound 4096
16k = write 1 a o sub len a o
17if le k 0
18exit 1
19end
20o = add o ulong k
21end
22end
23note emitu writes n in decimal; 20 digits hold every ulong
24fn emitu n ulong to void
25d = new uchar 20 0
26i = ulong 20
27v = n
28while true bound 20
29i = sub i 1
30put d i uchar add rem v 10 48
31v = div v 10
32if eq v 0
33break
34end
35end
36emit part d i sub 20 i
37end
38note nextm steps pick[0..k-1], a non-decreasing list of kinds 0..n-1, to the next one in lexicographic
39note order: raise the last pick below n-1 and set every pick after it to the same kind
40fn nextm k ulong n ulong to bool
41i = k
42while gt i 0 bound 4
43i = sub i 1
44if lt get pick i sub n 1
45v = add get pick i 1
46for x ulong sub k i
47put pick add i x v
48end
49ret true
50end
51end
52ret false
53end
54fn kind d ulong to void
55if eq d 0
56emit t0
57end
58if eq d 1
59emit t1
60end
61if eq d 2
62emit t2
63end
64end
65fn main to int
66note the two-doughnut choices from three kinds: C(3+2-1, 2) = 6
67put pick 0 0
68put pick 1 0
69while true bound 6
70kind get pick 0
71emit sp
72kind get pick 1
73emit nl
74if not nextm 2 3
75break
76end
77end
78note counted, not computed: C(10+3-1, 3) = 220 choices bound the loop
79put pick 0 0
80put pick 1 0
81put pick 2 0
82c = ulong 1
83while nextm 3 10 bound 220
84c = add c 1
85end
86emit tcount
87emitu c
88emit nl
89ret 0
90end