omega-rosetta
aien-dev/omega-rosetta
Brought by drakestapleton
omega-rosetta / tasks / longest-common-subsequence / longest-common-subsequence.om
| 1 | note Rosetta Code task "Longest common subsequence": https://rosettacode.org/wiki/Longest_common_subsequence |
| 2 | note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 3 | om2 |
| 4 | text nl "\n" |
| 5 | text sp " " |
| 6 | text a1 "thisisatest" |
| 7 | text b1 "testing123testing" |
| 8 | text a2 "1234" |
| 9 | text b2 "1224533324" |
| 10 | note emit writes every byte of a to stdout; a short write is retried, an error exits 1 |
| 11 | fn emit a view uchar * to void |
| 12 | o = ulong 0 |
| 13 | while lt o len a bound 4096 |
| 14 | k = write 1 a o sub len a o |
| 15 | if le k 0 |
| 16 | exit 1 |
| 17 | end |
| 18 | o = add o ulong k |
| 19 | end |
| 20 | end |
| 21 | note fill writes the (len a + 1) x (len b + 1) length table into t, row-major with width len b + 1; |
| 22 | note both lengths up to 63 |
| 23 | fn fill a view uchar * b view uchar * t edit ulong 4096 to void |
| 24 | w = add len b 1 |
| 25 | for i ulong len a |
| 26 | for j ulong len b |
| 27 | up = add mul i w add j 1 |
| 28 | x = add get t sub up 1 1 |
| 29 | if ne get a i get b j |
| 30 | x = get t up |
| 31 | l = get t add up sub w 1 |
| 32 | if lt x l |
| 33 | x = l |
| 34 | end |
| 35 | end |
| 36 | put t add up w x |
| 37 | end |
| 38 | end |
| 39 | end |
| 40 | note goup: the cell above is at least the cell to the left |
| 41 | fn goup t view ulong 4096 i ulong j ulong w ulong to bool |
| 42 | u = get t add mul sub i 1 w j |
| 43 | ret ge u get t add mul i w sub j 1 |
| 44 | end |
| 45 | note walk goes back from the corner of the table: a match is taken, otherwise the larger neighbour, |
| 46 | note the upper one on a tie. The subsequence is written into o back to front. |
| 47 | fn walk a view uchar * b view uchar * t view ulong 4096 o edit uchar 64 to void |
| 48 | w = add len b 1 |
| 49 | i = len a |
| 50 | j = len b |
| 51 | k = get t add mul i w j |
| 52 | while and gt i 0 gt j 0 bound 200 |
| 53 | if eq get a sub i 1 get b sub j 1 |
| 54 | k = sub k 1 |
| 55 | put o k get a sub i 1 |
| 56 | i = sub i 1 |
| 57 | j = sub j 1 |
| 58 | else |
| 59 | if goup t i j w |
| 60 | i = sub i 1 |
| 61 | else |
| 62 | j = sub j 1 |
| 63 | end |
| 64 | end |
| 65 | end |
| 66 | end |
| 67 | fn lcs a view uchar * b view uchar * to void |
| 68 | t = new ulong 4096 0 |
| 69 | fill a b t |
| 70 | o = new uchar 64 0 |
| 71 | n = get t add mul len a add len b 1 len b |
| 72 | walk a b t o |
| 73 | emit part o 0 n |
| 74 | emit nl |
| 75 | end |
| 76 | fn main to int |
| 77 | lcs a1 b1 |
| 78 | lcs a2 b2 |
| 79 | ret 0 |
| 80 | end |