mirror of
https://github.com/HenkKalkwater/aoc-2020
synced 2025-09-05 09:52:44 +00:00
Added day 1
This commit is contained in:
parent
51afb9d03e
commit
c6f7df0bf3
4 changed files with 308 additions and 4 deletions
39
source/app.d
39
source/app.d
|
@ -1,6 +1,37 @@
|
|||
import std.stdio;
|
||||
import core.stdc.stdlib;
|
||||
|
||||
import std.conv;
|
||||
import std.format;
|
||||
import std.stdio;
|
||||
import std.getopt;
|
||||
|
||||
import day1;
|
||||
|
||||
immutable string progName = "aoc-2020";
|
||||
|
||||
void function(string[])[] programs = [
|
||||
&day1.run
|
||||
];
|
||||
|
||||
void main(string[] args) {
|
||||
int day;
|
||||
if (args.length < 2) {
|
||||
stderr.writeln("USAGE: %s [day]".format(args[0]));
|
||||
exit(-1);
|
||||
}
|
||||
try {
|
||||
day = to!int(args[1]);
|
||||
} catch (ConvException e) {
|
||||
stderr.writeln("[day] is not an integer");
|
||||
exit(-1);
|
||||
}
|
||||
|
||||
if (day <= 0 || day > programs.length) {
|
||||
stderr.writeln("Day must be between 1 and %d".format(programs.length - 1));
|
||||
exit(-1);
|
||||
}
|
||||
|
||||
|
||||
programs[day - 1](args[2..$]);
|
||||
|
||||
void main()
|
||||
{
|
||||
writeln("Edit source/app.d to start your project.");
|
||||
}
|
||||
|
|
58
source/day1.d
Normal file
58
source/day1.d
Normal file
|
@ -0,0 +1,58 @@
|
|||
import std.algorithm;
|
||||
import std.array;
|
||||
import std.conv;
|
||||
import std.exception;
|
||||
import std.format;
|
||||
import std.range;
|
||||
import std.stdio;
|
||||
|
||||
immutable string progName = "aoc-2020";
|
||||
|
||||
void run(string[] args) {
|
||||
enforce(args.length == 1, "Please provide a part to run %s 1 [part]".format(progName));
|
||||
int part = to!int(args[0]);
|
||||
enforce(part > 0 && part <= 2, "Parts %d to %d supported".format(1, 2));
|
||||
|
||||
auto numbers = stdin.byLineCopy.map!(a => to!int(a)).array.sort;
|
||||
|
||||
auto fun = part == 1 ? &part1 : &part2;
|
||||
writeln(fun(numbers));
|
||||
}
|
||||
|
||||
int part1(SortedRange!(int[]) numbers) {
|
||||
int result = -1;
|
||||
|
||||
foreach (ref int a; numbers) {
|
||||
int b = 2020 - a;
|
||||
if (numbers.contains(b)) {
|
||||
result = b * a;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
unittest {
|
||||
auto numbers = [1721, 979, 366, 299, 675, 1456].sort;
|
||||
assert(part1(numbers) == 514579);
|
||||
}
|
||||
|
||||
int part2(SortedRange!(int[]) numbers) {
|
||||
int result = -1;
|
||||
foreach (ref int a; numbers) {
|
||||
foreach (ref int b; numbers) {
|
||||
int c = 2020 - b - a;
|
||||
if (numbers.contains(c)) {
|
||||
result = c * b * a;
|
||||
goto exit;
|
||||
}
|
||||
}
|
||||
}
|
||||
exit:
|
||||
return result;
|
||||
}
|
||||
|
||||
unittest {
|
||||
auto numbers = [1721, 979, 366, 299, 675, 1456].sort;
|
||||
assert(part2(numbers) == 241861950);
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue