Files
typescript-katas/5kyu/closest-and-smallest/solution.ts
2025-02-02 22:08:01 +01:00

60 lines
1.5 KiB
TypeScript

const weight = (s: string): number => s.split('').reduce((acc, cur) => acc + parseInt(cur), 0);
const sortWeightInfo = <T extends WeightInfo | DiffInfo>(a: T, b: T): number => {
if (a[0] !== b[0]) {
return a[0] - b[0];
} else if (a[1] !== b[1]) {
return a[1] - b[1];
} else {
return a[2] - b[2];
}
}
type WeightInfo = [
number, // weight
number, // index
number // number
];
type DiffInfo = [
number, // weight difference
number, // weight sum
number, // index sum
number, // index of first number
number // index of second number
];
export function closest(strng: string): number[][] {
if (strng === '') return [];
const weights: WeightInfo[] = strng
.split(' ')
.map((s, i) => [weight(s), i, parseInt(s)]);
// calculate all weight differences, weight sum, and index sum
const diffs: DiffInfo[] = [];
for (const [weight, index, num] of weights) {
for (let i = index + 1; i < weights.length; i++) {
if(i >= weights.length) break;
const [weight2, index2, num2] = weights[i];
const weightDiff = Math.abs(weight - weight2);
const weightSum = weight + weight2;
const indexSum = index + index2;
diffs.push([weightDiff, weightSum, indexSum, index, index2]);
}
}
// sort by weight difference, weight sum, and index sum
diffs.sort(sortWeightInfo);
const minimumDiff = diffs[0]
const firstNumIndex = minimumDiff[3];
const secondNumIndex = minimumDiff[4];
const result = [
weights[firstNumIndex],
weights[secondNumIndex]
].sort(sortWeightInfo)
return result;
}