Created
September 5, 2024 16:47
-
-
Save jjhiggz/64c8fb44bb9e05f3e35c2914f946b02b to your computer and use it in GitHub Desktop.
closest three sum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function reduce<T, U>( | |
arr: T[], | |
reducer: (acc: U, currentValue: T, index: number, array: T[]) => U, | |
initialValue: U, | |
index: number = 0 | |
): U { | |
// Base case: if the index is out of bounds, return the accumulated value | |
if (index >= arr.length) { | |
return initialValue; | |
} | |
// Recursive case: apply the reducer and recurse with updated accumulator | |
const newAccumulator = reducer(initialValue, arr[index], index, arr); | |
return reduce(arr, reducer, newAccumulator, index + 1); | |
} | |
const closest = (arr: number[], target: number) => { | |
return reduce(arr, (acc, _el, i) => { | |
return reduce(arr, (acc, _el, j) => { | |
return reduce(arr, (acc, _el, k) => { | |
if(i === j) return acc | |
if(j === k) return acc | |
if(k === i) return acc | |
const newSum = arr[i] + arr[j] + arr[k] | |
if(Math.abs(target - newSum) < Math.abs(target - acc)){ | |
return newSum | |
} else { | |
return acc | |
} | |
}, acc) | |
}, acc) | |
}, Infinity) | |
} | |
const problems = [ | |
[closest([-1, 2, 1, -4], 1), 2], | |
[closest([0, 0, 0], 1), 0], | |
[closest([1, 2, 3, 4], 6), 6], | |
[closest([-1, 2, 1, -4, 5], 10), 6], | |
] | |
for(let problem of problems){ | |
const result = problem[0] | |
const expected = problem[0] | |
if(result !== expected) console.error(expected) | |
console.log("yay") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment