ProjectsAOCBlogAbout

Day 13: Distress Signal

**
Something about some distress signal, but it's out of order. Part I is to figure out which parts are in order and Part II to to put them in order.
Journal

I don't honestly remember a lot about this one.

Basically using eval to turn the input into js objects and then applying some rules.

Lots of magic numbers and I don't really know what's going on. Can't say I'm super proud of this one, tbh.

Relevant Code
const getSignalPairs = (input: string) => {
const lines = input.split("\n");
const { pairs } = lines.reduce(
(accum, line, i) => {
if (i % 3 === 0) {
// eslint-disable-next-line no-eval
accum.currentPair = [eval(line)];
} else if (i % 3 === 1) {
// eslint-disable-next-line no-eval
accum.currentPair.push(eval(line));
accum.pairs.push(accum.currentPair);
}
return accum;
},
{ pairs: [], currentPair: [] } as { pairs: any[][]; currentPair: any[] }
);
return pairs;
};
const getAllSignals = (input: string): any[][] => {
return (
input
.split("\n")
.filter((line) => line)
// eslint-disable-next-line no-eval
.map((line) => eval(line))
);
};
const signalCmp = (left: any[], right: any[]): number => {
if (typeof left === "undefined") {
return -1;
}
if (typeof right === "undefined") {
return 1;
}
for (let i = 0; i < left.length; i++) {
if (typeof left[i] === "number" && typeof right[i] === "number") {
if (left[i] > right[i]) {
return 1;
}
if (left[i] < right[i]) {
return -1;
}
} else {
const leftArray = typeof left[i] === "number" ? [left[i]] : left[i];
const rightArray = typeof right[i] === "number" ? [right[i]] : right[i];
const subIsCorrect = signalCmp(leftArray, rightArray);
if (subIsCorrect) {
return subIsCorrect;
}
}
}
return left.length < right.length ? -1 : 0;
};
const sum = (numbers: number[]) => {
return numbers.reduce((accum, val) => accum + val, 0);
};
// Part I
export const getCorrectIndexSum = (input: string) => {
const signalPairs = getSignalPairs(input);
const indexes = signalPairs.reduce((correctIndexes, pair, i) => {
if (signalCmp(pair[0], pair[1]) === -1) {
correctIndexes.push(i + 1);
}
return correctIndexes;
}, [] as number[]);
return sum(indexes);
};
// Part II
export const sortSignals = (input: string) => {
const signals = getAllSignals(input);
signals.push([2]);
signals.push([6]);
signals.sort(signalCmp);
const twoIndex =
signals.findIndex((signal) => signal[0] === 2 && signal.length === 1) + 1;
const sixIndex =
signals.findIndex((signal) => signal[0] === 6 && signal.length === 1) + 1;
return twoIndex * sixIndex;
};
Output

Test Signal

  1. Part I: 13 (0 ms)
  2. Part II: 140 (0 ms)

Real Signal

  1. Part I: 5905 (6 ms)
  2. Part II: 21691 (8 ms)