Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Scanner;
- import java.io.File;
- import java.io.FileNotFoundException;
- public class D1 {
- public ArrayList<Integer> parseInput(String filename) {
- ArrayList<Integer> inputs = new ArrayList<Integer>();
- File f = new File(filename);
- try (Scanner scan = new Scanner(f)) {
- while (scan.hasNextInt()) {
- inputs.add(new Integer(scan.nextInt()));
- }
- } catch (FileNotFoundException e) {
- }
- return inputs;
- }
- public int getProduct(ArrayList<Integer> inputs) {
- // NEW VERSION FROM REDDIT https://www.reddit.com/r/adventofcode/comments/k4e4lm/2020_day_1_solutions/ge93rku/
- int start = 0;
- int end = inputs.size() - 1;
- Collections.sort(inputs);
- int sum = inputs.get(start).intValue() + inputs.get(end).intValue();
- while (sum != 2020) {
- if (sum > 2020) {
- end--;
- } else {
- start++;
- }
- sum = inputs.get(start).intValue() + inputs.get(end).intValue();
- if (start > end) {
- break;
- }
- }
- int total = inputs.get(start).intValue() * inputs.get(end).intValue();
- return total;
- //
- // ORIGINAL VERSION
- //
- // ArrayList<Integer> reversedInputs = new ArrayList<Integer>(inputs);
- // Collections.reverse(reversedInputs);
- // for (Integer start : inputs) {
- // for (Integer end : reversedInputs) {
- // if (start.intValue() + end.intValue() == goal) {
- // total = start.intValue() * end.intValue();
- // return total;
- // }
- // }
- // }
- // return total;
- }
- public static void main(String[] args) {
- final long startTime = System.nanoTime();
- D1 dayOne = new D1();
- ArrayList<Integer> inputs = dayOne.parseInput("input.txt");
- int total = dayOne.getProduct(inputs);
- System.out.println(total);
- final long duration = System.nanoTime() - startTime;
- System.out.println(duration / 1000000000);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement