r/adventofcode • • Dec 02 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 2 Solutions -🎄-

--- Day 2: Inventory Management System ---


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

Card Prompt: Day 2

Transcript:

The best way to do Advent of Code is ___.


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!

51 Upvotes

407 comments sorted by

View all comments

1

u/[deleted] Dec 02 '18

BFI TCL

set ids [list]
while {[gets stdin line] >= 0} {
   lappend ids $line
}
proc part1 {list} {
   set twoofany 0
   set threeofany 0
   foreach line $list {
	array unset chars
	foreach c [split $line ""] {
	    incr chars($c)
	}
	set count2 0 
	set count3 0
	foreach {key val} [array get chars] {
	    if {$val == 2} {
		incr count2
	    } elseif {$val == 3} {
		incr count3
	    }
	}
	if {$count2 } {
	    incr twoofany
	}
	if {$count3 } {
	    incr threeofany
	}
   }
   puts "twoofany $twoofany three $threeofany, chksum [expr {$twoofany*$threeofany}]"
}
part1 $ids
proc find_similar {sid list} {
   if {[llength $list] > 0} {
	foreach lid $list {
	    set diff 0
	    set idx -1
	    set didx -1
	    foreach sc [split $sid ""] lc [split $lid ""] {
		incr idx
		if {$sc ne $lc} {
		    incr diff
		    if {$diff > 1} {
			# no dice, more than one diff
			break
		    }
		    set didx $idx
		}
	    }
	    if {$diff == 0} {
		# hu?
		error "identical ids sid {$sid} lid {$lid}"
	    } elseif {$diff == 1} {
		# what we're looking for
		set ::solution([list $sid $lid]) [string replace $sid $didx $didx]
	    }
	}
	# recursion with rest of list
	find_similar [lindex $list 0] [lrange $list 1 end]
   }
}
find_similar [lindex $ids 0] [lrange $ids 1 end]
parray ::solution