这是一个工作代码,它从用户那里输入一个低数字和高数字,生成一个数组,按顺序打印数组,然后使用 Fisher-Yates 启发的带有 rand() 的随机播放进行随机播放,并打印随机播放的数组。它应该适用于几乎任何范围的数字,并且可以用于打乱字符以及进行一些小的修改。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int low, high;
printf("Choose a range of numbers and first enter the lowest number in the range: ");
scanf("%d", &low);
printf("Please enter the highest number in the range: ");
scanf("%d", &high);
int arraylength = high - low + 1;
int numarray[arraylength];
printf("Here is your range of numbers in numerical order:\n");
/* Create array from low and high numbers provided. */
int i;
int j = low;
for (i = 0; i < arraylength; i++)
{
numarray[i] = j + i;
printf("%d\t", numarray[i]);
}
/* Shuffle array. */
srand(time (NULL));
int temp;
int randindex;
for (i = 0; i < arraylength; i++)
{
temp = numarray[i];
randindex = rand() % arraylength;
if (numarray[i] == numarray[randindex])
{
i = i - 1;
}
else
{
numarray[i] = numarray[randindex];
numarray[randindex] = temp;
}
}
printf("\nHere is your range of numbers in random order:\n");
/* Print shuffled array. */
for (i = 0; i < arraylength; i++)
{
printf("%d\t", numarray[i]);
}
getchar();
return 0;
}