Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to print different arrangement of strings every time?

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.

`

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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;
    }

`

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading