2020/c64/day01.asm

142 lines
2.7 KiB
NASM

// vim: filetype=kickass
* = * "Day 01"
//
// day01
//
// Destroys:
// a, x, y, $02..$04, $10..$1c, $20..$25, $fd..$fe, everything you've ever loved
//
.const input_pointer = $20
.const atoi_result = $03 // Needs to be $03 for tree_insert
.const loop_pointer = $20
.const remainder = $24
// Need to be $26 and $fd due to multiply_16bit_unsigned
.const outer_value = $26
.const inner_value = $fd
day01:
move_16_imm($03, str_title)
jsr write_string
//
// Parse the input at day01_input into an array of integers.
//
move_16_imm(input_pointer, day01_input)
ldy #0
!line:
// Create a temporary 16-bit integer to store the result in
// in between digits.
move_16_imm(atoi_result, 0)
!digit:
// Check for the newline character at the end of the line.
lda (input_pointer), y
cmp #'\n'
beq !newline+
// Multiply the stored number by 10.
i16_mul10(atoi_result)
// Subtract '0' from the current digit to convert it to "binary".
lda (input_pointer), y
sec
sbc #'0'
// Add the binary digit to the stored number
i16_i8_add_a(atoi_result)
// Increment y.
iny
bne !digit-
// If y overflows, increment the MSB of the input pointer as well,
// for a 16-bit increment.
inc input_pointer + 1
jmp !digit-
!newline:
// Insert the converted number into the tree.
jsr tree_insert
iny
bne !+
inc input_pointer + 1
!:
// Check for the null terminator.
lda (input_pointer), y
bne !line-
move_16_imm($03, str_parse_done)
jsr write_string
ldy #0
!loop:
// Subtract the number from 2020 to find the needed value.
lda tree_values_lo, y
sta $fd
eor #$ff
sec
adc #<2020
sta $03
sta $26
lda tree_values_hi, y
sta $fe
eor #$ff
adc #>2020
sta $04
sta $27
iny
jsr tree_contains
bne !loop-
// Multiply the results together
sec
jsr multiply_16bit_unsigned
move_16_imm($03, str_calc_done)
jsr write_string
// Print the 32-bit result as decimal.
lda $25
sta udivmod32_dividend + 3
lda $24
sta udivmod32_dividend + 2
lda $23
sta udivmod32_dividend + 1
lda $22
sta udivmod32_dividend + 0
jsr print_decimal_u32
rts
!error:
move_16_imm($03, str_no_result)
jsr write_string
rts
str_title:
.text "# Day 01, part 1:"
.byte '\n', 0
str_parse_done:
.text "* Finished parsing"
.byte '\n', 0
str_calc_done:
.text "* Finished calculating"
.byte '\n', 0
str_no_result:
.byte '\n'
.text "! Could not find a result"
.byte '\n', 0