Skip to content

Commit

Permalink
day 1, 2 java
Browse files Browse the repository at this point in the history
  • Loading branch information
pin2t committed Dec 9, 2024
1 parent 7f48b87 commit 0077023
Show file tree
Hide file tree
Showing 3 changed files with 79 additions and 0 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,8 @@ inputs directory contains **my** inputs. Yours will be different

```shell
go run 01.go < inputs/01.txt
```

```shell
java day01.java < inputs/01.txt
```
26 changes: 26 additions & 0 deletions day01.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import java.util.*;

import static java.lang.Integer.parseInt;
import static java.lang.Math.abs;
import static java.lang.System.in;
import static java.lang.System.out;

public class day01 {
public static void main(String[] args) {
var left = new ArrayList<Integer>();
var right = new ArrayList<Integer>();
new Scanner(in).findAll("(\\d+)\\s+(\\d+)").forEach(pair -> {
left.add(parseInt(pair.group(1)));
right.add(parseInt(pair.group(2)));
});
left.sort(Integer::compareTo);
right.sort(Integer::compareTo);
int total = 0, similarity = 0;
for (int i = 0; i < left.size(); i++) {
int l = left.get(i);
total += abs(l - right.get(i));
similarity += (int) (l * right.stream().filter(n -> n.equals(l)).count());
}
out.println(total + " " + similarity);
}
}
49 changes: 49 additions & 0 deletions day02.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import java.io.*;
import java.util.*;

import static java.lang.System.in;
import static java.lang.System.out;

public class day02 {
public static void main(String[] args) {
var safes = new int[]{0, 0};
new BufferedReader(new InputStreamReader(in)).lines().forEach(line -> {
var report = new Report(line);
if (report.safe()) {
safes[0]++;
safes[1]++;
} else if (report.canBeSafe()) {
safes[1]++;
}
});
out.println(safes[0] + " " + safes[1]);
}

static class Report extends ArrayList<Integer> {
Report(String input) {
super(Arrays.stream(input.split("\\s")).map(Integer::valueOf).toList());
}

Report(List<Integer> source, int except) {
super(source);
remove(except);
}

boolean safe() {
boolean increasing = getFirst().compareTo(getLast()) < 0;
for (int i = 1; i < size(); i++) {
if (increasing && (get(i) - get(i - 1) <= 0 || get(i) - get(i - 1) > 3) ||
!increasing && (get(i) - get(i - 1) >= 0 || get(i - 1) - get(i) > 3)) {
return false;
}
}
return true;
}

boolean canBeSafe() {
for (int i = 0; i < size(); i++)
if (new Report(this, i).safe()) return true;
return false;
}
}
}

0 comments on commit 0077023

Please sign in to comment.