1

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.

chqrlie
  • 131,814
  • 10
  • 121
  • 189
david
  • 65
  • 1
  • 6
  • Where is `rows` defined? – sj95126 Nov 12 '21 at 20:51
  • 1
    1. Copy the array as-is to your target that will hold the random sequence. 2. rando-shuffle the target using any proper shuffle algorithm you want (Fisher-Yates for example). 3. Done; the target will now contain the sequence without duplicates (assuming there were none in the source array to begin with) in random order. – WhozCraig Nov 12 '21 at 20:53
  • sorry rows is number 4.. I forgot about it – david Nov 12 '21 at 20:56
  • Select 4 random numbers as in https://stackoverflow.com/questions/69888283/random-4-digit-number-with-non-repeating-digits-in-c Then use them as indices to pick the characters. – Eugene Sh. Nov 12 '21 at 21:01
  • 2
    You're calling `strlen()` on an uninitialized char array, which is bad news and the dreaded undefined behavior. At least you're not then trying to use that `size` variable. – Shawn Nov 12 '21 at 21:27

1 Answers1

1
  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

0___________
  • 60,014
  • 4
  • 34
  • 74