Skip to content

Instantly share code, notes, and snippets.

@rherrick
Created December 19, 2018 21:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rherrick/a5729b633a11f17c01b45ff5b4c8c957 to your computer and use it in GitHub Desktop.
Save rherrick/a5729b633a11f17c01b45ff5b4c8c957 to your computer and use it in GitHub Desktop.
Refactor of advent day 1 code
package com.nerdnetworks;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
public static void main(String[] args) throws IOException {
// Use of streams and closure below requires final variables.
// Use Atomic* objects for accumulator-type objects.
final AtomicInteger startingFreq = new AtomicInteger();
// The value in the map was never used, so a set is more straightforward.
final Set<Integer> foundFreqs = new HashSet<>();
// Line below reads lines from file, converts each line to an integer, and iterates over them, all in one step.
Files.readAllLines(Paths.get("/Users/rherrick/Development/Reference/Gradle/advent/data/day-1-input.txt")).stream().mapToInt(Integer::parseInt).forEach(value -> {
// Parsing the file lines was basically to get the '+' or '-' at the beginning to decide whether to add or
// subtract the absolute value of the number. This just adds the number directly and lets the sign decide
// the operation. The return value gives you what you got from that exchange of startingFreq and endingFreq.
final int found = startingFreq.addAndGet(value);
if (foundFreqs.contains(found)) {
System.out.println("Repeated frequency: " + found);
} else {
foundFreqs.add(found);
}
});
// Result has accumulated in the startingFreq object.
System.out.println(startingFreq.get());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment