interplane.Get Omega
Read in your language

omega-rosetta

aien-dev/omega-rosetta

Brought by drakestapleton

branch main Branches Tags History

omega-rosetta / tasks / knapsack-problem-unbounded / knapsack-problem-unbounded.om

88 lines · 1902 bytes Raw Blame History
1note Rosetta Code task "Knapsack problem/Unbounded": https://rosettacode.org/wiki/Knapsack_problem/Unbounded
2note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3om2
4text nl "\n"
5text sp " "
6text minus "-"
7text thead "panacea ichor gold value weight volume\n"
8text ttenth "/10 "
9text tthou "/1000\n"
10note emit writes every byte of a to stdout; a short write is retried, an error exits 1
11fn emit a view uchar * to void
12o = ulong 0
13while lt o len a bound 4096
14k = write 1 a o sub len a o
15if le k 0
16exit 1
17end
18o = add o ulong k
19end
20end
21note emitu writes n in decimal; 20 digits hold every ulong
22fn emitu n ulong to void
23d = new uchar 20 0
24i = ulong 20
25v = n
26while true bound 20
27i = sub i 1
28put d i uchar add rem v 10 48
29v = div v 10
30if eq v 0
31break
32end
33end
34emit part d i sub 20 i
35end
36note the weights are in tenths (0.3, 0.2, 2.0 -> 3, 2, 20; limit 25 -> 250) and the volumes in
37note thousandths (0.025, 0.015, 0.002 -> 25, 15, 2; limit 0.25 -> 250), so all arithmetic is exact;
38note values are 3000, 1800 and 2500; every count that fits is tried (at most 11 * 17 * 13 cases)
39fn fits a ulong b ulong c ulong to bool
40w = add add mul a 3 mul b 2 mul c 20
41v = add add mul a 25 mul b 15 mul c 2
42ret and le w 250 le v 250
43end
44fn value a ulong b ulong c ulong to ulong
45ret add add mul a 3000 mul b 1800 mul c 2500
46end
47fn row a ulong b ulong c ulong to void
48emitu a
49emit sp
50emitu b
51emit sp
52emitu c
53emit sp
54emitu value a b c
55emit sp
56emitu add add mul a 3 mul b 2 mul c 20
57emit ttenth
58emitu add add mul a 25 mul b 15 mul c 2
59emit tthou
60end
61note pass 1 finds the best value, pass 2 prints every combination that reaches it
62fn main to int
63best = ulong 0
64for a ulong 11
65for b ulong 17
66for c ulong 13
67if fits a b c
68if gt value a b c best
69best = value a b c
70end
71end
72end
73end
74end
75emit thead
76for a ulong 11
77for b ulong 17
78for c ulong 13
79if fits a b c
80if eq value a b c best
81row a b c
82end
83end
84end
85end
86end
87ret 0
88end