https://github.com/akkartik/mu/blob/main/linux/advent2020/5a.mu
 1 # https://adventofcode.com/2020/day/5
 2 #
 3 # To run (on Linux):
 4 #   $ git clone https://github.com/akkartik/mu
 5 #   $ cd mu
 6 #   $ ./translate advent2020/5a.mu
 7 #   $ ./a.elf < input
 8 #
 9 # You'll need to register to download the 'input' file for yourself.
10 
11 fn main -> _/ebx: int {
12   var line-storage: (stream byte 0x10)  # 16 bytes is enough
13   var line/edx: (addr stream byte) <- address line-storage
14   var max-seat-id/edi: int <- copy 0
15   {
16     # read line from stdin
17     clear-stream line
18     read-line-from-real-keyboard line
19     print-stream-to-real-screen line
20     # if line is empty (not even a newline), quit
21     var done?/eax: boolean <- stream-empty? line
22     compare done?, 0/false
23     break-if-!=
24     # process line
25     var seat-id/eax: int <- convert-from-binary line
26     compare seat-id, max-seat-id
27     {
28       break-if-<=
29       max-seat-id <- copy seat-id
30     }
31     loop
32   }
33   print-int32-decimal 0, max-seat-id
34   print-string 0, "\n"
35   return 0
36 }
37 
38 fn convert-from-binary in: (addr stream byte) -> _/eax: int {
39   var result/edi: int <- copy 0
40   var i/ecx: int <- copy 9  # loop counter and also exponent
41   {
42     compare i, 0
43     break-if-<
44     var c/eax: byte <- read-byte in
45 #?     print-string 0, "char: "
46 #?     {
47 #?       var c2/eax: int <- copy c
48 #?       print-int32-hex 0, c2
49 #?     }
50 #?     print-string 0, "\n"
51     var bit/edx: int <- copy 0
52     {
53       compare c, 0x42/B
54       break-if-!=
55       bit <- copy 1
56     }
57     {
58       compare c, 0x52/R
59       break-if-!=
60       bit <- copy 1
61     }
62 #?     print-string 0, "bit: "
63 #?     print-int32-decimal 0, bit
64 #?     print-string 0, "\n"
65     var bit-value/eax: int <- repeated-shift-left bit, i
66 #?     print-string 0, "bit value: "
67 #?     print-int32-decimal 0, bit-value
68 #?     print-string 0, "\n"
69     result <- add bit-value
70 #?     print-string 0, "result: "
71 #?     print-int32-decimal 0, result
72 #?     print-string 0, "\n"
73     i <- decrement
74     loop
75   }
76   print-int32-decimal 0, result
77   print-string 0, "\n"
78   return result
79 }