Files
typescript-katas/5kyu/smallest-possible-sum/solution.ts
2025-02-02 23:52:53 +01:00

51 lines
1.3 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
// subtract as many multiples of the smallest number from all the rest
let i = 1;
// 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;
while (i < arr.length) {
const div = arr[i] / first;
let flooredDiv = Math.floor(arr[i] / first);
if(flooredDiv === div && flooredDiv > 0) {
flooredDiv--;
}
const newValue = arr[i] - first * flooredDiv;
if (newValue !== 0) {
arr[i] = newValue;
}
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);
}