I try to create a program in C that selects random characters from the array and stores them in the second array but without repetition.
Code:
int main() {
srand(time(NULL));
char characters[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I' };
char array[20];
int size = strlen(array);
int random, random_character;
for (int i = 0; i < 4; i++) {
random_character = rand() % 4;
random = characters[random_character];
array[i] = random;
for (int j = 0; j < 4; j++) {
if (array[i] == array[j]) {
array[i] = random;
}
}
}
for (int i = 0; i < 4; i++) {
printf("%c ", array[i]);
}
}
My output still has at least two equal characters.
int size = strlen(array);
undefined behaviour as array is not initialized. Additionally wrong type.characters
array, not only 4 first.int main(void)
{
srand ( time(NULL) );
char characters[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'};
char array[20];
int random, random_character;
size_t j;
for(size_t i = 0; i < 4; )
{
random_character= rand() % sizeof(characters);
random = characters[random_character];
array[i] = random;
for(j = 0; j < i; j++)
{
if(array[j] == random) break;
}
if(j == i)
{
i++;
}
}
for(size_t i = 0; i < 4; i++){
printf("%c ", array[i]);
}
}