Created with <3 with dartpad.dev.
Created
November 20, 2023 08:51
-
-
Save mykdavies/2ae60c3e3a6ae2edf57a5eff9c298d8d to your computer and use it in GitHub Desktop.
AOC2022 day20
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// AOC 2022, Day 20: Grove Positioning System | |
// Mix a list according to some rules | |
// 1) Once. | |
// 2) Ten times with a key. | |
// https://dartpad.dev/?id=2ae60c3e3a6ae2edf57a5eff9c298d8d | |
import 'package:collection/collection.dart'; | |
extension IntegerRangeExtension on int { | |
List<int> to(int end, {int step = 1}) => | |
List.generate((end - this + (step - 1)) ~/ step, (i) => i * step + this); | |
} | |
parseLines(List<String> lines, {int key = 1}) => | |
lines.map((e) => int.parse(e) * key).indexed.toList(); | |
process(List<(int, int)> ns) { | |
for (var n in ns.indexed) { | |
// "move each number forward or backward in the file a number of positions | |
// equal to the value of the number being moved" | |
var ix = ns.indexWhere((e) => e.$1 == n.$1); | |
var el = ns.removeAt(ix); | |
ns.insert((ix + el.$2) % ns.length, el); | |
} | |
return ns; | |
} | |
int answer(List<(int, int)> ns) { | |
// "sum of the 1000th, 2000th, and 3000th numbers after the value 0" | |
var ix = ns.indexWhere((e) => e.$2 == 0); | |
return [1000, 2000, 3000].map((e) => ns[(ix + e) % ns.length].$2).sum; | |
} | |
part1(List<String> lines) => answer(process(parseLines(lines))); | |
// "you need to apply the decryption key, 811589153" | |
part2(List<String> lines) => answer( | |
0.to(10).fold(parseLines(lines, key: 811589153), (s, _) => process(s))); | |
var testdata = ["1", "2", "-3", "3", "-2", "0", "4"]; | |
void main(List<String> args) { | |
var dt = DateTime.now(); | |
assert(part1(testdata) == 3); | |
assert(part2(testdata) == 1623178306); | |
var rt = DateTime.now().difference(dt).inMilliseconds; | |
print('tests succeeded in $rt ms'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment