some-advent-of-code: d115dc46423faa44e416b283d1e61b6d1ffc3d8b
1:
2: import java.io.IOException;
3: import java.nio.file.Files;
4: import java.nio.file.InvalidPathException;
5: import java.nio.file.Path;
6: import java.nio.file.Paths;
7: import java.util.HashSet;
8: import java.util.LinkedList;
9: import java.util.List;
10: import java.util.Map;
11: import java.util.Set;
12: import java.util.TreeMap;
13:
14: public class Exercise200101
15: {
16:
17: public static void main( String args[] )
18: {
19: final String here = "e20011.m ";
20: if ( args.length < 1 )
21: {
22: throw new RuntimeException( here +"add a filename argument" );
23: }
24: String userSaysFile = args[ 0 ];
25: List<String> fileLines = new LinkedList<>();
26: try
27: {
28: Path where = Paths.get( userSaysFile );
29: fileLines = Files.readAllLines( where );
30: }
31: catch ( IOException | InvalidPathException ie )
32: {
33: System.err.println( here +"couldn't read file "+ userSaysFile +" because "+ ie );
34: return;
35: }
36: /*
37: - interpretation of spec -
38: for values in file
39: partition into more and less than half of target
40: for values in less than half
41: for values in more than half
42: if sum is target
43: print less * more
44: */
45: // gather
46: Set<Integer> lessThanHalf = new HashSet<>();
47: Set<Integer> moreThanHalf = new HashSet<>();
48: Integer temp;
49: int target = 2020, half = target /2;
50: boolean seenExactlyHalfAlready = false;
51: int lineNum = 0;
52: for ( String line : fileLines )
53: {
54: lineNum += 1;
55: try
56: {
57: temp = Integer.parseInt( line );
58: if ( temp < half )
59: lessThanHalf.add( temp );
60: else if ( temp > half )
61: moreThanHalf.add( temp );
62: else if ( ! seenExactlyHalfAlready )
63: seenExactlyHalfAlready = true; // no need to save it
64: else
65: {
66: System.err.println( here +"exactly half twice, squared is "+ (temp * temp) );
67: return;
68: }
69: }
70: catch ( NumberFormatException nfe )
71: {
72: System.err.println( here +"handed a non int "+ line +" on "+ lineNum +" because "+ nfe );
73: continue;
74: }
75: }
76: // combinatoric
77: for ( Integer lesser : lessThanHalf )
78: {
79: for ( Integer greater : moreThanHalf )
80: {
81: if ( (lesser + greater) == target )
82: {
83: System.err.println( here +"lesser is "+ lesser +" greater is "+ greater +" product is "+ (lesser * greater) );
84: return;
85: }
86: }
87: }
88: System.out.println( here +"input had no pair that summed to "+ target );
89: }
90: }
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
Generated by git2html.