Skip to content

Instantly share code, notes, and snippets.

@4skinSkywalker
Created February 23, 2019 19:51
Show Gist options
  • Save 4skinSkywalker/40e5bc27a62049d1d34632f9776f2fc0 to your computer and use it in GitHub Desktop.
Save 4skinSkywalker/40e5bc27a62049d1d34632f9776f2fc0 to your computer and use it in GitHub Desktop.
The third hardest challenge listed in the “easy” section of Coderbyte.
function scaleBalancing(plates, weights) {
weights.sort((a, b) => a - b)
let [a, b] = plates
if (a === b) {
return 'already balanced'
}
let diff = Math.abs(a - b)
if (weights.includes(diff)) {
return '' + diff
}
for (let i = 0; i < weights.length; i++) {
let copy = [...weights]
copy.splice(i, 1)
let solution = copy.indexOf(diff - weights[i])
if (solution > -1) {
return [weights[i], weights[solution + 1]].toString()
}
}
let biggest = Math.max(a, b)
let smallest = Math.min(a, b)
for (let i = 0; i < weights.length; i++) {
let sum = biggest + weights[i]
let copy = [...weights]
copy.splice(i, 1)
let solution = copy.indexOf(sum - smallest)
if (solution > -1) {
return [weights[i], weights[solution + 1]].toString()
}
}
return 'impossible'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment