Skip to content

Instantly share code, notes, and snippets.

@hayleyxyz
Created January 21, 2020 15:23
Show Gist options
  • Save hayleyxyz/46e7dd32b5a7819f2ce8d177d298ea48 to your computer and use it in GitHub Desktop.
Save hayleyxyz/46e7dd32b5a7819f2ce8d177d298ea48 to your computer and use it in GitHub Desktop.
/* You have a set of scales which are unbalanced and the aim is to use a maximum of two of the remaining weights to see if you can balance the scales. If you do need to use 2 weights they can be placed on the same scale.
Write a function that can accept 3 arguments. The first argument will be an integer greater than 0 that represents the current weight of the left scale, the second argument will be an integer greater than 0 that represents the weight of the right scale and the last argument will be an array of positive integers that represent the weights you currently have remaining to use.
For example (5, 9, [3,5,8,12]). 5 represents the left scale’s current weight. 9 represents the right scale’s current weight and the array represents the weights you have at your disposal.
If you can balance the scales then the function should return an array of the number(s) required to make the scales balance. Otherwise it can return nil/null.
Examples
input (6, 8, [3, 4, 5, 8])
output [3, 5]
input (1,2, [4, 7, 9, 1])
output [1]
input (5, 9, [ 1, 3, 6, 7])
output [1, 3] #=> can both be placed on the left scale to make it weigh 9
input (3, 6, [2, 6, 7, 19])
output nil
Time taken ~20 mins
*/
function scale(scales, weights) {
for(var x = 0; x < weights.length; x++) {
for(var y = 0; y < weights.length; y++) {
if(scales[0] + weights[x] == scales[1] + weights[y]) {
return [ [weights[x]], [weights[y]] ];
}
if(scales[0] + weights[y] == scales[1] + weights[x]) {
return [ [weights[y]], [weights[x]] ];
}
if(scales[0] + weights[x] + weights[y] == scales[1]) {
return [ [weights[y], weights[x]], [] ];
}
if(scales[1] + weights[x] + weights[y] == scales[0]) {
return [ [], [weights[y], weights[x]] ];
}
if(scales[0] + weights[x] == scales[1]) {
return [ [weights[x]], [] ];
}
if(scales[0] + weights[y] == scales[1]) {
return [ [weights[y]], [] ];
}
if(scales[1] + weights[x] == scales[1]) {
return [ [], [weights[x]] ];
}
if(scales[1] + weights[y] == scales[1]) {
return [ [], [weights[y]] ];
}
}
}
return null;
}
console.log(scale([6, 8], [3, 4, 5, 8]));
console.log(scale([1, 2], [4, 7, 9, 1]));
console.log(scale([5, 9], [1, 3, 6, 7]));
console.log(scale([3, 6], [2, 6, 7, 19]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment