First of all, computing a number mod A (num % A) gives you a number from 0 to A-1, not 0 to A. Also, in C, mod doesn't work correctly with negative numbers but there's an easy fix and its not important.
Secondly, its quite simple to extend this to work in 2D. Consider your set to grow so that you have a ROW_RANGE and a COL_RANGE so that your array is numbers[ROW_RANGE][COL_RANGE]. The modified code looks like this:
Code:
do
{
ball = rand()%(ROW_RANGE*COL_RANGE); // X
}while(numbers[ball/COL_RANGE][ball%COL_RANGE]); //Y
Then you set this number to 1 and whatever, you should be able to get the rest.
Instruction X gives a number between 0 and ROW_RANGE*COL_RANGE - 1
Instruction Y divides this number by COL_RAGE to get the row and mods it by COL_RANGE to get the column. Work out a simple example and you will see it works. As long as you know how mod works (takes the remainder) then you should be able to understand this.
I'm feeling less lazy so I will explain more. Imagine that you have a 3 X 4 array.
0 1 2 3
4 5 6 7
8 9 .....
Element 0 starts the zeroth row, Element 4 starts the first row, Element 8 starts the second row, ..... , Element 4*i starts the ith row. So diving the number by column (=4) will give you the row its in.
Now notice that element 0 (4,8, ... , 4*j) is in the 0th col, element 1 (5,9, ... , 4*j+1) is in the 1st col, element 2 (6,10, ... , 4*j + 2) is the 2nd col. If you notice the remainder of each of these numbers is the column index its in, so modding the number by col ( = 4) will give you the column its in.
Now if you want to write better code then that busy while loop isn't necessary.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define RANGE 50
#define BALLS 50
int main()
{
int numbers[RANGE];
int c, ball;
puts("L O T T O P I C K E R\n");
srandom((unsigned)time(NULL));
/* initialize array */
for(c = 0; c < RANGE; c++)
numbers[c]=c+1;
printf("Press Enter to pick numbers: ");
getchar();
/* draw numbers */
puts("Here they come: ");
for(c = 0; c < BALLS; c++)
{
ball = rand() % (RANGE - c);
printf("%d ", numbers[ball]);
numbers[ball] = numbers[RANGE - c -1];
}
printf("\n\nGood luck in the drawing!\n");
return(0);
}
Here's smarter code that I will not explain in detail. It revolves around only selecting numbers from a set of numbers not chosen already though. That's what this line: numbers[ball] = numbers[RANGE - c -1]; allows you to do. Define both range and balls to 1 million in both your code and the code I posted and compare run times.
I admittedly don't remember how rand() works since I only use drand48(). I'm also too lazy to look it up but the concept is right if rand() generates large numbers.