C语言 如何每次打印不同排列的字符串?

new9mtju  于 2022-12-02  发布在  其他
关注(0)|答案(1)|浏览(128)

我想知道我怎么能每次都以不同的顺序打印出字符串变量?
我想过用rand()做一个开关盒,但我认为它在更大的数量下效率不是很高。
`

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

`

3pvhb19x

3pvhb19x1#

正如在评论中指出的那样,shuffling an array的伸缩性很好,而且更容易编写和维护。
粗略举个例子:

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

按回车键前进:

Portruding
Gaelet
Malfeasance
Star
Jostled
Morpheus

Star
Morpheus
Portruding
Gaelet
Jostled
Malfeasance

Jostled
Gaelet
Morpheus
Portruding
Malfeasance
Star

相关问题