Page 1 of 1

finding two index values that add up to a certain value

Posted: Wed Jan 06, 2010 9:42 pm
by arrobeusa
I need a function that takes an array of integers as an argument and returns an array of the first pair of indexes that add up to 10.

So, given an array:

Code: Select all

 
array(1,3,5,7,9)
 
3 and 7 are the first pair of values that add up to 10 so the function would return

Code: Select all

 
array(1,3)
 
Since 3 and 7 are at index 1 and 3 respectively.

Anybody have any ideas?

Re: finding two index values that add up to a certain value

Posted: Wed Jan 06, 2010 9:47 pm
by Griven
Sounds like homework to me.

Re: finding two index values that add up to a certain value

Posted: Wed Jan 06, 2010 10:50 pm
by requinix
If you're fishing for ideas then

If the array is sorted it's really easy. Pick two adjacent indexes - call them A and B: if array[A]+array is <10 what would you do? If array[A]+array is >10 what would you do?