r/adventofcode • • Dec 03 '22

SOLUTION MEGATHREAD -🎄- 2022 Day 3 Solutions -🎄-

NEWS

  • Solutions have been getting longer, so we're going to start enforcing our rule on oversized code.
  • The Visualizations have started! If you want to create a Visualization, make sure to read the guidelines for creating Visualizations before you post.
  • Y'all may have noticed that the hot new toy this year is AI-generated "art".
    • We are keeping a very close eye on any AI-generated "art" because 1. the whole thing is an AI ethics nightmare and 2. a lot of the "art" submissions so far have been of little real quality.
    • If you must post something generated by AI, please make sure it will actually be a positive and quality contribution to /r/adventofcode.
    • Do not flair AI-generated "art" as Visualization. Visualization is for human-generated art.

FYI


--- Day 3: Rucksack Reorganization ---


Post your code solution in this megathread.


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

EDIT: Global leaderboard gold cap reached at 00:05:24, megathread unlocked!

88 Upvotes

1.6k comments sorted by

View all comments

4

u/ciemrnt Dec 03 '22

C++ - s1 = o(N) & s2 = o(N)

class AdventOfCode
{
private:

    void closeFile(ifstream &input_file) {
        input_file.clear();
        input_file.seekg(0, ios::beg);
    }

public:

    int part1(ifstream &input_file) {
        int sumOfDuplicateItems = 0;
        unordered_map<char, int> visitedItems;
        string str;

        while(getline(input_file, str)) {
            visitedItems = {};
            for (int i = 0; i < str.length() / 2; i++) {
                visitedItems[str[i]] = 1;
            }
            for (int i = str.length() / 2; i < str.length(); i++) {
                char chr = str[i];
                if (visitedItems[chr] == 1) {
                    visitedItems[chr]++;
                    sumOfDuplicateItems += (chr <= 90) ? chr - 38 : chr - 96;
                }
            }
        }

        closeFile(input_file);
        return sumOfDuplicateItems;
    }

    int part2(ifstream &input_file) {
        int sumOfDuplicateItems = 0, grp_index = 0;
        unordered_map<char, int> visitedItems, visitedGrpItems;
        string str;

        while(getline(input_file, str)) {
            if (grp_index++ == 3) {
                grp_index = 1;
                visitedGrpItems = {};
            }
            visitedItems = {};

            for (int i = 0; i < str.length(); i++) {
                char item = str[i];
                if (++visitedItems[item] == 1 && ++visitedGrpItems[item] == 3) 
                    sumOfDuplicateItems += (item <= 90) ? item - 38 : item - 96;
            }
        }

        closeFile(input_file);
        return sumOfDuplicateItems;
    }
};

int main()
{
    AdventOfCode puzzle;
    ifstream infile("input");

    cout << "Result part one: " << puzzle.part1(infile) << endl;
    cout << "Result part two: " << puzzle.part2(infile) << endl;
}

1

u/daggerdragon Dec 04 '22

Please edit your post to use the four-spaces Markdown syntax for a code block so your code is easier to read on old.reddit and mobile apps.

1

u/slim_toni Dec 03 '22

Another C++ solution

#include <iostream>
#include <string>
#include <vector>
#include <numeric>
#include <algorithm>
#include <iterator>
#include "../include/utils.h"

using namespace std;


int main (int argc, char **argv) 
{
    // Create a string that has all the item types (alpahbet letters) in order of priority
    // To do so, take the ASCII values of the lower and uppercase letters, and add them to string
    int lower_begin = 97;
    int lower_end = 122;
    int upper_begin = 65;
    int upper_end = 90;
    string letters;

    for (int i = lower_begin; i < lower_end + 1; i++) 
    {
        letters.push_back(i);
    }
    for (int i = upper_begin; i < upper_end + 1; i++) 
    {
        letters.push_back(i);
    }

    // Initialize variables to keep track of priority sums
    int prioritiesPart1 = 0;
    int prioritiesPart2 = 0;
    const int N = letters.length(); // Number of item types
    int itemTypeFreq[N] {0}; // How many times a type appears in each elf group
    int elfCount = 0; // Keep track of elf rucksacks analyzed

    // Process input
    vector<string> inputLines = utils::readFileLines(argv[1]);
    for (auto line : inputLines) 
    {
        elfCount++;

        // Part 1
        // Loop through items until we find the type that is in both halves of the string
        for (char& c : line)
        {
            if (line.find(c, line.size()/2) != string::npos) 
            {
                prioritiesPart1 += letters.find(c) + 1; // Find priority of item type and add to total
                break; // Once we found the missplaced type, we're done with this rucksack for Part 1
            }
        }

        // Part 2
        // Get a list of the unique item types carried by this elf
        sort(line.begin(), line.end());
        string itemTypes = string(line.begin(), unique(line.begin(), line.end()));
        // And keep count of the number of elves in this group that carry each type
        for (auto c : itemTypes) {
            itemTypeFreq[letters.find(c)]++;
        }

        // When we reach the third elf of each group, we find the common item type, and reset the count
        if (elfCount % 3 == 0) 
        {
            // Find priority of the item that the common to the 3 elves in the group
            prioritiesPart2 += 1 + distance(itemTypeFreq, find(itemTypeFreq, itemTypeFreq+N, 3));
            fill(itemTypeFreq, itemTypeFreq+N, 0); // Reset item type frequency for next group
        }

    }

    cout << "Solution to Part 1: " << prioritiesPart1 << endl
        << "Solution to Part 2: " << prioritiesPart2;

}