interplane.Get Omega
Read in your language

omega-mv

Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.

Brought by drakestapleton

branch main Branches Tags History

omega-mv / si / rosetta / tasks / equilibrium-index / equilibrium-index.om

122 lines · 2165 bytes Raw Blame History
1note Rosetta Code task "Equilibrium index": https://rosettacode.org/wiki/Equilibrium_index
2note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3om2
4text nl "\n"
5text sp " "
6text minus "-"
7text d1 "-7 1 5 2 -4 3 0"
8text d2 "2 4 6"
9text d3 "2 9 2"
10text d4 "1 -1 1 -1 1 -1 1"
11text tidx "equilibrium indices:"
12global vals long 16
13note emit writes every byte of a to stdout; a short write is retried, an error exits 1
14fn emit a view uchar * to void
15o = ulong 0
16while lt o len a bound 4096
17k = write 1 a o sub len a o
18if le k 0
19exit 1
20end
21o = add o ulong k
22end
23end
24note emitu writes n in decimal; 20 digits hold every ulong
25fn emitu n ulong to void
26d = new uchar 20 0
27i = ulong 20
28v = n
29while true bound 20
30i = sub i 1
31put d i uchar add rem v 10 48
32v = div v 10
33if eq v 0
34break
35end
36end
37emit part d i sub 20 i
38end
39note emiti writes a signed n; the magnitude is taken as a ulong so the minimum long cannot overflow
40fn emiti n long to void
41if lt n 0
42emit minus
43emitu add bitcast ulong not n 1
44else
45emitu ulong n
46end
47end
48note parse reads the decimal numbers in s (separated by spaces, an optional - sign) into vals and
49note returns how many; one pass over s, so the loop is bounded by len s
50fn parse s view uchar * to ulong
51n = ulong 0
52v = long 0
53sg = long 1
54dig = false
55for i ulong len s
56c = get s i
57if eq c 45
58sg = long -1
59else
60if and ge c 48 le c 57
61v = add mul v 10 long sub c 48
62dig = true
63else
64if dig
65put vals n mul sg v
66n = add n 1
67end
68v = long 0
69sg = long 1
70dig = false
71end
72end
73end
74if dig
75put vals n mul sg v
76n = add n 1
77end
78ret n
79end
80note show writes vals[0..n-1] separated by spaces, then a newline
81fn show n ulong to void
82for i ulong n
83if gt i 0
84emit sp
85end
86emiti get vals i
87end
88emit nl
89end
90note eqidx keeps the sum to the left and the sum to the right of i in one pass after the total
91fn eqidx n ulong to void
92tot = long 0
93for i ulong n
94tot = add tot get vals i
95end
96lsum = long 0
97emit tidx
98for i ulong n
99rsum = sub sub tot lsum get vals i
100if eq lsum rsum
101emit sp
102emitu i
103end
104lsum = add lsum get vals i
105end
106emit nl
107end
108fn main to int
109n = parse d1
110show n
111eqidx n
112n = parse d2
113show n
114eqidx n
115n = parse d3
116show n
117eqidx n
118n = parse d4
119show n
120eqidx n
121ret 0
122end