Last active
December 9, 2020 17:31
-
-
Save deanbot/7fd88ab625654d5b918fc5df11c64882 to your computer and use it in GitHub Desktop.
Advent Of Code 2020 Day 9 in dart
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
import 'dart:math'; | |
void main() { | |
final List<Object> solutions = [ | |
SolutionA(), | |
SolutionB() | |
]; | |
solutions.forEach((s) => print(s.toString())); | |
} | |
// Full inputs at https://adventofcode.com/2020/day/9/input | |
const inputsDay9 = """35 | |
20 | |
15 | |
25 | |
47 | |
40 | |
62 | |
55 | |
65 | |
95 | |
102 | |
117 | |
150 | |
182 | |
127 | |
219 | |
299 | |
277 | |
309 | |
576"""; | |
List<int> _parseInputs(String inputs) => inputs | |
.split('\n') | |
.where((element) => element.isNotEmpty) | |
.map((e) => int.parse(e)) | |
.toList(); | |
List<int> _inputs = _parseInputs(inputsDay9); | |
abstract class AdventSolution { | |
final int day; | |
final String name; | |
AdventSolution(this.day, this.name); | |
// implement in subclass | |
String getSolution(); | |
@override | |
String toString() { | |
return "Advent Of Code, " | |
"Day $day " | |
"${name.isNotEmpty ? name : ''} " | |
"solution: ${getSolution()}"; | |
} | |
} | |
abstract class _Day9Solution extends AdventSolution { | |
_Day9Solution(name) : super(9, name); | |
} | |
class SolutionA extends _Day9Solution { | |
SolutionA() : super('A'); | |
String getSolution() { | |
var stackLength = 5; | |
// uncomment if using full inputs | |
// var stackLength = 25; | |
var stack = <int>[..._inputs.take(stackLength)]; | |
return _inputs.skip(stackLength).firstWhere((value) { | |
var valid = false; | |
for (var n in stack) { | |
withoutN(e) => e != n; | |
if (stack.where(withoutN).contains(value - n)) { | |
valid = true; | |
break; | |
} | |
} | |
stack.removeAt(0); | |
stack.add(value); | |
return !valid; | |
}).toString(); | |
} | |
} | |
class SolutionB extends _Day9Solution { | |
SolutionB() : super('B'); | |
String getSolution() { | |
var search = 127; | |
// uncomment if using full inputs and use part A solution | |
// var search = 90433990; | |
var total = 0, i = 0, startingIndex = 0, seq = <int>[]; | |
while (!(seq.length > 2 && total == search) && | |
startingIndex < _inputs.length) { | |
seq.add(_inputs[i++]); | |
total += seq.last; | |
// reached end, increment starting index | |
if (i == _inputs.length && total != search) { | |
i = ++startingIndex; | |
seq.clear(); | |
total = 0; | |
} | |
} | |
return seq.length > 0 ? (seq.reduce(min) + seq.reduce(max)).toString() : ''; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment