r/adventofcode • • Dec 02 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 2 Solutions -🎄-

--- Day 2: Inventory Management System ---


Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


Advent of Code: The Party Game!

Click here for rules

Card Prompt: Day 2

Transcript:

The best way to do Advent of Code is ___.


This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.

edit: Leaderboard capped, thread unlocked!

51 Upvotes

407 comments sorted by

View all comments

Show parent comment

1

u/niclas0219 Dec 28 '18

Very nice!

I just started redoing all of the days trying to use other approaches than i did the first time. The have really learned alot since the first day and the room for improvement through all of the days are huge! Here is my Java solution for part 1 and part 2. I am cheating a little bit by reading the input into an ArrayList (strings) in my main method. Please comment if you have any nice tips to make it more compact!

int i;
    String last = "";

    @Override
    public void init() {

        long checksum = strings.stream().map(s -> s.toCharArray()).filter(s -> count(s, 2)).count();
        checksum *= strings.stream().map(s -> s.toCharArray()).filter(s -> count(s, 3)).count();
        System.out.println("Part 1 = " + checksum);

        for (i = 0; i < strings.get(0).length(); i++) {
            strings.stream().map(s -> s.substring(0, i) + s.substring(i + 1)).sorted().forEach(s -> {
                if (last.equals(s)) {
                    System.out.println("Part 2 = " + s);
                } else {
                    last = s;
                }
            });
        }
    }

    public static Boolean count(char[] t, int n) {
        Arrays.sort(t);
        char last = t[0];
        int count = 1;
        for (int i = 1; i < t.length; i++) {
            if (t[i] == last) {
                count++;
            } else {
                if (count == n) {
                    return true;
                }
                count = 1;
                last = t[i];
            }
        }

        if (count == n) {
            return true;
        }

        return false;
    }