Last active
December 7, 2020 14:49
-
-
Save deanbot/1cd1704cf5b8cf24220ad5b2f8a82565 to your computer and use it in GitHub Desktop.
Advent Of Code 2020 Day 5 in dart
This file contains hidden or 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
void main() { | |
int i = 0; | |
final List<Object> solutions = [ | |
SolutionA(), | |
SolutionB() | |
]; | |
solutions.forEach((s) => print(s.toString())); | |
} | |
// Full inputs at https://adventofcode.com/2020/day/5/input | |
const inputsDay5 = """BFFFBBFRRR | |
FFFBBBFRRR | |
BBFFBBFRLL"""; | |
List<BoardingPass> _parseInputs(String inputs) => inputs | |
.split('\n') | |
.where((element) => element.isNotEmpty) | |
.map<BoardingPass>((element) => BoardingPass.fromString(element)) | |
.toList(); | |
List<BoardingPass> _inputs = _parseInputs(inputsDay5); | |
class BoardingPass { | |
int row; | |
int column; | |
BoardingPass.fromString(String input) | |
: this.row = int.parse( | |
input.substring(0, 7).replaceAll('B', '1').replaceAll('F', '0'), | |
radix: 2), | |
this.column = int.parse( | |
input.substring(7).replaceAll('R', '1').replaceAll('L', '0'), | |
radix: 2); | |
int get seatId => row * 8 + column; | |
} | |
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 _Day5Solution extends AdventSolution { | |
_Day5Solution(name) : super(5, name); | |
} | |
class SolutionA extends _Day5Solution { | |
SolutionA() : super('A'); | |
String getSolution() { | |
var highest = 0; | |
_inputs.forEach((e) { | |
if (highest < e.seatId) { | |
highest = e.seatId; | |
} | |
}); | |
return highest.toString(); | |
} | |
} | |
class SolutionB extends _Day5Solution { | |
SolutionB() : super('B'); | |
String getSolution() { | |
var seatId, seatIds = _inputs.map<int>((e) => e.seatId).toList(); | |
seatIds.sort(); | |
for (var i = 0; i < seatIds.length - 1; i++) { | |
if (i == 0) { | |
continue; | |
} | |
// seat id found if previous is not current - 1 | |
final prevSeat = --seatIds[i]; | |
if (prevSeat != seatIds[i - 1]) { | |
seatId = prevSeat; | |
break; | |
} | |
} | |
return seatId.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment