I have a vector of numbers between 1 and 100(this is not important) which can take sizes between 3 and 1.000.000 values.
If anyone can help me getting 3 value unique* combinations from that vector.
*Unique
Example: I have in the array the following values: 1[0] 5[1] 7[2] 8[3] 7[4] (the [x] is the index)
In this case 1[0] 5[1] 7[2] and 1[3] 5[1] 7[4] are different, but 1[0] 5[1] 7[2] and 7[2] 1[0] 5[1] are the same(duplicate)
My algorithm is a little slow when i work with a lot of values(example 1.000.000). So what i want is a faster way to do it.
for(unsigned int x = 0;x<vect.size()-2;x++){
for(unsigned int y = x+1;y<vect.size()-1;y++){
for(unsigned int z = y+1;z<vect.size();z++)
{
// do thing with vect[x],vect[y],vect[z]
}
}
}
In fact it is very very important that your values are between 1 and 100! Because with a vector of size 1,000,000 you have a lot of numbers that are equal and you don’t need to inspect all of them! What you can do is the following:
Note: the following code is just an outline! It may lack sufficient error checking and is just here to give you the idea, not for copy paste!
Note2: When I wrote the answer, I assumed the numbers to be in the range [0, 99]. Then I read that they are actually in [1, 100]. Obviously this is not a problem and you can either -1 all the numbers or even better, change all the 100s to 101s.
Then, you do similar to what you did before:
Another thing you can do is spend more time in preparation to have less time generating the pairs. For example:
Then
Let us consider 100 to be a variable, so let’s call it
k, and the actual numbers present in the array asm(which is smaller than or equal tok).With the first method, you have
O(n)preparation andO(m^2*k)operations to search for the value which is quite fast.In the second method, you have
O(nm)preparation andO(m^3)for generation of the values. Given your values fornandm, the preparation takes too long.You could actually merge the two methods to get the best of both worlds, so something like this:
Then:
This method has
O(n)preparation andO(m^3)cost to find the unique triplets.Edit: It turned out that for the OP, the same number in different locations are considered different values. If that is really the case, then I’m sorry, there is no faster solution. The reason is that all the possible combinations themselves are
C(n, m)(That’s a combination) that although you are generating each one of them inO(1), it is still too big for you.