This code takes a selection of numbers between 1 to 9 which could be 1,2,3,4,5,6,7,8,9
or 1,2,4
or 4,5,8,9
, etc.
Looks for every possible combination and compares them to a dice roll of two dice
e.g. If the dice roll is 7 then can it be found in a list which contains
1,2,3,4,5,6,7,8,9
- (Yes, 7 and 5+2 and 3+4 etc)
OR the list could contain
1,3,4,8
- (Yes 3+4 only)
OR
1,4,8,9
- (No)
Note:
remainder is the dice roll
Binarypositions works out the different possibilities and returns a list of all the combinations available for checking
void gameovercheck(){
List <int> selection = new List <int> ();
bool found = false;
//Calculate number of possible combinations
int combination = (int)Mathf.Pow (2, blocklist.Count);
//Loop to step through each possible combination
for (int x = 0; x < combination; x++) {
selection = ReturnBinary.Binarypositions (x, 8);
//string output = "";
int sum = 0;
for (int z = 0; z < selection.Count; z++) {
sum += blocklist [selection [z]];
}
if (sum == remainder)
found = true;
}
if (!found) {
gamerunning = false;
}
}
}
to find out all the possible combinations I work out the binary positions using the following function
public static List<int> Binarypositions(int number,int bits){
List <int> newanswer = new List <int>();
int count = 0;
for (int y = 0; y < bits; y++) {
int answer = number >> y & 0x1;
if (answer==1) {
newanswer.Add (count);
}
count++;
}
//Output
return (newanswer);
}
I have to run this everytime I want to check if it can be found, so how can I optimise this for performance?
gamerunning
andremainder
? your code won't run by itself, you haven't given us enough code to review \$\endgroup\$