Added day 2.

This commit is contained in:
Andrew Lalis 2021-12-02 14:29:16 +01:00
parent 8ca21fcdf4
commit f4b4845e38
3 changed files with 1046 additions and 1 deletions

View File

@ -2,7 +2,8 @@ import std.stdio;
import day1.part1; import day1.part1;
import day1.part2; import day1.part2;
import day2.part1;
void main() { void main() {
slidingSum(); dive2();
} }

1000
source/day2/input.txt Normal file

File diff suppressed because it is too large Load Diff

44
source/day2/part1.d Normal file
View File

@ -0,0 +1,44 @@
module day2.part1;
import std.file;
import std.stdio;
import std.string;
import std.conv;
import std.typecons;
Tuple!(string, int) parseOp(char[] op) {
auto parts = op.split();
int x = parts[1].to!int;
string d = parts[0].to!string;
return tuple(d, x);
}
void dive() {
File f = File("source/day2/input.txt", "r");
int depth = 0;
int position = 0;
foreach (line; f.byLine) {
auto op = parseOp(line);
if (op[0] == "up") depth -= op[1];
if (op[0] == "down") depth += op[1];
if (op[0] == "forward") position += op[1];
}
writefln("Final depth: %d, Final position: %d, Product: %d", depth, position, depth * position);
}
void dive2() {
File f = File("source/day2/input.txt", "r");
int aim = 0;
int depth = 0;
int position = 0;
foreach (line; f.byLine) {
auto op = parseOp(line);
if (op[0] == "up") aim -= op[1];
if (op[0] == "down") aim += op[1];
if (op[0] == "forward") {
position += op[1];
depth += aim * op[1];
}
}
writefln("Final depth: %d, Final position: %d, Product: %d", depth, position, depth * position);
}