Skip to content
Snippets Groups Projects
Commit 24e81aea authored by Christopher Bohn's avatar Christopher Bohn :thinking:
Browse files

Completed 2021 day 2

parent e982821c
Branches
No related tags found
No related merge requests found
# 2021 Advent of Coding Solutions
## Day 1
A nice little warmup exercise in which we iterate over a list. Notice that I
get to use Java's new multiline strings.
## Day 2
Can we follow instructions? Yes we can. This isn't a particularly challenging
problem. Beside using Java's new Records, I'm also using Java's new style of
switch statements.
\ No newline at end of file
......@@ -8,7 +8,7 @@ import java.util.stream.Collectors;
@SuppressWarnings("unused")
public class Day1 extends Puzzle {
List<Integer> depths;
private List<Integer> depths;
public Day1() {
day = 1;
......
package edu.unl.cse.bohn.year2021;
import edu.unl.cse.bohn.Puzzle;
import java.util.List;
import java.util.stream.Collectors;
@SuppressWarnings("unused")
public class Day2 extends Puzzle {
private record NavigationInstruction(String direction, int magnitude) {
}
private List<NavigationInstruction> navigationInstructions;
private int range;
private int depth;
@SuppressWarnings("FieldCanBeLocal")
private int aim;
public Day2() {
day = 2;
sampleData = """
forward 5
down 5
forward 8
up 3
down 8
forward 2""";
isProductionReady = true;
}
@Override
public int computePart1(List<String> data) {
navigationInstructions = data.stream()
.map(instruction -> new NavigationInstruction(
instruction.split(" ")[0],
Integer.parseInt(instruction.split(" ")[1])))
.collect(Collectors.toList());
range = 0;
depth = 0;
for (NavigationInstruction instruction : navigationInstructions) {
switch (instruction.direction()) {
case ("forward") -> range += instruction.magnitude();
case ("down") -> depth += instruction.magnitude();
case ("up") -> depth -= instruction.magnitude();
default -> throw new IllegalStateException("Unknown direction: " + instruction.direction());
}
}
return range * depth;
}
@Override
public int computePart2(List<String> data) {
range = 0;
depth = 0;
aim = 0;
for (NavigationInstruction instruction : navigationInstructions) {
switch (instruction.direction()) {
case ("forward") -> {
range += instruction.magnitude();
depth += aim * instruction.magnitude();
}
case ("down") -> aim += instruction.magnitude();
case ("up") -> aim -= instruction.magnitude();
default -> throw new IllegalStateException("Unknown direction: " + instruction.direction());
}
}
return range * depth;
}
}
# 2021 Advent of Coding Solutions
# Advent of Code
## Day 1
My solutions to the [Advent of Code](https://adventofcode.com/) puzzles.
I'm making [notes](2021/README.md) about the 2021 puzzles and my solutions.
A nice little warmup exercise in which we iterate over a list.
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment