Skip to content

Instantly share code, notes, and snippets.

@deanbot
Last active December 3, 2020 22:46
Show Gist options
  • Save deanbot/0c42b304757240a0284234ca739d8ed2 to your computer and use it in GitHub Desktop.
Save deanbot/0c42b304757240a0284234ca739d8ed2 to your computer and use it in GitHub Desktop.
Advent Of Code 2020 Day 3 in dart
void main() {
final List<Object> solutions = [
SolutionA(),
SolutionB()
];
solutions.forEach((s) => print(s.toString()));
}
// Full inputs at https://adventofcode.com/2020/day/3/input
var inputAdvent3 = """..##.......
#...#...#..
.#....#..#.
..#.#...#.#
.#...##..#.
..#.##.....
.#.#.#....#
.#........#
#.##...#...
#...##....#
.#..#...#.#""";
// get plot line objects from input string
List<PlotLine> _parseInputLines(String inputLines) => inputLines
.split("\n")
.where((element) => element.isNotEmpty)
.map<PlotLine>((l) => PlotLine.fromString(l))
.toList();
var _plotLines = _parseInputLines(inputAdvent3);
// convert string to List<SpaceType>
const _charOpen = ".";
const _charTree = "#";
enum SpaceType { open, tree }
List<SpaceType> _parseInputLine(String inputLine) => inputLine.runes
.map<SpaceType>((f) =>
String.fromCharCode(f) == _charTree ? SpaceType.tree : SpaceType.open)
.toList();
// get total space type occurences at slope
int getCount(int rateX, int rateY, [SpaceType searchType = SpaceType.tree]) {
var x = 0, y = 0, count = 0;
do {
x += rateX;
y += rateY;
if (y < _plotLines.length) {
SpaceType type = _plotLines[y].spaceAt(x);
if (type == searchType) {
count++;
}
}
} while (y < _plotLines.length);
return count;
}
class PlotLine {
final List<SpaceType> _template;
PlotLine(List<SpaceType> inputLine) : _template = inputLine;
PlotLine.fromString(String inputLine)
: _template = _parseInputLine(inputLine);
// get space type at x-index
SpaceType spaceAt(int index) => _template[index % _template.length];
String charAt(int index) =>
spaceAt(index) == SpaceType.tree ? _charTree : _charOpen;
}
abstract class AdventSolution {
final int day;
final String name;
AdventSolution(this.day, this.name);
String get solution => getSolution();
// implement in subclass
String getSolution();
@override
String toString() {
return "Advent Of Code, "
"Day $day "
"${name.isNotEmpty ? name : ''} "
"solution: $solution";
}
}
abstract class _Day3Solution extends AdventSolution {
_Day3Solution(name) : super(3, name);
}
class SolutionA extends _Day3Solution {
SolutionA() : super("A");
String getSolution() {
return getCount(3, 1).toString();
}
}
class SolutionB extends _Day3Solution {
SolutionB() : super("B");
String getSolution() {
var slopes = [
[1, 1],
[3, 1],
[5, 1],
[7, 1],
[1, 2]
];
return slopes
.map<int>((s) => getCount(s[0], s[1]))
.toList()
.reduce((value, element) => element * value)
.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment