misshyde misshyde - 16 days ago 6
C Question

Generate random letters in C

here is my code. I am trying generate random alphabet but i see same letters.
example: (YHTGDHFBSHXCHFYFUXZWDYKLXI) How can i fix it? just i need mixed alphabet not same letters. Thank you so much.

#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

void random_string(char * string, unsigned length)
{
/* Seed number for rand() */
srand((unsigned int) time(0));


int i;
for (i = 0; i < length; ++i)
{
string[i] = rand() % 26 + 'A';
}

string[i] = '\0';
}

int main(void)
{
char s[26];
random_string(s, 26);
printf("%s\n", s);
return 0;
}

Answer

The operation you are looking for is called a shuffle or a permutation. It is not sufficient to call a random-letter function 26 times, since, as you see, you can generate duplicates.

Instead, start with the string "ABCDEFGHIJKLMNOPQRSTUVWXYZ" and perform a shuffle operation. If you want to learn by doing such things from scratch, I recommend reading about the Fisher-Yates Shuffle then crafting an implementation on your own.