r/adventofcode • • Dec 06 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 6 Solutions -🎄-

--- Day 6: Chronal Coordinates ---


Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


Advent of Code: The Party Game!

Click here for rules

Please prefix your card submission with something like [Card] to make scanning the megathread easier. THANK YOU!

Card prompt: Day 6

Transcript:

Rules for raising a programmer: never feed it after midnight, never get it wet, and never give it ___.


This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.

edit: Leaderboard capped, thread unlocked at 0:26:52!

32 Upvotes

387 comments sorted by

View all comments

1

u/tinyhurricanes Dec 06 '18 edited Dec 06 '18

Modern Fortran 2018 (complete code)

Runs in about 0.1 sec without visualizations, 0.2 sec with outputting the field to a log file a few times

This problem illustrates an interesting perk of Fortran: although arrays are 1-indexed by default, the index range can be anything (including negative). So I initialized a field that only just bounded all the points with no excess.

program main
use syslog_mod
use fclap_mod
use file_tools_mod
use string_tools_mod
use point_mod
implicit none

!-- Counters
integer :: i
integer :: x, y

!-- Input file unit
integer :: input_unit

!-- Number of lines in input file
integer :: num_lines

!-- Distances
integer,parameter :: MAX_MANHATTAN_DISTANCE = 10000
integer :: dist = 0
integer :: num_occurrences = 0
integer :: area_safe = 0
integer,allocatable :: distances(:)

!-- Control for whether to write the canvas to log
logical,parameter :: write_canvas = .true.

! Input file reading properties
!integer,parameter            :: max_line_len = 100
!character(len=max_line_len)  :: line
character(len=:),allocatable :: input_file

!-- Initialize System Log
call init_syslog

!-- Process Command Line Arguments
call configure_fclap
call parse_command_line_arguments

!-- Get input file name from command line
input_file = get_value_for_arg('input_file')

!-- Count lines in input file
num_lines = lines_in_file(input_file)

!-- Allocate data appropriately
allocate(points(num_lines))
allocate(distances(num_lines))

!-- Open file and read into memory
open (                    & 
    newunit = input_unit, & 
    file    = input_file, &
    action  = 'read',     &
    status  = 'old',      &
    form    = 'formatted' &
)
write (syslog%unit,*) 'Raw Points:'
write (syslog%unit,*) '  ID   X   Y'
do i = 1, num_lines
    
    !-- Read
    read (input_unit,*) points(i) % x, points(i) % y
    points(i) % id = i

    !-- Write to log
    write (syslog%unit,'(3i5)') &
        points(i) % id,         &
        points(i) % x,          &
        points(i) % y

end do
close (input_unit)

!-- Start timer
call syslog % start_timer

!-- Build canvas
xmin = minval(points(:) % x)
xmax = maxval(points(:) % x)
ymin = minval(points(:) % y)
ymax = maxval(points(:) % y)
write (syslog%unit,'(4(a,i0),a)') 'Building grid of (',xmin,'-',xmax,',',ymin,'-',ymax,')'
allocate(canvas(xmin:xmax,ymin:ymax))

!-- Put existing points on canvas
do i = 1, num_lines
    canvas(points(i) % x, points(i) % y) % id = points(i) % id
end do

!-- Draw initial canvas
if (write_canvas) then
    write (syslog%unit,*) 'Point Field:'
    call draw_canvas
end if

!-- Calculate distances between all points on canvas and defined points
X_LOOP: do x = xmin, xmax
    Y_LOOP: do y = ymin, ymax
        
        ! Calculate distances to all defined points
        distances(:) = abs(x - points(:) % x) + abs(y - points(:) % y)

        ! Minimum distance
        dist = minval(distances)
        num_occurrences = 0

        ! Ensure there was only one occurrence of minimum distance
        do i = 1, num_lines
            if (distances(i) == dist) num_occurrences = num_occurrences + 1
        end do

        ! Point is equally far from 2 or more points: invalidate
        if (num_occurrences > 1) then
            canvas(x,y) % dist = -1
            canvas(x,y) % id   = -1

        ! Closest point
        else
            canvas(x,y) % dist = dist
            canvas(x,y) % id   = minloc(distances(:),1)
        end if
    end do Y_LOOP
end do X_LOOP

!-- Illustrate closest points
if (write_canvas) then
    write (syslog%unit,*) 'Closest points:'
    call draw_canvas
end if

!-- Calculate areas around points
do x = xmin, xmax
    do y = ymin, ymax
        do i = 1, num_lines
            if (canvas(x,y) % id == i) points(i) % area = points(i) % area + 1
        end do
    end do
end do

!-- Write areas to log
write (syslog%unit,*) 'Areas for each point:'
write (syslog%unit,*) '  ID   Area'
do i = 1, num_lines
    write (syslog%unit,'(i4,i8)') points(i) % id, points(i) % area
end do
write (syslog%unit,'(a,i0)') 'Part 1: largest area = ', maxval(points(:)%area) !4475

!-- Calculate
X_LOOP_2: do x = xmin, xmax
    Y_LOOP_2: do y = ymin, ymax
        
        ! Calculate distances to all defined points
        distances(:) = abs(x - points(:) % x) + abs(y - points(:) % y)

        ! Minimum distance
        dist = sum(distances)

        ! Point exceeds maximum distance: invalidate
        if (dist >= MAX_MANHATTAN_DISTANCE) then
            canvas(x,y) % dist = HUGE(i)
            canvas(x,y) % id   = 0

        ! Point is close enough
        else
            canvas(x,y) % dist = dist
            canvas(x,y) % id   = 1 ! now using ID field as a flag
        end if
    end do Y_LOOP_2
end do X_LOOP_2

!-- Illustrate safe area
if (write_canvas) then
    write (syslog%unit,*) 'Safe & close area:'
    call draw_canvas
end if

!-- Calculate area of safe region
area_safe = sum(canvas(:,:) % id)
write (syslog%unit,'(a,i0)') 'Part 2: safe & close area = ',area_safe !35237

!-- End timer
call syslog % end_timer

call syslog%log(__FILE__,'Done.')

end program

Point class:

module point_mod
use syslog_mod
implicit none

integer,private :: i

type :: Point
    integer :: id   = 0         ! Points(:) - id of self, Canvas(:,:) - id of closest point, or satisfactory distance flag
    integer :: x    = 0         ! x location
    integer :: y    = 0         ! y location
    integer :: area = 0         ! Points(:) - surrounding area
    integer :: dist = HUGE(i)   ! distance to nearest point
end type

! Points (field & defined points)
type(Point),allocatable :: points(:)    ! Array of points from input
type(Point),allocatable :: canvas(:,:)  ! Array of all points in canvas

!-- Canvas extents
integer :: xmin = 0
integer :: xmax = 0
integer :: ymin = 0
integer :: ymax = 0

contains

subroutine draw_canvas
    implicit none
    integer :: x, y

    ! Write blank
    write (syslog%unit,'(3X)',advance='no')
    
    ! Write x-headers
    do x = xmin, xmax
        write (syslog%unit,'(i3)',advance='no') x
    end do
    write (syslog%unit,*) ! advance
    
    ! Write field
    do y = ymin, ymax
        ! Write y-column
        write (syslog%unit,'(i3)',advance='no') y
        do x = xmin, xmax
            write (syslog%unit,'(i3)',advance='no') canvas(x,y) % id
        end do
        write (syslog%unit,*) ! advance
    end do
end subroutine
end module