Click here to Skip to main content
15,889,858 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hello everyone,
How can i search for all matching values in an array of integers and then return their indexes

Thanks in advance,
z3ngew
Posted
Comments
[no name] 2-Sep-13 1:49am    
Are you serious?

1 solution

We don't do your homework - you get the credit, so it's only fair you do the work as well! :laugh:

But this isn't difficult:
Set up a simple loop to check each array entry to see if it matches.
The only complication is that you want to return a variable number of index values - which means in practice that you will need to malloc an array that is big enough for all indexes possible, and have a termination value (a negative index say) or a parameter value to return the indexes count.


"if there is 2 pair of matches, i should return 2d array or not"

Ah! I see what you mean now...
You have an input array:
7,3,2,6,3,5,2,1,9,6
And you want to return:
2, 6
1, 4
3, 9
In which case it's a little more complex to do.
First off there is a problem with returning the value pairs - yes, you could use a 2D array, and that would work well (remember to allocate size of input / 2) as the number of pairs of elements - but what happens if there are three matches in your input?
I would instead be tempted to create a struct which held the value, and an array, or list of index values. I would then return an array of pointers to those...or better a linked list of them. (It depends on your ability level and what you have learned so far which way you will want to go)

To actually do the matching, I'd cheat. I'd set up an array of indexes to elements, and then sort it so that indexes which refer to the same number were side by side:
Input:   7,3,2,6,3,5,2,1,9,6
Indexes: 0,1,2,3,4,5,6,7,8,9

Input:   7,3,2,6,3,5,2,1,9,6
Indexes: 7,2,6,1,4,5,3,9,0,8
The values the indexes refer to are in ascending order, so the indexes for equal values are side by side: 1 & 4, and 3 & 9
Now all you have to do is traverse the indexes array comparing the values they refer to and create output values for those that are the same.

Does that make sense? If not try it on paper with arrows and you should see what I mean.
 
Share this answer
 
v2
Comments
z3ngew 2-Sep-13 6:34am    
thanks you, but what if there is more that one match, any ideas, and is there an alternative to the brute force method
OriginalGriff 2-Sep-13 6:41am    
Read the last paragraph...
z3ngew 2-Sep-13 6:44am    
if there is 2 pair of matches, i should return 2d array or not
OriginalGriff 2-Sep-13 7:12am    
Answer updated
z3ngew 2-Sep-13 7:24am    
Great explanation, thanks for your effort, and the sort trick is smart

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900