Skip to content

Instantly share code, notes, and snippets.

@angus-g
Created December 2, 2019 07:56
Show Gist options
  • Select an option

  • Save angus-g/601de5023c4c58cf7163b65ead474096 to your computer and use it in GitHub Desktop.

Select an option

Save angus-g/601de5023c4c58cf7163b65ead474096 to your computer and use it in GitHub Desktop.
advent of code day 2
program day2
implicit none
character(len=1024) :: line
integer, dimension(:), allocatable :: ops
integer :: n, noun, verb
open(1, file="day2.in")
read(1, "(A)") line
close(1)
! magic to count number of commas in the line
! convert string to a character array and count commas
n = count(transfer(line, "a", len(line)) == ",")
allocate(ops(n+1))
read(line, *) ops(:)
! part 1
print *, run(ops, 12, 2)
! part 2
loop: do noun = 0, 99
do verb = 0, 99
if (run(ops, noun, verb) == 19690720) then
print *, 100 * noun + verb
exit loop
end if
end do
end do loop
contains
function run(ops, noun, verb) result(res)
integer, dimension(:), intent(in) :: ops
integer, intent(in) :: noun, verb
integer, dimension(0:size(ops)-1) :: mem
integer :: ip, res
mem(:) = ops(:)
mem(1) = noun
mem(2) = verb
ip = 0
do
select case (mem(ip))
case (99)
exit
case (1)
mem(mem(ip + 3)) = mem(mem(ip + 1)) + mem(mem(ip + 2))
case (2)
mem(mem(ip + 3)) = mem(mem(ip + 1)) * mem(mem(ip + 2))
end select
ip = ip + 4
end do
res = mem(0)
end function run
end program day2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment