I think I almost understood what you want to do, but I think you cannot do it the way you have coded (see my comment).
The problem is: if you take a random number (1 or 2) 16 times, nothing guarantees that you will have the same number of ones and twos. Even by setting a flag in the
c
member variable as you did, that completely messes up with the algorithm. I think having an array of 16 names that you would shuffle would be much cleaner.
You could do this way:
#include <time.h>
struct f
{
const char* name;
};
void shuffle(f menu[], size_t count);
const int SIZE = 16;
int main() {
int i;
struct f menu[SIZE];
menu[ 0].name = "mee1";
menu[ 1].name = "mee2";
menu[ 2].name = "mee3";
menu[ 3].name = "mee4";
menu[ 4].name = "mee5";
menu[ 5].name = "mee6";
menu[ 6].name = "mee7";
menu[ 7].name = "mee8";
menu[ 8].name = "mee9";
menu[ 9].name = "me10";
menu[10].name = "me11";
menu[11].name = "me12";
menu[12].name = "me13";
menu[13].name = "me14";
menu[14].name = "me15";
menu[15].name = "me16";
shuffle(menu, SIZE);
}
void shuffle(f menu[], size_t count) {
size_t i, j;
f t;
srand((unsigned int)time(NULL));
if (count > 1) {
for (i = 0; i < count - 1; ++i) {
j = i + rand() / (RAND_MAX / (count - i) + 1);
t = menu[j];
menu[j] = menu[i];
menu[i] = t;
}
}
}
I changed your original algorithm a lot, but that is because I do not think you could achieve this the way you had done it. I kept the
f
structure, but got rid of
str1
and
str2
as they only introduced some unnecessary complexity.
I am aware this is a big change, and not knowing the exact requirement this may not be a valid solution. If it is not valid, my apologies. I don't think I would be able to only slightly modify your solution and achieve the same result.
As I said, I do not have a C compiler. I tested it on a VS 2017 C++ project and I actually get expected shuffling of names.