Alex Alex - 22 days ago 11
C Question

Inputing string and printing them in random order

I'm having a little trouble getting my words to print out in random order. The 8 words that I insert will need to be printed out in random order. Right now I'm only able to generate a few of them in random order because it overwrites the previous space if the same number is generated twice. How can I eliminate this issue?

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <ctype.h>
#define MAX 50

int readLine(char string[]);

int main(void)
{
int i;
char str[8][MAX], temp[8][MAX];
srand((unsigned)time(NULL));
int r_num;

printf("Enter 8 words:\n");

for(i=0; i<8; ++i)
{
readLine(str[i]);
}


for (int i = 0; i < 8; i++)
{
r_num = rand()%8+1;
strcpy(temp[r_num], str[i]);
}

printf("\nRandom order of words: \n");
for(i=0; i<8; ++i)
{
printf("%s\n", temp[i]);
}
printf("\n");

return 0;
}

int readLine(char string[])
{
int ch;
int i=0;
while (isspace(ch = getchar()))
;
while (ch != '\n' && ch != EOF)
{
if (i < MAX)
{
string[i++] = ch;
ch = getchar();
}
}
string[i] = '\0';
return i;
}

Answer

One of ways to shuffle data is picking from what is not selected yet.

int main(void)
{
    int i;
    char str[8][MAX];
    int order[8]; /* order list */
    srand((unsigned)time(NULL));
    int r_num;

    printf("Enter 8 words:\n");

    for(i=0; i<8; ++i)
    {
        readLine(str[i]);
    }

    /* initialize order list */
    for (i = 0; i < 8; i++)
    {
        order[i] = i;
    }
    for (i = 7; i > 0; i--) /* select from back to front */
    {
        int pos = rand() % (i + 1); /* pick one position randomly */
        /* pick selected element by swapping */
        int temp = order[pos];
        order[pos] = order[i];
        order[i] = temp;
    }

    printf("\nRandom order of words: \n");
    for(i=0; i<8; ++i)
    {
        printf("%s\n", str[order[i]]); /* print strings in the shuffled order */
    }
    printf("\n");

    return 0;
}