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/Sgt_Tailor Dec 02 '18

I did do the first part in awk and will do the second part as well.

PART 1 solution:

function handleBox(box,     characters, characterLength, characterCount, i, letterCount) {
    split(box, characters, "");
    characterLength = length(characters)
    
    # create a dict with the counts per character
    for (i=1; i <= characterLength; i++) {
        characterCount[characters[i]]++
    }
 
    # these variable are expose and used in the main function.
    wordHas2 = 0
    wordHas3 = 0

    # loop over the charactercounts and check if they are 2 or 3.
    for (i in characterCount) {
        letterCount = characterCount[i];
        if (letterCount == 2) {
          wordHas2  = 1
        }

        if (letterCount == 3) {
              wordHas3 = 1;
        }
    }
}

# this is the main function, called for every line within the input
# we handle the input and add the results to the global variables total2
# and total3
{
    handleBox($0)
    total2 = total2 + wordHas3
    total3 = total3 + wordHas2
}


# called after all the input has been handled. Used to print the checksum
END {
    print total2 * total3
}