HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

Sum of numbers that equal 100

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
equalnumbers100thatsum

Problem

I was asked to find all the numbers that added up to 100 with no duplicates in Ruby. I float between Python, GoLang, and Ruby in a day. I am always concerned if I am doing something in the most optimal way.

require 'pp'
sumdata = [ 95, 5, 95, 5 ]

def find_sum(data)
  result = []
  processed = []
  data.each_with_index do |item, index |
    next if processed.include? index
    data.each_with_index do |other, other_index|
      next if processed.include? other_index # next if already processed
      # add tuple to list
      if item + other == 100
        result << [item, other].sort
        processed << index
        processed << other_index
      end
    end
  end
  result
end

Solution

This is built assuming you want no duplicates in the results, since the goal is a little unclear.
Quickly Finding Combinations

The function you should be using is Array.combination(n), which generates an enumerator that yields all combinations of size n from the array. Once you have that it is a trivial matter to only select the combinations that sum to the target value.

My function here finds all combinations of size 2 to size data.length and then selects only the combinations with the correct sum.

def find_sum(data, target_sum)
  (2..data.length)
    .flat_map { |n| data.combination(n).to_a }
    .select { |arr| arr.inject(:+) == target_sum }
    #.uniq   # can call this to remove duplicates if necessary, depending on what the input data looks like
end

data = (1..9).to_a
pp find_sum(data, 10)
#[[1, 9],
# [2, 8],
# [3, 7],
# [4, 6],
# [1, 2, 7],
# [1, 3, 6],
# [1, 4, 5],
# [2, 3, 5],
# [1, 2, 3, 4]]

Code Snippets

def find_sum(data, target_sum)
  (2..data.length)
    .flat_map { |n| data.combination(n).to_a }
    .select { |arr| arr.inject(:+) == target_sum }
    #.uniq   # can call this to remove duplicates if necessary, depending on what the input data looks like
end

data = (1..9).to_a
pp find_sum(data, 10)
#[[1, 9],
# [2, 8],
# [3, 7],
# [4, 6],
# [1, 2, 7],
# [1, 3, 6],
# [1, 4, 5],
# [2, 3, 5],
# [1, 2, 3, 4]]

Context

StackExchange Code Review Q#128709, answer score: 2

Revisions (0)

No revisions yet.