program day2 implicit none integer, parameter :: max_games = 100 integer, parameter :: max_subgames = 100 integer, parameter :: max_cdraws = 3 integer, parameter :: max_chars = 10000 integer, parameter :: max_red = 12 integer, parameter :: max_green = 13 integer, parameter :: max_blue = 14 integer :: game, subgame, cdraw integer :: game_red, game_green, game_blue integer :: ca_1, ca_2 integer :: cb_1, cb_2 integer :: n_arguments character(max_chars) :: GameLine integer :: tLLen character(200) :: fname logical :: f_col, game_poss integer :: cubes integer :: sum_games, game_power, sum_power n_arguments = command_argument_count() if (n_arguments .eq. 1) then call get_command_argument(1, fname) print *, "File: ", fname else print *, "Wrong number of arguments: ", n_arguments stop end if open(10, file=fname) sum_games = 0 sum_power = 0 do game=1,max_games read(10, "(a)") GameLine tLLen = len_trim(GameLine) if (tLLen .eq. 0) then continue end if f_col = .false. ca_2 = index(GameLine, ':') if ((ca_2 .eq. 0) .or. (ca_2 .ge. tLLen)) then continue end if game_poss = .true. game_red = 0 game_green = 0 game_blue = 0 do subgame=1,max_subgames ca_1 = ca_2 if (ca_1 .ge. tLLen) then exit end if ca_2 = index(GameLine((ca_1 + 1):tLLen), ';') if (ca_2 .eq. 0) then ca_2 = tLLen else ca_2 = ca_1 + ca_2 end if cb_2 = ca_1 do cdraw=1,max_cdraws cb_1 = cb_2 if (cb_1 .eq. ca_2) then exit end if cb_2 = index(GameLine(cb_1 + 1:ca_2), ',') if (cb_2 .eq. 0) then cb_2 = ca_2 else cb_2 = cb_1 + cb_2 end if read(GameLine((cb_1 + 1):cb_2), *) cubes if (index(GameLine((cb_1 + 1):cb_2), "red") .ne. 0) then if (cubes .gt. max_red) then game_poss = .false. end if if (cubes .gt. game_red) then game_red = cubes end if else if (index(GameLine((cb_1 + 1):cb_2), "green") .ne. 0) then if (cubes .gt. max_green) then game_poss = .false. end if if (cubes .gt. game_green) then game_green = cubes end if else if (cubes .gt. max_blue) then game_poss = .false. end if if (cubes .gt. game_blue) then game_blue = cubes end if end if end do end do game_power = game_red * game_green * game_blue sum_power = sum_power + game_power if (game_poss) then print *, "Possible game! ", game, " Power = ", game_power sum_games = sum_games + game else print *, "Not possible. Power = ", game_power end if end do print *, "Sum of possible games: ", sum_games print *, "Sum of game powers: ", sum_power close(10) end program day2