I am doing a Pseudo Random Number Generator that creates 100 combinations with no repetition of 5 numbers from 1 to 56 and then it saves them on a text file. Like this:
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
...
This is my code, but I feel that it is a little bit too big, specially the part when is checking no repetitions of the numbers
// 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);
}
Is there a way to improve the code?
Aucun commentaire:
Enregistrer un commentaire