Sum Of Two Integers

July 19, 2011

We have today another exercise in our on-going series of interview questions:

Write a program that takes a list of integers and a target number and determines if any two integers in the list sum to the target number. If so, return the two numbers. If not, return an indication that no such integers exist.

Your task is to write the indicated program. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

"""
Prints the first pair of integers in list_of_integers that sum to target_sum.
A blank line is printed if there is no such pair.
The integers can be taken from the command line or standard input.
"""
import sys
def sumto(target, numbers):
diff = {}
for number in numbers:
if number in diff:
return diff[number], number
else:
diff[target-number] = number
if __name__ == '__main__':
if len(sys.argv) > 1:
if any(arg.startswith('-') for arg in sys.argv[1:]):
print __doc__
exit()
source = [' '.join(sys.argv[1:])]
else:
source = sys.stdin
for line in source:
numbers = map(int, line.split())
result = sumto(numbers[0], numbers[1:])
if result:
sys.stdout.write('{} {}\n'.format(*result))
else:
sys.stdout.write('\n')

Another Ruby solution, took it a bit further so it supports more than just addition.
Turns out Ruby has a builtin solution too. [1,2,3,4,5].combination(2).select { |a,b| a + b == 3 }
Anyway this was a fun exercise.

{-
Write a program that takes a list of integers and a target number and determines if any two integers in the list sum to the target number. If so, return the two numbers.
If not, return an indication that no such integers exist.
-}

/**
* Program that takes a list of integers and a target number and determines if
* any two integers in the list sum to the target number. If so, return the two
* numbers. If not, return an indication that no such integers exist.
*
* @see https://programmingpraxis.com/2011/07/19/sum-of-two-integers/
*/
var App = function() {

/**
* Determines if any two integer in a given list sum to the target number.
* @param list A list of integers.
* @param target The target number.
*/
this.sum = function(list, target) {

[…] try it out with a miniproject, perhaps from Programming Praxis. I went over there and found the Sum of Two Integers problem, which looked interesting. The problem is given a list of integers and a target integer […]

http://codepad.org/xgnHVxd6
my C++ version
it’s got a lot of extra code in it because i wasn’t satisfied with the efficiency of my first attempt
the only functions relating to the program are findPair() and/or SortFindPair().
I’m a beginner programmer. Constructive criticism and questions are wanted.