day9_pt1.java (1380B)
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_pt1 { 8 9 public static void main(String[] args) throws IOException { 10 var input = Files.readString(Path.of(args[0])); 11 //System.out.printf("input [%s]\n", input); 12 var dm = new ArrayList<Integer>(); 13 14 // Naïve way; just create the raw disk map as an arraylist... 15 int label = 0; 16 boolean block = true; 17 var it = input.chars().iterator(); 18 while (it.hasNext()) { 19 var ct = it.next() - '0'; 20 var add = block ? label : -1; 21 for (int i=0;i<ct;i++) dm.add(add); 22 label += block ? 1 : 0; 23 block = !block; 24 } 25 //System.out.printf("dm [%s]\n", dm); 26 27 // now compact it 28 for (int i=0;i<dm.size()-1;i++) { // use .size() every time, it changes. Also don't check the very last item 29 var ch = dm.get(i); 30 if (ch == -1) { 31 var ins = -1; 32 while (ins == -1) ins = dm.removeLast(); 33 dm.set(i, ins); 34 } 35 } 36 // trim 37 if (dm.getLast() == -1) dm.removeLast(); 38 39 // checksum 40 long ck = 0; 41 for (int i=0;i<dm.size();i++){ 42 ck += (long)i * (long)dm.get(i); 43 } 44 45 //System.out.printf("dm [%s]\n", dm); 46 47 System.out.printf("day9, pt1: %d\n", ck); 48 } 49 }