Advertisement
Eddy_S

Advent of Code Day 1

Dec 1st, 2020 (edited)
452
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.24 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.Collections;
  3. import java.util.Scanner;
  4. import java.io.File;
  5. import java.io.FileNotFoundException;
  6.  
  7.  
  8.  
  9. public class D1 {
  10.     public ArrayList<Integer> parseInput(String filename) {
  11.         ArrayList<Integer> inputs = new ArrayList<Integer>();
  12.         File f = new File(filename);
  13.         try (Scanner scan = new Scanner(f)) {
  14.             while (scan.hasNextInt()) {
  15.                 inputs.add(new Integer(scan.nextInt()));
  16.             }
  17.         } catch (FileNotFoundException e) {
  18.         }
  19.         return inputs;
  20.     }
  21.  
  22.     public int getProduct(ArrayList<Integer> inputs) {
  23.         // NEW VERSION FROM REDDIT https://www.reddit.com/r/adventofcode/comments/k4e4lm/2020_day_1_solutions/ge93rku/
  24.         int start = 0;
  25.         int end = inputs.size() - 1;
  26.         Collections.sort(inputs);
  27.         int sum = inputs.get(start).intValue() + inputs.get(end).intValue();
  28.         while (sum != 2020) {
  29.             if (sum > 2020) {
  30.                 end--;
  31.             } else {
  32.                 start++;
  33.             }
  34.             sum = inputs.get(start).intValue() + inputs.get(end).intValue();
  35.             if (start > end) {
  36.                 break;
  37.             }
  38.         }
  39.         int total = inputs.get(start).intValue() * inputs.get(end).intValue();
  40.         return total;
  41.  
  42.         //
  43.         // ORIGINAL VERSION
  44.         //
  45.         // ArrayList<Integer> reversedInputs = new ArrayList<Integer>(inputs);
  46.         // Collections.reverse(reversedInputs);
  47.         // for (Integer start : inputs) {
  48.         //     for (Integer end : reversedInputs) {
  49.         //         if (start.intValue() + end.intValue() == goal) {
  50.         //             total = start.intValue() * end.intValue();
  51.         //             return total;
  52.         //         }
  53.         //     }
  54.         // }
  55.         // return total;
  56.     }
  57.  
  58.     public static void main(String[] args) {
  59.         final long startTime = System.nanoTime();
  60.         D1 dayOne = new D1();
  61.         ArrayList<Integer> inputs = dayOne.parseInput("input.txt");
  62.         int total = dayOne.getProduct(inputs);
  63.         System.out.println(total);
  64.         final long duration = System.nanoTime() - startTime;
  65.         System.out.println(duration / 1000000000);
  66.     }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement