-
Notifications
You must be signed in to change notification settings - Fork 0
/
day7.java
72 lines (70 loc) · 2.16 KB
/
day7.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashSet;
public class day7{
public static void main(String[] args){
System.out.println(part1());
System.out.println(part2());
}
public static int part1(){
ArrayList<Integer> crabs = openFile("input.txt");
HashSet<Integer> unique = new HashSet<Integer>(crabs);
int minDiff = -1;
for(int target: unique){
int totalDiff = 0;
for(int item: crabs){
totalDiff += Math.abs(item - target);
}
if(totalDiff < minDiff || minDiff == -1){
minDiff = totalDiff;
}
}
return minDiff;
}
public static int part2(){
ArrayList<Integer> crabs = openFile("input.txt");
int minCrab = -1;
int maxCrab = -1;
for(int crab: crabs){
if(crab < minCrab || minCrab == -1){
minCrab = crab;
}
else if(crab > maxCrab || maxCrab == -1){
maxCrab = crab;
}
}
int minDiff = -1;
// For every horizontal target
for(int i = minCrab; i <= maxCrab; i++){
int totalDiff = 0;
// For each crab
for(int item: crabs){
// Get the sum distance between them
for(int j = 1; j <= Math.abs(item - i); j++){
totalDiff += j;
}
}
if(totalDiff < minDiff || minDiff == -1){
minDiff = totalDiff;
}
}
return minDiff;
}
public static ArrayList<Integer> openFile(String path){
try{
Scanner s = new Scanner(new File(path));
ArrayList<Integer> items = new ArrayList<Integer>();
while(s.hasNextLine()){
for(String item: s.nextLine().split(",")){
items.add(Integer.parseInt(item));
}
}
s.close();
return items;
} catch(FileNotFoundException e){
throw new RuntimeException(e);
}
}
}