day9_pt2.java (1910B)
1 import java.nio.file.Files; 2 import java.nio.file.Path; 3 import java.io.IOException; 4 import java.util.*; 5 import java.util.stream.*; 6 7 public class day9_pt2 { 8 public static void main(String[] args) throws IOException { 9 var input = Files.readString(Path.of(args[0])); 10 var dm = new ArrayList<Integer>(); 11 int label = 0; 12 boolean block = true; 13 var it = input.chars().iterator(); 14 while (it.hasNext()) { 15 var ct = it.next() - '0'; 16 var add = block ? label : -1; 17 for (int i=0;i<ct;i++) dm.add(add); 18 label += block ? 1 : 0; 19 block = !block; 20 } 21 label--; 22 //System.out.printf("dm [%s]\n", dm); 23 24 25 while (label >= 0) { 26 var fStart = dm.indexOf(label); 27 var fEnd = dm.lastIndexOf(label)+1; 28 var fLen = fEnd-fStart; 29 30 // find first free space 31 var sStart = 0; 32 while (sStart < dm.size() && dm.get(sStart) != -1) sStart++; 33 34 while (sStart < dm.size() && sStart < fStart) { 35 var sEnd = sStart; 36 while (dm.get(sEnd) == -1) sEnd++; 37 var sLen = sEnd-sStart; 38 if (sLen >= fLen) { 39 //System.out.printf("moving label %d sLen %d sStart %d sEnd %d fStart %d fEnd %d\n", label, sLen, sStart, sEnd, fStart, fEnd); 40 for (var j=sStart; j<sStart+fLen; j++) dm.set(j, label); 41 for (var j=fStart; j<fEnd; j++) dm.set(j, -1); 42 break; 43 } else { 44 // space wasnt big enough, find the next free space 45 sStart = sEnd; 46 while (sStart < dm.size() && dm.get(sStart) != -1) sStart++; 47 } 48 } 49 label--; 50 } 51 //System.out.printf("dm [%s]\n", dm); 52 long ck = 0; 53 for (int i=0;i<dm.size();i++){ 54 long ch = dm.get(i); 55 if (ch != -1) ck += (long)i * ch; 56 } 57 System.out.printf("day9, pt2: %d\n", ck); 58 } 59 }