Skip to content

Instantly share code, notes, and snippets.

@certik
Created December 1, 2023 15:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save certik/7106c13c85b87f7bafe0eb06f1219839 to your computer and use it in GitHub Desktop.
Save certik/7106c13c85b87f7bafe0eb06f1219839 to your computer and use it in GitHub Desktop.
PROGRAM Calibration
IMPLICIT NONE
INTEGER :: total_sum, first_digit, last_digit, calibration_value
CHARACTER(100), DIMENSION(:), ALLOCATABLE :: calibration_document
INTEGER :: i, len_line, char_value, status
! Initialize total sum
total_sum = 0
! Read calibration document from input.txt
OPEN(UNIT=10, FILE='input.txt', STATUS='OLD', ACTION='READ', IOSTAT=status)
ALLOCATE(calibration_document(1000))
i = 1
DO WHILE (i <= 1000 .AND. status == 0)
READ(10, '(A100)', IOSTAT=status) calibration_document(i)
i = i + 1
ENDDO
CLOSE(UNIT=10)
! Calculate the sum of calibration values
DO i = 1, SIZE(calibration_document)
len_line = LEN_TRIM(calibration_document(i))
IF (len_line > 0) THEN
! Filter out non-digit characters and take the first and last digits
last_digit = -1
DO WHILE (len_line > 0 .AND. last_digit < 0)
char_value = IACHAR(calibration_document(i)(len_line:len_line))
IF (char_value >= IACHAR('0') .AND. char_value <= IACHAR('9')) THEN
last_digit = char_value - IACHAR('0')
ENDIF
len_line = len_line - 1
ENDDO
first_digit = -1
len_line = 1
DO WHILE (len_line <= len_trim(calibration_document(i)) .AND. first_digit < 0)
char_value = IACHAR(calibration_document(i)(len_line:len_line))
IF (char_value >= IACHAR('0') .AND. char_value <= IACHAR('9')) THEN
first_digit = char_value - IACHAR('0')
ENDIF
len_line = len_line + 1
ENDDO
! Combine the digits to form a two-digit number
calibration_value = first_digit * 10 + last_digit
! Add the calibration value to the total sum
total_sum = total_sum + calibration_value
ENDIF
ENDDO
! Print the result
PRINT *, 'Sum of calibration values:', total_sum
! Deallocate memory
DEALLOCATE(calibration_document)
END PROGRAM Calibration
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment