24-02-2018 Balancing the Scales


#1

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

Again we encourage you to write tests for the problem for practice and share your solutions here.


#2

Should the output have order? Like “The first is for the left, the second is for the right”.
Are the array sorted increasing? Are the array always contains four weights?
Is the left always smaller than the right?


#4

My solution in ruby 2.4.1:

my_arguments1 = [6, 8, [3, 4, 5, 8]]
my_arguments2 = [1, 2, [4, 7, 9, 1]]
my_arguments3 = [5, 9, [1, 3, 6, 7]]
my_arguments4 = [3, 6, [2, 6, 7, 19]]

def output(left, right, weights)
  
  difference = (left - right).abs
  result = weights.select do |weight|
    weight == difference
  end
  
  unless result.empty?
    return result
  end
  
  weights.combination(2) do |item|
    
    if item.sum == difference
      return item
    end
    
    if (item[0] - item[1]).abs == difference
      return item
    end
  end
  
  return nil
end

output(*my_arguments1)
output(*my_arguments2)
output(*my_arguments3)
output(*my_arguments4)

I love ruby!


#5

Great solution. Thank you for submitting :smile:


#6

A solution in Ruby


#7

#8

not particularly elegant… but it works :sunglasses:

JS solution on repl.it