#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/*
This program generates random Powerball lottery numbers:
- 5 distinct numbers from 1..69
- 1 Powerball number from 1..26
It uses:
- srand(time(NULL)) to seed the RNG
- rand() for random number generation
- Fisher–Yates shuffle for efficient, uniform shuffling
*/
/*
shuffle(array, n):
Implements the Fisher–Yates shuffle.
This algorithm:
- runs in O(n)
- produces a uniform random permutation
- is the standard way to shuffle arrays correctly
*/
void shuffle(int *array, int n) {
for (int i = n - 1; i > 0; i--) {
int j = rand() % (i + 1); // random index 0..i
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
/*
pickDistinctNumbers(count, max, result):
Fills `result` with `count` distinct numbers from 1..max.
Algorithm:
- Build an array [1, 2, ..., max]
- Shuffle it using Fisher–Yates
- Copy the first `count` numbers into result[]
*/
void pickDistinctNumbers(int count, int max, int *result) {
int *numbers = malloc(max * sizeof(int));
if (!numbers) {
fprintf(stderr, "Memory allocation failed\n");
exit(1);
}
for (int i = 0; i < max; i++) {
numbers[i] = i + 1;
}
shuffle(numbers, max);
for (int i = 0; i < count; i++) {
result[i] = numbers[i];
}
free(numbers);
}
/*
pickPowerball(max):
Returns a single random number in the range 1..max.
*/
int pickPowerball(int max) {
return (rand() % max) + 1;
}
int main(void) {
srand((unsigned)time(NULL)); // seed RNG
const int MAIN_COUNT = 5;
const int MAIN_MAX = 69;
const int POWER_MAX = 26;
int mainNumbers[MAIN_COUNT];
// Generate main numbers (distinct)
pickDistinctNumbers(MAIN_COUNT, MAIN_MAX, mainNumbers);
// Sort for nicer output
for (int i = 0; i < MAIN_COUNT - 1; i++) {
for (int j = i + 1; j < MAIN_COUNT; j++) {
if (mainNumbers[j] < mainNumbers[i]) {
int temp = mainNumbers[i];
mainNumbers[i] = mainNumbers[j];
mainNumbers[j] = temp;
}
}
}
// Generate Powerball number
int powerball = pickPowerball(POWER_MAX);
// Output results
printf("Powerball numbers (5 out of 69): ");
for (int i = 0; i < MAIN_COUNT; i++) {
printf("%d ", mainNumbers[i]);
}
printf("\nPowerball (1 out of 26): %d\n", powerball);
return 0;
}
/*
run:
Powerball numbers (5 out of 69): 4 9 31 44 64
Powerball (1 out of 26): 8
*/