This repository was archived by the owner on Aug 4, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay9.java
More file actions
74 lines (62 loc) · 2.26 KB
/
Copy pathDay9.java
File metadata and controls
74 lines (62 loc) · 2.26 KB
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
73
74
package aoc2015;
import common.PermutationUtil;
import common.Util;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class Day9
{
private static Map<String, Map<String, Integer>> parseDistances(List<String> input)
{
Map<String, Map<String, Integer>> map = new HashMap<>();
for( String line : input )
{
String[] split = line.split(" ");
String from = split[0];
String to = split[2];
int distance = Integer.parseInt( split[4] );
map.computeIfAbsent( from, key -> new HashMap<>()).put( to, distance );
map.computeIfAbsent( to, key -> new HashMap<>()).put( from, distance );
}
return map;
}
private static int calculateDistance( String[] path, Map<String, Map<String, Integer>> distances )
{
int totalDistance = 0;
for( int i=0; i<path.length - 1; i++ )
totalDistance += distances.get( path[i] ).get( path[i+1]);
return totalDistance;
}
private static TreeMap<Integer, String[]> getPathMap( List<String> input )
{
Map<String, Map<String, Integer>> distances = parseDistances( input );
String[] cities = distances.keySet().toArray( new String[]{} );
TreeMap<Integer, String[]> map = new TreeMap<>();
PermutationUtil.permute( cities, permutation ->
{
int totalDistance = calculateDistance( permutation, distances );
map.put( totalDistance, permutation );
});
return map;
}
public static void main(String[] args) throws IOException
{
List<String> input = new ArrayList<>();
input.add("London to Dublin = 464");
input.add("London to Belfast = 518");
input.add("Dublin to Belfast = 141");
assert getPathMap( input ).firstKey() == 605;
input = Files.readAllLines( Util.getInputFilePath() );
TreeMap<Integer, String[]> pathMap = getPathMap( input );
//part 1
System.out.println( pathMap.firstKey() );
//part 2
System.out.println( pathMap.lastKey() );
}
}