···
1
+
module day_07_part_2_utils
2
+
use iso_fortran_env, only: int64
5
+
recursive function test_values(arr, target, next_idx, current_value) result(pass)
7
+
integer(kind=int64), intent(in) :: target, current_value, arr(:)
8
+
integer, intent(in) :: next_idx
9
+
character(len=20) :: str_1, str_2, concat_str
10
+
integer(kind=int64) :: concat_value
13
+
if(next_idx > size(arr)) then
14
+
pass = current_value == target
18
+
write(str_1, '(I0)') current_value
19
+
write(str_2, '(I0)') arr(next_idx)
20
+
concat_str = trim(str_1) // trim(str_2)
21
+
read(concat_str, '(I20)') concat_value
23
+
pass = test_values(arr, target, next_idx + 1, current_value + arr(next_idx)) .or. &
24
+
test_values(arr, target, next_idx + 1, current_value * arr(next_idx)) .or. &
25
+
test_values(arr, target, next_idx + 1, concat_value)
26
+
end function test_values
27
+
logical function is_calibrated(arr, target)
29
+
integer(kind=int64), intent(in) :: target, arr(:)
31
+
is_calibrated = test_values(arr, target, 2, arr(1))
32
+
end function is_calibrated
33
+
end module day_07_part_2_utils
34
+
program day_07_part_2
35
+
use iso_fortran_env, only: int64
36
+
use day_07_part_2_utils
38
+
integer(kind=int64) :: test_number, res
39
+
integer(kind=int64), allocatable:: work(:)
40
+
integer :: io, ios, idx, i, ct
41
+
character(len=200) :: line, work_line
44
+
open(newunit=io, file='./day_07_input.txt', status='old', action='read')
46
+
read(io, '(a)', iostat=ios) line
48
+
idx = index(line, ':')
50
+
read(line(1:idx-1), *) test_number
52
+
work_line = trim(line(idx+1:len(trim(line))))
53
+
do i = 1 , len(trim(work_line))
54
+
if(work_line(i:i) == ' ') then
59
+
read(work_line, *) work(:)
61
+
pass = is_calibrated(work, test_number)
63
+
res = res + test_number
67
+
print*, "Result: ", res
68
+
end program day_07_part_2