Skip to content

Instantly share code, notes, and snippets.

@jhennerich
Created July 28, 2022 17:18
Show Gist options
  • Select an option

  • Save jhennerich/ea9da8afe85beac56d1b299a88a1e7d8 to your computer and use it in GitHub Desktop.

Select an option

Save jhennerich/ea9da8afe85beac56d1b299a88a1e7d8 to your computer and use it in GitHub Desktop.

Instructions

Write a method that takes two parameters, payload and target. The playload should be an array or unique integer values(positive, negative, or 0). The target should be an integer(positive, negative, or 0).Your method/function should search through the payload to find any two numbers that add together to equal the target value.

When you find a pair of numbers that add up to your target value, you can stop processing/searching and return an array of those two values. If no values are found return an empty array.

Be careful that you don’t find the same number twice in your payload; for example if your payload contains a 4 and your target is 8, your answer should not indicate that it found 4 twice.

Example output

 find_target([1, 3, 4, 5, 10], 15)
    => [5, 10]
    find_target([-1, -3, 4, 7, -5, 18, 10, -23, 5], 15)
    => [-3, 18]
    find_target([-3, -34, 2, 6, 40, -4], 1)
    => []

Start time 10:29 7/28

Brainstorm / Psudocode

  • ruby methods sum, pop, shift
  • edge cases, payload all 0, is target 0
  • .map itereation to step throught the payload array
  • unitl loop to check on the target value

Stop time 11:17 7/28

Code progress at stop time

def find_target(payload,target)
  return_array = []
  payload.each_with_index do |value, index|
    (payload.size-1).times do | cnt |
      cnt += 1
      arry_pos = index + cnt

    achive_target = value + payload[arry_pos]
      if achive_target == target
        return [value, payload[arry_pos]]
      end
    end
  end
end




#pp find_target([1, 3, 4, 5, 10], 15)
pp find_target([1, 5, 10], 15)
@chavdaamit1
Copy link
Copy Markdown

def find_target(arr,target)
  search_arr = []
  arr.each_with_index do |e,i|
    arr[i+1..arr.length-1].each do |j|
      if (e + j) == target
        search_arr += [e,j]
        return search_arr
      end
    end
  end
end


puts find_target([-1, -3, 4, 7, -5, 18, 10, -23, 5], -24)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment