Home > Blockchain >  How to print different arrangement of strings every time?
How to print different arrangement of strings every time?

Time:11-30

I was wondering how can I print out string variables in different order every time?

I thought about making a switch case with rand() but I think it is not that efficient with larger quantities.

`

    char *mal = "Malfeasance", *por = "Portruding", *jos = "Jostled",
         *gae = "Gaelet", *mor = "Morpheus", *sta = "Star";
    switch (rand() % 3)
    {
    case 0:
        printf("1. %s\n2. %s\n3. %s\n4. %s\n5. %s\nInput: ", mal, por, jos, gae, mor);
        which_case=1;
        break;
    case 1:
        printf("1. %s\n2. %s\n3. %s\n4. %s\n5. %s\nInput: ", sta, por, mor, jos, gae);
        which_case=2;
        break;
    case 2:
        printf("1. %s\n2. %s\n3. %s\n4. %s\n5. %s\nInput: ", gae, por, mor, jos, gae);
        which_case=3;
        break;
    }

`

CodePudding user response:

As pointed out in the comments, repeatedly shuffling an array scales well, and is easier to write and maintain.

A cursory example:

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

void shuffle(const char **data, size_t length)
{
    while (length > 1) {
        size_t n = rand() % (length--);
        const char *t = data[n];

        data[n] = data[length];
        data[length] = t;
    }
}

int main(void)
{
    const char *names[] = {
        "Malfeasance", "Portruding", "Jostled",
        "Gaelet", "Morpheus", "Star"
    };

    size_t len = sizeof names / sizeof *names;

    srand((unsigned) time(NULL));

    while (1) {
        shuffle(names, len);

        for (size_t i = 0; i < len; i  )
            printf("%s\n", names[i]);

        if (EOF == getchar())
            break;
    }
}

Pressing the return key to advance:

Portruding
Gaelet
Malfeasance
Star
Jostled
Morpheus

Star
Morpheus
Portruding
Gaelet
Jostled
Malfeasance

Jostled
Gaelet
Morpheus
Portruding
Malfeasance
Star
  • Related