DEV Community

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

Posted on

Advent of Code 2021 - Day 1: Puzzle 2

Hi all!

Here is my solution of the second puzzle of Advent of Code, Day 1.

package main;

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

public class Puzzle {

  public static void main(String[] args) {
    try {
      File input = new File("/Users/files/input.txt");
      Scanner scanner = new Scanner(input);
      List<Integer> numbers = new ArrayList<>();

      while (scanner.hasNextLine()) numbers.add(Integer.parseInt(scanner.nextLine()));

      int count = 0;

      for (int i = 1; i < numbers.size() - 2; i++) {
        int value = numbers.get(i) + numbers.get(i + 1) + numbers.get(i + 2);
        int previousValue = numbers.get(i - 1) + numbers.get(i) + numbers.get(i + 1);
        if (value > previousValue) count++;
      }
      System.out.println(count);
    } catch (Exception e) {
      System.out.println("Exception!");
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Discussion (0)