Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Main {
- public static void main(String[] args) throws IOException {
- // Reads input and loads into the ElfFileSystem using the
- List<String> data = IOUtils.readInputFile("day07input");
- ElfFileSystem fs = new ElfFileSystem(data);
- // Generates a map with all the paths in the ElfFileSystem with its whole size
- Map<Path, Integer> pathSize = fs.getElfFileSystemPaths().stream()
- .collect(Collectors.toMap(i -> i, fs::getPathContentSize));
- // --------- Part 1, my input answer 1350966 ---------
- int part1 = pathSize.values().stream().filter(i -> i < 100000).mapToInt(i -> i).sum();
- System.out.println("Part 1: " + part1);
- // --------- Part 2, my input answer 6296435 ---------
- int neededSpace = pathSize.values().stream()
- .sorted(Comparator.reverseOrder()).limit(1)
- .findFirst().orElse(-1) + 30000000 - 70000000;
- int part2 = pathSize.values().stream().filter(i -> i >= neededSpace)
- .mapToInt(i -> i)
- .sorted()
- .limit(1).findFirst().orElse(-1);
- System.out.println("Part 2: " + part2);
- }
- }
- public class FSElement {
- private final int size;
- private final Path path;
- public FSElement(String fileName, Path path) {
- if (Character.isDigit(fileName.charAt(0))) {
- this.size = Integer.parseInt(fileName.split(" ")[0]);
- } else {
- this.size = 0;
- }
- this.path = path;
- }
- public long getSize() {
- return this.size;
- }
- public Path getPath() {
- return this.path;
- }
- }
- public class ElfFileSystem {
- private final List<FSElement> elements;
- private Path currentPath;
- public ElfFileSystem(List<String> data) {
- currentPath = Path.of(File.separator);
- elements = new ArrayList<>();
- for (String line : data) {
- if (line.startsWith("$ cd")) {
- setPath(line.split(" ")[2]);
- } else if (!line.startsWith("$ ls")) {
- elements.add(new FSElement(line, currentPath));
- }
- }
- }
- private void setPath(String goTo) {
- if (goTo.equals("..")) {
- currentPath = currentPath.getParent();
- } else if (goTo.equals("/")) {
- currentPath = Path.of(File.separator);
- } else {
- currentPath = Path.of(currentPath.toString() + File.separator + goTo);
- }
- }
- public int getPathContentSize(Path path) {
- int size = 0;
- for (FSElement element : elements) {
- if (element.getPath().toString().contains(path.toString())) {
- size += element.getSize();
- }
- }
- return size;
- }
- public Set<Path> getElfFileSystemPaths() {
- return elements.stream().map(FSElement::getPath).collect(Collectors.toSet());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement