Let's say I have an array of arbitrary values.
arbitrary_type array[50];
I want to select a random element in this array, but I want to select this element between pre-determined elements in the array. I presume this is a common problem many may have had to deal with before. Here how I deal with this,
-
I create a new list of the same size.
int new_list[50];
-
Then I enumerate the elements I want to chose from,
[a, b, c, ............ m, n, ............ z] 0 1 2 3
I store the count of the elements which the new element will be selected from, which is 4
in the example above. Let's say this is int random_count
.
-
I fill the first
4
elements of thenew_list
. (This can also be done with element indexes).[b, c, m, z]
-
Then I use the regular random integer algorithm to achieve what I want.
result = new_list[rand() % random_count]
The fact that I used an extra array feels like this is a bad solution. Another solution might be using switch case and use the random number like:
case(1): return c;
But this would not be feasible because the elements that are selected may be changed. My question is, what programming method is being used in such a problem ?
Aucun commentaire:
Enregistrer un commentaire