In: Computer Science
Is there a shortcut or simpler way to get the same output in C ?
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define OFFSET 1
#define RANGE 53
int RandomInteger(int, int);
int PrintInstructions();
int main()
{
//six integer variables
int a, b, c, d, e, f;
//one integer for num of sets
int numSets;
srand(time(NULL));
while (1)
{
int i;
numSets = PrintInstructions();
if (numSets == 0)
{
printf("* You have choosen to exit the application.\n");
break;
}
for (i = 1; i <= numSets; i++)
{
a = RandomInteger(RANGE, OFFSET);
do
{
b = RandomInteger(RANGE, OFFSET);
} while (b == a);
do
{
c = RandomInteger(RANGE, OFFSET);
} while (c == a || c == b);
do
{
d = RandomInteger(RANGE, OFFSET);
} while (d == a || d == b || d == c);
do
{
e = RandomInteger(RANGE, OFFSET);
} while (e == a || e == b || e == c || e == d);
do
{
f = RandomInteger(RANGE, OFFSET);
} while (f == a || f == b || f == c || f == d || f == e);
printf("* Set # %d of six numbers is: %d %d %d %d %d %d\n", i, a, b, c, d, e, f);
}
}
return 0;
}
int RandomInteger(int range, int offset)
{
int randomNum = rand() % RANGE + OFFSET;
return randomNum;
}
int PrintInstructions()
{
int numSets = 0;
printf("*************************************************************************\n");
printf(" Enter in the number of randomly generated sets of numbers you want or \n");
printf(" enter in a 'q' or 'Q' to quit. \n");
printf("*************************************************************************\n");
printf("* Your Input: ");
scanf("%d", &numSets);
return numSets;
}
Modified Program :
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define OFFSET 1
#define RANGE 53
int RandomInteger();
int PrintInstructions();
int main()
{
//six integer variables
int a, b, c, d, e, f;
//one integer for num of sets
int numSets;
srand(time(NULL));
while (1){
int i;
numSets = PrintInstructions();
if (numSets == 0){
printf("* You have choosen to exit the application.\n");
break;
}
for (i = 1; i <= numSets; i++){
a = RandomInteger();
do
{
b = RandomInteger();
c = RandomInteger();
d = RandomInteger();
e = RandomInteger();
f = RandomInteger();
}while(b==a || c == a || c == b || d == a || d == b || d == c || e == a || e == b || e == c || e == d || f == a || f == b || f == c || f == d || f == e);
printf("* Set # %d of six numbers is: %d %d %d %d %d %d\n", i, a, b, c, d, e, f);
}
}
return 0;
}
int RandomInteger(){
int randomNum = rand() % RANGE + OFFSET;
return randomNum;
}
int PrintInstructions(){
int numSets = 0;
printf("*************************************************************************\n");
printf(" Enter in the number of randomly generated sets of numbers you want or \n");
printf(" enter in a 'q' or 'Q' to quit. \n");
printf("*************************************************************************\n");
printf("* Your Input: ");
scanf("%d", &numSets);
return numSets;
}
Output :
Explanation :