fourth solution

This commit is contained in:
2025-02-03 00:21:54 +01:00
parent ca92878a0a
commit 2ea2410fb3

View File

@@ -1,5 +1,19 @@
// idea: find lowest number, subtract it from all other numbers,
// repeat until all numbers are the same
// idea: do not ever sort
// simply keep looping from left to right and back to left
// whenever a smaller number is found,
// subtract as many multiples of that number from the rest of the array
const subtractMultiples = (a: number, b: number): number => {
// subtract a from b as many times as possible
const mod = b % a;
if (mod === 0) {
// figure out how many times a can be subtracted from b
const div = b / a - 1;
return b - a * div;
} else {
return mod;
}
}
/**
* Does a single operation on the given array.
@@ -7,46 +21,36 @@
* @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;
let step = 1;
let i = 0;
let done = false;
let hasChangedDuringLoop = false;
while (!done) {
if (i + step >= arr.length || i + step < 0) {
// reverse direction
step = -step;
if (!hasChangedDuringLoop) {
done = true;
}
hasChangedDuringLoop = false;
}
// 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;
const first = arr[i];
const next = arr[i + step];
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;
if (first > next) {
arr[i] = subtractMultiples(next, first);
hasChangedDuringLoop = true;
} else if (first < next) {
arr[i + step] = subtractMultiples(first, next);
hasChangedDuringLoop = true;
}
i++;
i += step;
}
// sort the array
arr.sort((a, b) => a - b);
return false;
return true;
}
export function solution(numbers: number[]): number {