random use in app
how can an array be created that randomizes results from 3 different values 0,1,2 and then makes 2 combinations of those
for example : i have
int values[3] = {0,1,2}
blah = values[arc4random() %3];
i tried using this from the arc4random help post on this site however when i do the above the app crashes. Im a begginer to arc4random and cant figure a solution to this since there isnt enough documents online to help me. Furthermore how can i choos开发者_运维知识库e 2 items from blah to be displayed?
Well, for one you're missing a ;
int values[3] = {0,1,2}; //<-- here
int blah = values[arc4random() %3];
NSLog(@"Value: %d",blah);
Second, the above compiles just fine.
Third, I think you want to do this, but as @Shaggy Frog mentioned, your question is kindof unclear:
int combo[3];
for (int i = 0; i < 3; i++) {
combo[i] = values[arc4random() %3];
}
Which should give you a random "combination" of the values in values[]
. Combination has a specific definition, as well as permutation.
I believe what you want is a set of 3 numbers chosen at random from values[]
. If you do need permutations, get comfy with Dijkstra.
[Edit]
To get what you specified in the comment, you can do this:
int values[3] = {0,1,2};
int sum;
switch (arc4random()%3) {
case 0:
sum = values[1] + values[2];
break;
case 1:
sum = values[0] + values[2];
break;
case 2:
sum = values[1] + values[0];
break;
}
[Edit]
Or, you can do this:
int values[3] = {0,1,2};
int blah[2];
int index;
switch (arc4random()%3) {
case 0:
index = arc4random()%2;
blah[index] = values[1];
blah[1-index] = values[2];
break;
case 1:
index = arc4random()%2;
blah[index] = values[0];
blah[1-index] = values[2];
break;
case 2:
index = arc4random()%2;
blah[index] = values[1];
blah[1-index] = values[0];
break;
}
a card drawing algorithm may also suit your needs.
精彩评论