Home > Software design >  Random characters from array without repetition
Random characters from array without repetition

Time:11-14

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.

CodePudding user response:

  1. int size = strlen(array); undefined behaviour as array is not initialized. Additionally wrong type.
  2. Your random index is wrong as you probably want to select from all characters in the characters array, not only 4 first.
  3. Your check for a duplicate is wrong.
  4. Many small issues like wrong types.
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]);
    }
}

https://godbolt.org/z/M9b73KK4r

  • Related