Files
typescript-katas/5kyu/smallest-possible-sum/solution.ts
2025-02-03 00:03:07 +01:00

61 lines
1.5 KiB
TypeScript

// idea: find lowest number, subtract it from all other numbers,
// repeat until all numbers are the same
/**
* Does a single operation on the given array.
* Keeps the array sorted.
* @returns True if the array is all the same, false otherwise.
*/
const operate = (arr: number[]): boolean => {
// last element is the largest
// find the first element that is not the largest
const first = arr[0]; // smallest
// if all numbers are the same, return true
// if the array is sorted, it is enough to compare the first and last elements
if(arr[arr.length - 1] === first) return true;
// if the first number is 1, set all numbers to 1
if(first === 1) {
for(let i = 1; i < arr.length; i++) {
arr[i] = 1;
}
return true;
}
// subtract as many multiples of the smallest number from all the rest
let i = 1;
while (i < arr.length) {
if(arr[i] <= first) {
i++;
continue;
}
const mod = arr[i] % first;
if (mod === 0) {
// figure out how many times the first number can be subtracted from the current number
const div = arr[i] / first - 1;
arr[i] = arr[i] - first * div;
} else {
arr[i] = mod;
}
i++;
}
// sort the array
arr.sort((a, b) => a - b);
return false;
}
export function solution(numbers: number[]): number {
numbers.sort((a, b) => a - b);
let done = false;
while (!done) {
done = operate(numbers);
}
// sum the numbers
return numbers.reduce((acc, num) => acc + num, 0);
}