skip to content

AOC 22 Day 3 🎒

Advent of Code 2022 Day 3 - Rucksack Reorganization - A group of Elves are going on a jungle journey and one Elf failed to follow the packing instructions for the rucksacks, causing items to be placed in the wrong compartments.

Problem🤔

Rucksack Reorganization: One Elf has the important job of loading all of the rucksacks with supplies for the jungle journey. Unfortunately, that Elf didn’t quite follow the packing instructions, and so a few items now need to be rearranged.

Each rucksack has two large compartments. All items of a given type are meant to go into exactly one of the two compartments. The Elf that did the packing failed to follow this rule for exactly one item type per rucksack.

The Elves have made a list of all of the items currently in each rucksack (your puzzle input), but they need your help finding the errors. Every item type is identified by a single lowercase or uppercase letter (that is, a and A refer to different types of items).

The list of items for each rucksack is given as characters all on a single line. A given rucksack always has the same number of items in each of its two compartments, so the first half of the characters represent items in the first compartment, while the second half of the characters represent items in the second compartment.

Sample Data

For example, suppose you have the following list of contents from six rucksacks:

vJrwpWtwJgWrhcsFMMfFFhFp
jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
PmmdzqPrVvPwwTWBwg
wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
ttgJtRGJQctTZtZT
CrZsJsPPZsGzwwsLwLmpwMDw
vJrwpWtwJgWrhcsFMMfFFhFp
jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
PmmdzqPrVvPwwTWBwg
wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
ttgJtRGJQctTZtZT
CrZsJsPPZsGzwwsLwLmpwMDw

This strategy guide predicts and recommends the following:

  • The first rucksack contains the items vJrwpWtwJgWrhcsFMMfFFhFp, which means its first compartment contains the items vJrwpWtwJgWr, while the second compartment contains the items hcsFMMfFFhFp. The only item type that appears in both compartments is lowercase p.
  • The second rucksack’s compartments contain jqHRNqRjqzjGDLGL and rsFMfFZSrLrFZsSL. The only item type that appears in both compartments is uppercase L.
  • The third rucksack’s compartments contain PmmdzqPrV and vPwwTWBwg; the only common item type is uppercase P.
  • The fourth rucksack’s compartments only share item type v.
  • The fifth rucksack’s compartments only share item type t.
  • The sixth rucksack’s compartments only share item type s.

To help prioritize item rearrangement, every item type can be converted to a priority:

  • Lowercase item types a through z have priorities 1 through 26.
  • Uppercase item types A through Z have priorities 27 through 52.

Part 1

In the above example, the priority of the item type that appears in both compartments of each rucksack is 16 p, 38 L, 42 P, 22 v, 20 t, and 19 s; the sum of these is 157.

What is the sum of the priorities of those item types?

Solution 1💡

import { input } from './input.ts';
 
// Split the input into an array of strings,one string per rucksack
const rugSacks = input.split('\n');
 
// This string defines the order of
// the letters, from lowest to highest priority
const LetterPriority =
  ' abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
 
// This variable will keep track of the total number of points
let count = 0;
 
// Loop through each rucksack
rugSacks.forEach(([...items]) => {
  // Split the items into two arrays, the first half and the second half
  let first = items.slice(0, items.length / 2);
  let last = items.slice(items.length / 2, items.length);
 
  // Keep track of items that have already been counted
  let blackList = new Set<string>();
 
  // Loop through each item in the first half of the rucksack
  first.forEach((f) => {
    // If the item hasn't been counted yet...
    if (!blackList.has(f)) {
      // Add the priority of the matching item in the
      // second half of the rucksack to the total count
      count += LetterPriority.indexOf(
        last.find((l) => l === f) ?? ''
      );
 
      // Mark the item as counted
      blackList.add(f);
    }
  });
});
 
// Print the final count
console.log(count);
import { input } from './input.ts';
 
// Split the input into an array of strings,one string per rucksack
const rugSacks = input.split('\n');
 
// This string defines the order of
// the letters, from lowest to highest priority
const LetterPriority =
  ' abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
 
// This variable will keep track of the total number of points
let count = 0;
 
// Loop through each rucksack
rugSacks.forEach(([...items]) => {
  // Split the items into two arrays, the first half and the second half
  let first = items.slice(0, items.length / 2);
  let last = items.slice(items.length / 2, items.length);
 
  // Keep track of items that have already been counted
  let blackList = new Set<string>();
 
  // Loop through each item in the first half of the rucksack
  first.forEach((f) => {
    // If the item hasn't been counted yet...
    if (!blackList.has(f)) {
      // Add the priority of the matching item in the
      // second half of the rucksack to the total count
      count += LetterPriority.indexOf(
        last.find((l) => l === f) ?? ''
      );
 
      // Mark the item as counted
      blackList.add(f);
    }
  });
});
 
// Print the final count
console.log(count);

This code reads a list of strings from the input variable, where each string represents a rucksack and its contents. The code then splits each string into two halves, and for each item in the first half of the string, it looks for a matching item in the second half of the string. If a matching item is found, the code adds the priority of the item to a total count. The final count is then printed to the console.

The input variable holds the list of rucksacks and their contents. This variable is not defined in this code, so it must be defined elsewhere.

The rugSacks variable is an array of strings, where each string represents a rucksack and its contents. This array is created by splitting the input string on the newline character \n, using the split() method.

The LetterPriority variable is a string that defines the order of the letters, from lowest to highest priority. In this case, the string contains all the letters of the alphabet, both uppercase and lowercase, with a space character at the beginning.

The count variable is a number that will keep track of the total number of points. It is initially set to 0.

The rugSacks.forEach() method loops through each string in the rugSacks array. The code inside the forEach() method will be executed once for each string in the array.

The items variable is an array that holds the items in the current rucksack. It is created by spreading the string into an array of characters, using the spread syntax [...].

The first variable is an array that holds the items in the first half of the rucksack. It is created by calling the slice() method on the items array, passing 0 as the starting index and items.length / 2 as the ending index.

The last variable is an array that holds the items in the second half of the rucksack. It is created by calling the slice() method on the items variable.

After the last variable is set, the code creates a blackList set to keep track of items that have already been counted to avoid double-counting. It then loops through each item in the first array, and if the item hasn’t been counted yet, it adds the priority of the matching item in the last array to the total count, using the LetterPriority string to determine the priority of each letter. Finally, the code marks the item as counted by adding it to the blackList set.

Part 2

As you finish identifying the misplaced items, the Elves come to you with another issue.

For safety, the Elves are divided into groups of three. Every Elf carries a badge that identifies their group. For efficiency, within each group of three Elves, the badge is the only item type carried by all three Elves. That is, if a group’s badge is item type B, then all three Elves will have item type B somewhere in their rucksack, and at most two of the Elves will be carrying any other item type.

The problem is that someone forgot to put this year’s updated authenticity sticker on the badges. All of the badges need to be pulled out of the rucksacks so the new authenticity stickers can be attached.

Additionally, nobody wrote down which item type corresponds to each group’s badges. The only way to tell which item type is the right one is by finding the one item type that is common between all three Elves in each group.

Every set of three lines in your list corresponds to a single group, but each group can have a different badge item type. So, in the above example, the first group’s rucksacks are the first three lines:

vJrwpWtwJgWrhcsFMMfFFhFp
jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
PmmdzqPrVvPwwTWBwg
vJrwpWtwJgWrhcsFMMfFFhFp
jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
PmmdzqPrVvPwwTWBwg

And the second group’s rucksacks are the next three lines:

wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
ttgJtRGJQctTZtZT
CrZsJsPPZsGzwwsLwLmpwMDw
wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
ttgJtRGJQctTZtZT
CrZsJsPPZsGzwwsLwLmpwMDw

In the first group, the only item type that appears in all three rucksacks is lowercase r; this must be their badges. In the second group, their badge item type must be Z.

Priorities for these items must still be found to organize the sticker attachment efforts: here, they are 18 r for the first group and 52 Z for the second group. The sum of these is 70.

Find the item type that corresponds to the badges of each three-Elf group. What is the sum of the priorities of those item types?

Solution 2💡

import { input } from './input.ts';
 
// Split the input into an array of strings, one string per rucksack
const rugSacks = input.split('\n');
 
// Group the rucksacks into groups of 3
const groupedRugSacks: string[][][] = [];
let currentGroup: string[][] = [];
rugSacks.forEach((r, i) => {
  // Add the current rucksack to the current group
  currentGroup.push([...r]);
 
  // If this is the last rucksack, push the current
  // group to the final array and return
  if (i === rugSacks.length - 1) {
    groupedRugSacks.push(currentGroup);
    return;
  }
 
  // If this is the last rucksack in a group of 3, push the
  // current group to the final array and reset the current group
  if (i % 3 === 0 && i !== 0) {
    groupedRugSacks.push(currentGroup);
    currentGroup = [];
  }
 
  // Add the current rucksack to the current group
  currentGroup.push([...r]);
});
 
// This string defines the order of the letters,
// from lowest to highest priority
const LetterPriority =
  ' abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
 
// This variable will keep track of the total number of points
let count = 0;
 
// Loop through each group of 3 rucksacks
groupedRugSacks.forEach((gr) => {
  // Find the items that are common to all 3 rucksacks in the group
  const common = gr[0].filter(
    (x) => gr[1].includes(x) && gr[2].includes(x)
  );
 
  // Add the priority of the first common item to the total count
  count += LetterPriority.indexOf(common[0] ?? '');
});
 
// Print the final count
console.log(count);
import { input } from './input.ts';
 
// Split the input into an array of strings, one string per rucksack
const rugSacks = input.split('\n');
 
// Group the rucksacks into groups of 3
const groupedRugSacks: string[][][] = [];
let currentGroup: string[][] = [];
rugSacks.forEach((r, i) => {
  // Add the current rucksack to the current group
  currentGroup.push([...r]);
 
  // If this is the last rucksack, push the current
  // group to the final array and return
  if (i === rugSacks.length - 1) {
    groupedRugSacks.push(currentGroup);
    return;
  }
 
  // If this is the last rucksack in a group of 3, push the
  // current group to the final array and reset the current group
  if (i % 3 === 0 && i !== 0) {
    groupedRugSacks.push(currentGroup);
    currentGroup = [];
  }
 
  // Add the current rucksack to the current group
  currentGroup.push([...r]);
});
 
// This string defines the order of the letters,
// from lowest to highest priority
const LetterPriority =
  ' abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
 
// This variable will keep track of the total number of points
let count = 0;
 
// Loop through each group of 3 rucksacks
groupedRugSacks.forEach((gr) => {
  // Find the items that are common to all 3 rucksacks in the group
  const common = gr[0].filter(
    (x) => gr[1].includes(x) && gr[2].includes(x)
  );
 
  // Add the priority of the first common item to the total count
  count += LetterPriority.indexOf(common[0] ?? '');
});
 
// Print the final count
console.log(count);

Let starts by importing an input file called input.ts and splitting the input into an array of strings, with one string per rucksack.

Next, create an empty array groupedRugSacks and an empty array currentGroup. It then loops through each rucksack, adding each rucksack to currentGroup, and pushing currentGroup to groupedRugSacks whenever the loop is at the last rucksack or at every third rucksack, resetting currentGroup to be an empty array after pushing it to groupedRugSacks.

Now, lets defines a LetterPriority string, which defines the order of the letters from lowest to highest priority. We can also initializes the count variable to zero, which will be used to keep track of the total number of points.

We can loop through each group of rucksacks (where a group is an array of three rucksacks) in groupedRugSacks and finds the common items in each rucksack. It then adds the priority of the first common item to the count variable.

Finally we can find the priority by logging it.

const: This keyword is used to declare a variable that cannot be reassigned.

split(): This method is used to split a string into an array of substrings based on a specified separator string.

forEach(): This method is used to execute a function on each element in an array.

indexOf(): This method is used to find the index of the first occurrence of a specified substring in a string.

find(): This method is used to return the value of the first element in an array that satisfies a specified condition.

Set: This type represents a collection of unique values.

has(): This method is used to check whether a set contains a specified element.

add(): This method is used to add a new element to a set.

log(): This method is used to print output to the console.