DEV Community

Cover image for Advent of Code - Day 7: Puzzle 2
Petra
Petra

Posted on

Advent of Code - Day 7: Puzzle 2

Puzzle

--- Part Two ---

The crabs don't seem interested in your proposed solution. Perhaps you misunderstand crab engineering?

As it turns out, crab submarine engines don't burn fuel at a constant rate. Instead, each change of 1 step in horizontal position costs 1 more unit of fuel than the last: the first step costs 1, the second step costs 2, the third step costs 3, and so on.

As each crab moves, moving further becomes more expensive. This changes the best horizontal position to align them all on; in the example above, this becomes 5:

Move from 16 to 5: 66 fuel
Move from 1 to 5: 10 fuel
Move from 2 to 5: 6 fuel
Move from 0 to 5: 15 fuel
Move from 4 to 5: 1 fuel
Move from 2 to 5: 6 fuel
Move from 7 to 5: 3 fuel
Move from 1 to 5: 10 fuel
Move from 2 to 5: 6 fuel
Move from 14 to 5: 45 fuel
This costs a total of 168 fuel. This is the new cheapest possible outcome; the old alignment position (2) now costs 206 fuel instead.

Determine the horizontal position that the crabs can align to using the least fuel possible so they can make you an escape route! How much fuel must they spend to align to that position?*

My solution

package main;

import java.io.File;
import java.util.*;

public class Puzzle {

  public static int calculateSteps(int startIndex, int endIndex) {
    List<Integer> differences = new ArrayList<>();
    int subtotal = 0;

    for (int k = startIndex; k < endIndex; k++) {
      subtotal++;
      differences.add(subtotal);
    }
    return differences.stream().mapToInt(Integer::intValue).sum();
  }

  public static void main(String[] args) throws Exception {
    File input = new File("/Users/files/input.txt");
    Scanner scanner = new Scanner(input);

    List<Integer> numbers = new ArrayList<>();
    List<Integer> values = new ArrayList<>();

    while (scanner.hasNext()) {
      String[] arrayOfNumbers = scanner.nextLine().split(",");
      for (String number : arrayOfNumbers) {
        numbers.add(Integer.parseInt(number));
      }
    }

    int total = 0;
    for (int i = 0; i < numbers.size(); i++) {
      total = 0;
      for (Integer number : numbers) {

        if (i > number) {

          int sum = calculateSteps(number, i);
          total += sum;

        } else if (number > i) {

          int sum = calculateSteps(i, number);
          total += sum;
        }
      }
      values.add(total);
    }

    int minValue = Collections.min(values);

    System.out.println(minValue);
  }
}

Enter fullscreen mode Exit fullscreen mode

*Source: https://adventofcode.com/2021/day/7

Top comments (0)