Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/omega-rosetta/blob/main/tasks/binary-search/binary-search.om # omega-rosetta aien-dev/omega-rosetta Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `omega-rosetta / tasks / binary-search / binary-search.om` 98 lines ยท 1648 bytes Raw Blame History 1 note Rosetta Code task "Binary search": https://rosettacode.org/wiki/Binary_search 2 note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 3 om2 4 text nl "\n" 5 text minus "-" 6 text found " found at index " 7 text nf " not found" 8 note emit writes every byte of a to stdout; a short write is retried, an error exits 1 9 fn emit a view uchar * to void 10 o = ulong 0 11 while lt o len a bound 4096 12 k = write 1 a o sub len a o 13 if le k 0 14 exit 1 15 end 16 o = add o ulong k 17 end 18 end 19 note emitu writes n in decimal; 20 digits hold every ulong 20 fn emitu n ulong to void 21 d = new uchar 20 0 22 i = ulong 20 23 v = n 24 while true bound 20 25 i = sub i 1 26 put d i uchar add rem v 10 48 27 v = div v 10 28 if eq v 0 29 break 30 end 31 end 32 emit part d i sub 20 i 33 end 34 note emiti writes a signed n; the magnitude is taken as a ulong so the minimum long cannot overflow 35 fn emiti n long to void 36 if lt n 0 37 emit minus 38 emitu add bitcast ulong not n 1 39 else 40 emitu ulong n 41 end 42 end 43 note returns the index of x in the sorted a, or -1; 16 elements need at most 5 halvings 44 fn bsearch a view long 16 x long to long 45 lo = ulong 0 46 hi = ulong 16 47 while lt lo hi bound 16 48 mid = add lo shr sub hi lo 1 49 v = get a mid 50 if eq v x 51 ret long mid 52 end 53 if lt v x 54 lo = add mid 1 55 else 56 hi = mid 57 end 58 end 59 ret -1 60 end 61 fn query a view long 16 x long to void 62 r = bsearch a x 63 emiti x 64 if ge r 0 65 emit found 66 emiti r 67 else 68 emit nf 69 end 70 emit nl 71 end 72 fn main to int 73 a = new long 16 0 74 put a 0 -40 75 put a 1 -12 76 put a 2 -3 77 put a 3 0 78 put a 4 2 79 put a 5 5 80 put a 6 8 81 put a 7 13 82 put a 8 21 83 put a 9 34 84 put a 10 55 85 put a 11 89 86 put a 12 144 87 put a 13 233 88 put a 14 377 89 put a 15 610 90 query a -40 91 query a 0 92 query a 21 93 query a 610 94 query a 7 95 query a 1000 96 query a -41 97 ret 0 98 end