I am finally catching up to Day 1 of this year's Advent of Code. In this problem, we are asked to determine how many times the depth of the ocean floor increases. Part B of the problem asks us modify the solution to consider a sliding window of depths.
If we were to plot the example given in the problem we can see the instances in which the depth increases. There are 7 such increases.
To solve part a, we need to compare the previous depth to the current one and increase a counter, as shown in the following function -Integer prev = null; Integer counter = 0; File myObj = new File(inputFile); Scanner reader = new Scanner(myObj); while (reader.hasNextLine()) { Integer depth = Integer.parseInt(reader.nextLine()); if (prev != null && depth > prev) counter++; prev = depth; } reader.close();
The problem gets interesting when we need to solve for increases in a 3 element sliding window. We now need to keep track of the sum of depths in the previous sliding window, and compare it to the current one.
In order to solve part b, we maintain a queue of elements representing the sliding window. Depths can be added and removed as they come or go out of window, and this action is used to adjust the sum of depths in the sliding windowThe following function uses an ArrayQueue to keep track of the depths in a sliding window. Once the sliding window is full, we start to compare the previous sums (prev). The current sliding window sum is updated by subtracting the depth that has gone out of window
Integer prev = null; Integer counter = 0; Integer slidingWindowSum = 0; ArrayDeque<Integer> slidingWindow = new ArrayDeque<>(); File myObj = new File(inputFile); Scanner reader = new Scanner(myObj); while (reader.hasNextLine()) { Integer depth = Integer.parseInt(reader.nextLine()); // track the depth in the sliding window queue and also track sliding window sum slidingWindow.add(depth); slidingWindowSum += depth; // if we are tracking enough depths we can start comparing the prev sliding sum if (slidingWindow.size() > slidingWindowSize) { slidingWindowSum -= slidingWindow.pop(); // subtract depth out of window if (prev < slidingWindowSum) counter++; } prev = slidingWindowSum; }
Full source code can be found here -
https://github.com/jasoncoelho/adventOfCode2021/blob/main/1/run.java