some-advent-of-code: b6de987443aff3e8db40c086b99cbe833cd84c9c
1:
2: import java.io.IOException;
3: import java.nio.file.*;
4: import java.util.*;
5:
6: public class Exercise210701
7: {
8:
9: public static void main(
10: String args[]
11: ) {
12: final String here = "e210701.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: for crab position
32: increment number at that position
33: update max
34: for ( 1 - max position )
35: for position
36: increment cost * index
37: */
38: Exercise210701.align( fileLines );
39: }
40:
41:
42: private static void align(
43: List<String> fileLines
44: ) {
45: String[] positionsStr = null;
46: for ( String line : fileLines )
47: {
48: if ( line.isEmpty() )
49: continue;
50: positionsStr = line.split( "," );
51: }
52: boolean testing = true;
53:
54: int maxPosition = 0;
55: Map<Integer, Integer> position_crabs = new HashMap<>();
56: for ( String position : positionsStr )
57: {
58: int crabPosition = Integer.parseInt( position );
59: if ( position_crabs.containsKey( crabPosition ) )
60: position_crabs.put( crabPosition, position_crabs.get( crabPosition ) +1 );
61: else
62: position_crabs.put( crabPosition, Integer.valueOf( 1 ) );
63:
64: if ( crabPosition > maxPosition )
65: maxPosition = crabPosition;
66: }
67: if ( testing )
68: {
69: for ( int ind = 0; ind <= maxPosition; ind++ )
70: {
71: if ( ind % 100 == 0 )
72: System.out.println();
73: if ( position_crabs.containsKey( ind ) )
74: System.out.print( " "+ ind +"-"+ position_crabs.get( ind ) );
75: }
76: System.out.println();
77: }
78:
79: long minimumDistance = (long)Integer.MAX_VALUE;
80: // ASK slow ?
81: for ( int center = 0; center <= maxPosition; center++ )
82: {
83: long currentTotalDistance = 0;
84: for ( int ind = 0; ind <= maxPosition; ind++ )
85: {
86: if ( position_crabs.containsKey( ind ) )
87: {
88: int crabsHere = position_crabs.get( ind );
89: currentTotalDistance += crabsHere * Math.abs( center - ind );
90: if ( currentTotalDistance > minimumDistance )
91: break; // ASK part 2 ?
92: }
93: }
94: if ( currentTotalDistance < minimumDistance )
95: {
96: minimumDistance = currentTotalDistance;
97: if ( testing )
98: System.out.println( "cmin at "+ center +" is "+ minimumDistance );
99: }
100: }
101:
102: System.out.println( "\t"+ minimumDistance );
103: }
104:
105:
106: }
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
Generated by git2html.