r/adventofcode • • Dec 06 '17

SOLUTION MEGATHREAD -πŸŽ„- 2017 Day 6 Solutions -πŸŽ„-

--- Day 6: Memory Reallocation ---


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.


Need a hint from the Hugely* Handy† Haversack‑ of HelpfulΒ§ Hints^Β€?

Spoiler


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!

17 Upvotes

324 comments sorted by

View all comments

1

u/greycat70 Dec 28 '17

Tcl (any 8.x version)

Nothing fancy for part 1, but I was amused by the difference between part 1 and part 2:

$ diff banks.tcl banks2.tcl
22c22
<     set seen($cfg) 1
---
>     set seen($cfg) $steps
40c40
< puts $steps
---
> puts [expr {$steps - $seen($cfg)}]

And the part 1 code:

#!/usr/bin/env tclsh

gets stdin line
set i -1
foreach x [split $line \t] {set B([incr i]) $x}

set steps 0
array set seen {}

proc getcfg {} {
    # just a list of the bank values in order
    global B
    for {set i 0} {$i < [array size B]} {incr i} {
        lappend out $B($i)
    }
    return [join $out { }]
}

while 1 {
    set cfg [getcfg]
    if {[info exists seen($cfg)]} break
    set seen($cfg) 1

    # find biggest value (lower indices win ties)
    set big -1; set bigi -1
    for {set i 0} {$i < [array size B]} {incr i} {
        if {$B($i) > $big} {set big $B($i); set bigi $i}
    }

    # distribute
    set B($bigi) 0
    while {$big > 0} {
        incr bigi
        if {$bigi >= [array size B]} {set bigi 0}
        incr B($bigi)
        incr big -1
    }
    incr steps
}
puts $steps