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

2

u/Sgt_Tailor Dec 02 '18

AWK all the things!

part1:

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
}

part2:

{
    boxes[NR] = $0
}

function compareBoxes(boxA, boxB,        i, boxACharacters, boxBCharacters, characterCount) {
    differences = 0
    commonCharacters = ""
    split(boxA, boxACharacters, "")
    split(boxB, boxBCharacters, "")

    characterCount = length(boxACharacters)
    for (i=1; i<=characterCount; i++) {
       if (boxACharacters[i] != boxBCharacters[i]) {
           differences++
           continue         
       }

       commonCharacters = commonCharacters boxACharacters[i]
    }
}

END {
    for (i in boxes) {
        for (j in boxes) {
            if (i==j) continue; #the same boxes don't count
             boxA = boxes[i]
             boxB = boxes[j]

             compareBoxes(boxA, boxB)
             if (differences == 1) {
                 print commonCharacters
                 exit                      
            }
        }                  
    }
}