想将char * array改组并使元素随机排序
我读了Shuffle array in C,但我读了
我尝试
const char *words = { "one", "two", "three", "four", "five", "six" };
for (int i=0; i<6; i++)
{
int r = (rand() % (6 - i)) + i;
int temp = words[i];
words[i] = words[r];
words[r] = temp;
}
虽然在迭代数组单词时出错
请解释
答案 0 :(得分:4)
如前所述,您有几个问题
const char *words = { "one", "two", "three", "four", "five", "six" };
无效,因为初始化(以及代码的其余部分)表明 words 是一个数组,因此将其替换为
const char *words[] = { "one", "two", "three", "four", "five", "six" };
int temp = words[i]; words[i] = words[r]; words[r] = temp;
单词是const char *
的数组,因此 temp 不能是 int ,请使用
const char * temp = words[i];
除此之外
sizeof(words)/sizeof(*words)
替换6 size_t
,例如:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
const char *words[] = { "one", "two", "three", "four", "five", "six" };
const size_t nelts = sizeof(words)/sizeof(*words);
srand(time(NULL));
for (size_t i=0; i < nelts; ++i)
{
size_t r = (rand() % (nelts - i)) + i;
const char * temp = words[i];
words[i] = words[r];
words[r] = temp;
}
/* show */
for (size_t i=0; i < nelts; ++i)
puts(words[i]);
return 0;
}
编译和执行:
pi@raspberrypi:/tmp $ gcc -pedantic -Wall -Wextra c.c
pi@raspberrypi:/tmp $ ./a.out
four
one
two
five
three
six
pi@raspberrypi:/tmp $ ./a.out
one
three
two
four
five
six
pi@raspberrypi:/tmp $ ./a.out
six
five
two
four
three
one
pi@raspberrypi:/tmp $ ./a.out
three
one
five
four
six
two
答案 1 :(得分:1)
OPs代码中存在多个错误和缺陷。
const char *words = { "one", "two", "three", "four", "five", "six" };
不确定编译器如何读取(如果没有抱怨的话)。 C字符串数组应为:
const char *words[] = { "one", "two", "three", "four", "five", "six" };
for (int i=0; i<6; i++)
6
是magic number,被认为是不良样式。最好给它起个名字。更好的是:该值可以由编译器确定,这可以提高代码的可维护性:
int n = sizeof words / sizeof *words;
for (int i = 0; i < n; ++i) {
rand()
int r = (rand() % (6 - i)) + i;
rand()
是具有某些限制的伪随机生成器。不应与% n
一起使用。对于某些n
(例如2),这可能会导致出现相当不随机的序列。 cppreference文档。 rand()
的例子给出了一个更好的示例,我将其转换为函数:
int randomRange(int min, int max)
{
for (int range = max - min;;) {
int x = min + rand() / ((RAND_MAX + 1u) / range);
if (x < max) return x;
}
}
被称为
int r = randomRange(i, n);
int temp = words[i];
如果要交换的数组元素的类型为const char*
,则temp
也必须为:
const char *temp = words[i];
words[i] = words[j];
words[j] = temp;
完整的示例代码:
#include <stdio.h>
#include <stdlib.h>
int randomRange(int min, int max)
{
for (int range = max - min;;) {
int x = min + rand() / ((RAND_MAX + 1u) / range);
if (x < max) return x;
}
}
int main(void)
{
/* an array of strings */
const char *words[] = { "one", "two", "three", "four", "five", "six" };
/* let compiler determine size */
int n = sizeof words / sizeof *words;
/* shuffle */
for (int i = 0; i < n; ++i) {
int j = randomRange(i, n);
/* idiomatic swap */
const char *temp = words[i];
words[i] = words[j];
words[j] = temp;
}
/* print result */
const char *sep = "";
for (int i = 0; i < n; ++i) {
printf("%s%s", sep, words[i]);
sep = ", ";
}
/* done */
return 0;
}
输出:
six, three, one, two, four, five