second solution

This commit is contained in:
2025-02-02 23:52:53 +01:00
parent b768376ff0
commit 58ce2189f7
2 changed files with 36 additions and 35 deletions

View File

@@ -1,20 +1,5 @@
// idea: keep the array sorted
// whenever we execute the subtraction, place the result in the correct position
/**
* Inserts the value in a sorted array to keep it sorted.
* The sort direction is assumed to be ascending.
* @param arr The sorted array
* @param value The value to insert
*/
const sortInsert = (arr: number[], value: number): void => {
let i = 0;
while (i < arr.length && arr[i] < value) {
i++;
}
arr.splice(i, 0, value);
}
// 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.
@@ -24,24 +9,32 @@ const sortInsert = (arr: number[], value: number): void => {
const operate = (arr: number[]): boolean => {
// last element is the largest
// find the first element that is not the largest
let i = arr.length - 1;
while (i >= 0 && arr[i] === arr[arr.length - 1]) {
i--;
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++;
}
if (i < 0) {
// all elements are the same
return true;
}
// subtract
const value = arr[arr.length - 1] - arr[i];
// remove the last element
arr.pop();
// insert the value in the correct position
sortInsert(arr, value);
// sort the array
arr.sort((a, b) => a - b);
return false;
}

View File

@@ -3,6 +3,14 @@ import { assert } from "chai";
import { solution } from "./solution";
describe('Example test', function() {
it('[6,9,12]', () => assert.strictEqual(solution([6,9,21]),9));
describe('Example test', function () {
it('[6,9,12]', () => assert.strictEqual(solution([6, 9, 21]), 9));
it('[1,21,55]', () => assert.strictEqual(solution([1, 21, 55]), 3));
it('[3,13,23,7,83]', () => assert.strictEqual(solution([3, 13, 23, 7, 83]), 5));
it('[4,16,24]', () => assert.strictEqual(solution([4, 16, 24]), 12));
it('[30,12]', () => assert.strictEqual(solution([30, 12]), 12));
it('[60,12,96,48,60,24,72,36,72,72,48]', () => assert.strictEqual(solution([60, 12, 96, 48, 60, 24, 72, 36, 72, 72, 48]), 132));
it('[71,71,71,71,71,71,71,71,71,71,71,71,71]', () => assert.strictEqual(solution([71, 71, 71, 71, 71, 71, 71, 71, 71, 71, 71, 71, 71]), 71 * 13));
it('[11,22]', () => assert.strictEqual(solution([11,22]), 22));
it('[9]', () => assert.strictEqual(solution([9]), 9));
});