-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathlottery_number_generator.cpp
More file actions
74 lines (62 loc) · 2.59 KB
/
Copy pathlottery_number_generator.cpp
File metadata and controls
74 lines (62 loc) · 2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*******************************************************************************
*
* Program: Lottery Number Generator
*
* Description: Program to generate random lottery numbers using C++.
*
* YouTube Lesson: https://www.youtube.com/watch?v=VFqixcyaJEA
*
* Author: Kevin Browne @ https://portfoliocourses.com
*
*******************************************************************************/
#include <iostream>
#include <cstdlib>
#include <ctime>
// We generate TOTAL_NUMBERS amount of lottery numbers in the range 1-RANGE_MAX.
// The numbers generated are integers, and each number is unique as lottery
// numbers are "drawn" from a set of numbers.
#define TOTAL_NUMBERS 6
#define RANGE_MAX 59
using namespace std;
int main()
{
// Seed the random number generator with the current time to help ensure we
// may get a different sequence of random numbers generated each time the
// program runs.
srand((unsigned int) time(NULL));
// Stores each random number generated
int number = 0;
// Stores the unique lottery numbers generated
int numbers[TOTAL_NUMBERS];
// Helps to ensure each lottery number is unique
bool unique = false;
// Outer loop generates TOTAL_NUMBERS amount of lottery numbers
for (int i = 0; i < TOTAL_NUMBERS; i++)
{
// Inner loop ensures a unique lottery number is generated
do
{
// Generates a random integer in the range of 1-RANGE_MAX. rand() will
// return a random integer in the range of 0 ... RAND_MAX (a large
// positive integer), applying % RANGE_MAX will result in an integer in
// the range of 0 ... RANGE_MAX-1 because those are the possible
// remainders when dividing by RANGE_MAX and the modulus operator %
// gives us the remainder of a division operation. The +1 will shift
// this number into a value in the range 1-RANGE_MAX.
number = (rand() % RANGE_MAX) + 1;
// When unique is set to true it will indicate the random number is
// unique. Start off with the assumption the random number is
// unique, loop through all previous 'i' amount of lottery numbers
// so far and check for the number... if it's found, set unique to
// false as the number is not unique.
unique = true;
for (int j = 0; j < i; j++)
if (numbers[j] == number) unique = false;
// if the number is not unqiue, keep running the loop to try again
} while (!unique);
// Once we have a unique number, store it into the array and output it
numbers[i] = number;
cout << "number " << (i+1) << ": " << number << endl;
}
return 0;
}