Untitled

 avatar
unknown
plain_text
3 years ago
914 B
3
Indexable
const solve = (input: string) => {
  const rucksacks = input.split('\n');
  // Find the item type that appears in both compartments of each rucksack
  let sumOfPriorities = 0;
  for (const rucksack of rucksacks) {
    const firstCompartment = rucksack.substr(0, rucksack.length / 2);
    const secondCompartment = rucksack.substr(rucksack.length / 2);
    let commonItemType = null;
    for (const itemType of new Set(firstCompartment)) {
      if (secondCompartment.includes(itemType)) {
        commonItemType = itemType;
        break;
      }
    }
    if (commonItemType) {
      // Calculate the priority of the item type
      const priority =
        commonItemType.charCodeAt(0) >= 'a'.charCodeAt(0)
          ? commonItemType.charCodeAt(0) - 'a'.charCodeAt(0) + 1
          : commonItemType.charCodeAt(0) - 'A'.charCodeAt(0) + 27;
      sumOfPriorities += priority;
    }
  }
  return sumOfPriorities;
};
Editor is loading...