finding two index values that add up to a certain value

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
arrobeusa
Forum Newbie
Posts: 1
Joined: Wed Jan 06, 2010 9:31 pm

finding two index values that add up to a certain value

Post 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?
Griven
Forum Contributor
Posts: 165
Joined: Sat May 09, 2009 8:23 pm

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

Post by Griven »

Sounds like homework to me.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

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

Post 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?
Post Reply