【发布时间】:2019-11-01 19:09:14
【问题描述】:
我正在做一个伪随机数生成器,它创建 100 个从 1 到 56 范围内的 6 个数字的组合,没有重复,然后将它们保存在一个文本文件中。像这样:
33 28 46 7 30 57
15 29 43 41 16 21
11 43 7 18 31 25
36 32 19 42 47 33
46 13 14 1 28 25
33 14 55 43 29 13
30 14 12 45 46 32
56 31 54 32 20 21
10 52 40 57 31 14
28 44 15 47 57 45
...
这是我的代码,但我觉得有点太大了,特别是检查数字不重复的部分
// Including C Standard Libraries
#include <stdint.h>
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
// Initialing Random Generation C Library
srand(time(NULL));
// Variables for PRNG Loop
uint16_t i;
uint8_t j;
uint8_t x[6] = {0,0,0,0,0,0};
// Opening File to save Results
FILE *fp;
fp = fopen("combinations.txt", "w+");
// PRNF Loop
for(i = 0; i<100; i++) // Numbers of Combinations
{
for(j = 0; j<6; j++) // Number of Elements of the Combinations
{
x[j] = rand() % 57 + 1; // Generating Random Number
// Avoiding Repetition of Numbers
if ( j==1)
{
while(x[1] == x[0])
{
x[1] = rand() % 57 + 1;
}
}
if ( j==2)
{
while(x[2] == x[0] || x[2] == x[1])
{
x[2] = rand() % 57 + 1;
}
}
if ( j==3)
{
while(x[3] == x[0] || x[3] == x[1] || x[3] == x[2] )
{
x[3] = rand() % 57 + 1;
}
}
if ( j==4)
{
while(x[4] == x[0] || x[4] == x[1] || x[4] == x[2] || x[4] == x[3] )
{
x[4] = rand() % 57 + 1;
}
}
if ( j==5)
{
while(x[5] == x[0] || x[5] == x[1] || x[5] == x[2] || x[5] == x[3] || x[5] == x[4] )
{
x[5] = rand() % 57 + 1;
}
}
fprintf(fp, "%d", x[j]); // Saving Random Number in File
fprintf(fp, " ");
}
fprintf(fp, "\n"); // Saving Newline
for (int i = 0; i < 6; ++i)
{
x[i] = 0;
}
}
fclose(fp);
}
有没有办法简化代码?
【问题讨论】:
-
不用生成和检查重复,可以shuffle数组,看geeksforgeeks.org/…
-
rand() % 57 + 1生成一个从 1 到 57 的随机数。请注意,1 和 57 都出现在您的示例输出中。 -
57 也出现了?我希望 1 出现但 57 不出现 .. 所以它必须是 56 + 1 ?
-
我建议这个问题太开放了。也许是“减少长度”或“简化”而不是“改进”。代码当然可以改进 - 以你目前不关心的方式,只是你真正想要实现的噪音和意见。
-
另见stackoverflow.com/questions/10984974/…关于在给定范围内生成随机数的方法
标签: c file random combinations