aboutsummaryrefslogtreecommitdiffstats
path: root/examples/numbers.aup
diff options
context:
space:
mode:
authoreunhhu <[email protected]>2026-10-04 13:58:19 +0100
committereunhhu <[email protected]>2026-10-04 13:58:19 +0100
commit7340ba9af757b6f135dff9c51a193ba527f061b3 (patch)
tree955bb163aa584d52cf402fb123c901ec2271939c /examples/numbers.aup
parentfafed7edaf36ba18c200d395bd229d1f071cd409 (diff)
downloadaup-7340ba9af757b6f135dff9c51a193ba527f061b3.tar.gz
aup-7340ba9af757b6f135dff9c51a193ba527f061b3.zip
Count with for i in a .. b, break, nest fors and let an event's own lists (Pure 018)
Diffstat (limited to 'examples/numbers.aup')
-rw-r--r--examples/numbers.aup62
1 files changed, 62 insertions, 0 deletions
diff --git a/examples/numbers.aup b/examples/numbers.aup
new file mode 100644
index 0000000..3352993
--- /dev/null
+++ b/examples/numbers.aup
@@ -0,0 +1,62 @@
+# Numbers worked out in one event (Pure 018): a square root by Newton's
+# steps, stopping when they stop shrinking, and the best a knapsack holds,
+# its table an event's list.
+record Item {
+ id = 0
+ weight = 0
+ worth = 0
+}
+record Cell {
+ at = 0
+ best = 0
+}
+state items: list of Item by id
+state root = 0
+state steps = 0
+state packed = 0
+input stock = message {
+ id: u32
+ weight: u32
+ worth: u32
+}
+input sqrt = message {
+ x: number
+}
+input pack = message {
+ capacity: u32
+}
+
+on stock {
+ items.add(Item { id: stock.id, weight: stock.weight, worth: stock.worth })
+}
+
+on sqrt {
+ let r = if sqrt.x > 1 { sqrt.x } else { 1 }
+ steps = 0
+ for i in 0 .. 200 {
+ let next = (r + sqrt.x / r) / 2
+ if next >= r { break }
+ r = next
+ steps = steps + 1
+ }
+ root = r
+}
+
+on pack {
+ let table: list of Cell by at
+ for c in 0 .. pack.capacity + 1 {
+ table.add(Cell { at: c })
+ }
+ for it in items {
+ for k in 0 .. pack.capacity + 1 {
+ let c = pack.capacity - k
+ if c >= it.weight {
+ let with = table[c - it.weight].best + it.worth
+ if with > table[c].best { table[c].best = with }
+ }
+ }
+ }
+ packed = table[pack.capacity].best
+}
+
+view answer = "root {root} in {steps} steps, packed {packed}"