diff --git a/.gitignore b/.gitignore index 3acba4b..fc5d555 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,5 @@ session.key input .tup out -*.im \ No newline at end of file +*.im +vis/ \ No newline at end of file diff --git a/days/day05.st b/days/day05.st new file mode 100644 index 0000000..638fe5b --- /dev/null +++ b/days/day05.st @@ -0,0 +1,58 @@ +Dictionary extend [ + at: key inA: Type [^self at: key ifAbsentPut: [Type new]] + at: key inA: Type add: elt [ (self at: key inA: Type) add: elt ] +] + +Object subclass: Ordering [ + | beforeMap | + initialize [beforeMap := Dictionary new] + + graphviz + [ AOC visualizeWithExt: '.dot' do: [ + :stream | + stream << 'digraph {'. + beforeMap keysAndValuesDo: [ + :k :vs | vs do: [ + :v | stream << k << ' -> ' << v << ';'. ]]. + stream << '}'. + ]] + + order: page1 before: page2 + [ beforeMap at: page2 inA: Set add: page1 ] + addRule: ruleStr + [ ruleStr scanf: '%d|%d' with: [ :x :y | self order: x before: y ] ] + + isValid: man + [ | mustNotOccur | mustNotOccur := Set new. + man do: [ + :elt | + (mustNotOccur includes: elt) ifTrue: [^false]. + mustNotOccur addAll: (beforeMap at: elt inA: Set). ]. + ^true ] + + sort: man + [ ^man asSortedCollection: [ :x :y | ((beforeMap at: y) includes: x) ] ] +] + +Collection extend [ + middleElement [ ^self at: self size // 2 + 1 ] +] + +AOC input: [ (stdin contents tokenize: (String with: $<10> with: $<10>)) + letArrayInBlock: [ + :rules :seqs | | ord mans | + ord := Ordering new. + rules lines do: [ :rule | ord addRule: rule ]. + mans := seqs lines collect: [ + :seq | seq chain tokenize: ','; collect: [:x | x asNumber] ]. + "ord graphviz." + {ord . mans} ] ]; + part1: [ :ord :mans | mans select: [ :man | ord isValid: man ] ]; + part2: [ :ord :mans | + mans chain reject: [ :man | ord isValid: man ]; + collect: [ :man | ord sort: man ] ]; + result: [ :ordAndMans :part | + part chain valueWithArguments: ordAndMans; + collect: [:man | man middleElement]; + sum ]; + finish. diff --git a/days/utils.st b/days/utils.st index 31688e9..0aa909c 100644 --- a/days/utils.st +++ b/days/utils.st @@ -22,10 +22,21 @@ AOC class extend [ "TODO: save as an image?" finish [ | startTime stopTime | + (Smalltalk getenv: 'AOC_RUN') ifNil: [ + stdout << 'AOC_RUN not set -- not running.'. + ^nil ]. startTime := Time millisecondClock. self run. stopTime := Time millisecondClock. stdout << 'Time elapsed: ' << (stopTime - startTime) << 'ms'; nl. ] + + visualizeWithExt: ext do: block + [ | file io | + file := (Smalltalk getenv: 'AOC_VIS') ifNil: [^nil]. + file := (file,ext) asFile. + file printNl. + file parent createDirectories. + io := file writeStream. [ block value: io ] ensure: [io close] ] ] "--- Scanf ---" diff --git a/run.sh b/run.sh index c3dd0de..9811507 100755 --- a/run.sh +++ b/run.sh @@ -22,4 +22,7 @@ else fi fi +export AOC_VIS="$DIR/vis/day$DAYP" +export AOC_RUN=1 + exec gst -g "days/utils.st" "days/day$DAYP.st" < "$AOC_INPUT"