some-advent-of-code: 73a649674a6b499648d8d1427222c879de253b80
1:
2: import java.io.IOException;
3: import java.nio.file.*;
4: import java.util.*;
5:
6: public class Exercise210301
7: {
8:
9: public static void main(
10: String args[]
11: ) {
12: final String here = "e210301.m ";
13: if ( args.length < 1 )
14: {
15: throw new RuntimeException( here +"add a filename argument" );
16: }
17: String userSaysFile = args[ 0 ];
18: List<String> fileLines = new LinkedList<>();
19: try
20: {
21: Path where = Paths.get( userSaysFile );
22: fileLines = Files.readAllLines( where );
23: }
24: catch ( IOException | InvalidPathException ie )
25: {
26: System.err.println( here +"couldn't read file "+ userSaysFile +" because "+ ie );
27: return;
28: }
29: /*
30: - interpretation of spec -
31: gamma is the more common bit, epsilon is the less common bit
32: put these in a bit set and multiply the resulting binary number
33: */
34: Exercise210301.interpretDiagnostic( fileLines );
35: }
36:
37:
38: private static void interpretDiagnostic(
39: List<String> fileLines
40: ) {
41: final int oneInd = 0, nilInd = oneInd +1;
42: int[][] bitCounts = new int[ 2 ][ fileLines.get( 0 ).length() ];
43: for ( int initInd = 0; initInd < bitCounts[ oneInd ].length; initInd++ )
44: {
45: bitCounts[ oneInd ][ initInd ] = 0;
46: bitCounts[ nilInd ][ initInd ] = 0;
47: }
48:
49: // sum bits
50: for ( String line : fileLines )
51: {
52: if ( line.isEmpty() )
53: continue;
54: for ( int charInd = 0; charInd < line.length(); charInd++ )
55: {
56: if ( line.charAt( charInd ) == '1' )
57: bitCounts[ oneInd ][ charInd ] += 1;
58: else // == 0
59: bitCounts[ nilInd ][ charInd ] += 1;
60: }
61: }
62:
63: // determine gamma and epsilon
64: long gamma = 0L, epsilon = 0L, multiplier = 1;
65: for ( int bitInd = bitCounts[ oneInd ].length -1; bitInd >= 0; bitInd-- )
66: {
67: if ( bitCounts[ oneInd ][ bitInd ] > bitCounts[ nilInd ][ bitInd ] )
68: gamma += multiplier;
69: else
70: epsilon += multiplier;
71: multiplier *= 2;
72: }
73:
74: System.out.println( "\tg"+ gamma +" e"+ epsilon +" t"+ gamma * epsilon );
75: }
76:
77:
78: }
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
Generated by git2html.