Last active
December 2, 2020 16:27
-
-
Save deanbot/0f794ade224b9db11fc37de8aac91585 to your computer and use it in GitHub Desktop.
Advent Of Code 2020 Day 1 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
void main() { | |
int i = 0; | |
final List<AdventSolution> solutions = [ | |
AdventSolution1(inputAdvent1), | |
AdventSolution2(inputAdvent1) | |
]; | |
solutions.forEach((s) => print("Advent ${++i} solution: ${s.solution}")); | |
} | |
// Full inputs at https://adventofcode.com/2020/day/1/input | |
const inputAdvent1 = """1721 | |
979 | |
366 | |
299 | |
675 | |
1456"""; | |
abstract class AdventSolution { | |
final List<int> expenses; | |
AdventSolution(String inputs) : expenses = AdventSolution.parseInputs(inputs); | |
static List<int> parseInputs(String inputs) => inputs | |
.split("\n") | |
.where((element) => element.isNotEmpty) | |
.map((element) => int.parse(element)) | |
.toList(); | |
String get solution => _getSolution(); | |
String _getSolution(); | |
} | |
class AdventSolution1 extends AdventSolution { | |
AdventSolution1(inputs) : super(inputs); | |
String _getSolution() { | |
var product; | |
for (var expense in expenses) { | |
var index = expenses.indexWhere( | |
(element) => element != expense && element + expense == 2020); | |
if (index == -1) { | |
continue; | |
} | |
product = expenses[index] * expense; | |
} | |
return product?.toString(); | |
} | |
} | |
class AdventSolution2 extends AdventSolution { | |
AdventSolution2(inputs) : super(inputs); | |
String _getSolution() { | |
int product; | |
for (var eA in expenses) { | |
for (var eB in expenses) { | |
if (eB == eA) { | |
continue; | |
} | |
for (var eC in expenses) { | |
if (eC == eA || eC == eB) { | |
continue; | |
} | |
if ((eA + eB + eC) == 2020) { | |
product = eA * eB * eC; | |
break; | |
} | |
} | |
if (product != null) { | |
break; | |
} | |
} | |
if (product != null) { | |
break; | |
} | |
} | |
return product.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment