Get every possible combination of elements in a list
Hey Community. So here is what I wanna do.
I have a List of ints and I want to compare every possible combination of the elements to an int.
For example. my List contains 2 ints, x and y. I also have an int z.
What I wanna do is check if:
z = x
or
z = y
or
z = x + y
or
z = y + x.
And if one of these returns true i wanna do some stuff.
Of cours my list does not always contain 2 elements but ranges from 1 to 6 elements... so yeah...
Little note: If my Lists contains 3 Elements, for example a, b and c I also wanna check the possibility:
z = a + b ...without c...
Any ideas?
In what context is this required, just incase there is a better approach?
Basically my situation is: Im making a card game On my field are 1 - 6 cards witch each have a value from 1 - 10 In my hand is one card. also with a value from 1 - 10 Now what i wanna do is check if there is any combinations of the cards on the field in witch the sum of their values is equal to the value of the card in my hand and the do stuff with those cards.
Answer by toddisarockstar · Mar 12, 2016 at 07:32 PM
you need a loop inside a loop ... something like this
var i:int;
var i2:int;
i=yourlist.length;
while(i>0){i--;
i2=yourlist.length;
while(i2>0){i2--;
// compare your suff here however ya like!!!!
if(yourlist[i].z==yourlist[i2].x+yourlist[i2].y){
print("one of your z's adds to x and y");}
if(yourlist[i].x==yourlist[i2].y){
print("one of your x's equals one of your y's" );}
} }
thanks for the answer... i dont think this is what i need though. Did you read the comment I wrote above? There I write more detailed what I need. :)
i didnt see the comment when i seen the first answer.
var cardinhand:int;
cardinhand=Random.Range(1,11);
var field:int[];
field=new int[Random.Range(1,7)];
for(var shuffle:int in field){shuffle=Random.Range(1,11);}
i=field.Length;
while(i>0){i--;
i2=field.Length;
while(i2>0){i2--;
if(i!=i2){if(cardinhand==field[i]+field[i2]){
print("two cards on the table = card in hand");}}}}
if you wanted to check to see if three cards add up you would add a third loop and so on..
var i:int;
var i2:int;
var i3:int;
var cardinhand:int;
cardinhand=Random.Range(1,11);
var field:int[];
field=new int[Random.Range(1,7)];
for(var shuffle:int in field){shuffle=Random.Range(1,11);}i=field.Length;
while(i>0){i--;
i2=field.Length;
while(i2>0){i2--;
if(i!=i2){if(cardinhand==field[i]+field[i2]){
print("card number "+i+"+ cardnumber"+i2+"= card in hand");}
i3=field.Length;
while(i3>0){i3--;
if(i!=i3){if(i2!=i3){
if(field[i]+field[i2]+field[i3]==cardinhand){print("card numbers "+i+","+i2+"and "+i3+" = card in hand");}}
}}}
}}
Thanks a lot... I'll dig into that. Looks promising... Ehm... im sure I will manage to translate it anyway but would you $$anonymous$$d writing it in C# if you are familiar with it? :D
Your answer
