/****
 *
 * This program does some simple experimentation with the rand function, with
 * an eye towards a deck shuffling function.  This comment is purposely vague,
 * since the intention of this example is to stimulate your thinking.
 *
 */

#include <stdio.h>	       /* The regularly used lib for input/output */
#include <stdlib.h>	       /* Lib containing the rand and srand functions */
#include <time.h>	       /* Lib containing the time function */


int main() {

    int rands[52];	      /* Array of 52 random numbers, between 0 and 51
			         inclusive */
    int already_used[52];     /* Array indicating if a random number between
			         0 and 51 has already been chosen */
    int i;		      /* Loop and array index */
    int r;		      /* Next generated random number */
    int dups = 0;	      /* Counter for number of thrown away duplicates */

    /*
     * To get genuine random numbers, we need to "seed" the rand function with
     * a different value every time we call it.  To test a program, it's best
     * NOT to seed the rand function this way, so we get a repeatable random
     * sequence.  When a program is used in actual card game playing, we'll
     * turn the seeding on, with this function call:
     *
     *    srand((int) time(0));
     *
     * You should leave this call commented out for programming assignment 3.
     */

    /*
     * Initialize all already_used elements to false to indicate that each is
     * initially unused.
     */
    for (i = 0; i < 52; i++) {
	already_used[i] = 0;
    }

    /*
     * For each element of rands, store an unused random number in it.
     */
    for (i = 0; i < 52; i++) {

	/*
	 * Generate the next unused random number in the 0-51 sequence by
         * finding an unused slot in already_used.
	 */
	for (r = rand() % 52; already_used[r]; r = rand() % 52) {
	    dups++;
	}

	/*
	 * Put the unused number in the next successive slot of rands and mark
	 * the already used slot for that number as used.
	 */
	rands[i] = r;
	already_used[r] = 1;
    }

    /*
     * Dump out the rands array.
     */
    for (i = 0; i < 52; i++) {
	printf("%d\n", rands[i]);
    }
    printf("\n");

    /*
     * For information purposes, dump out the number of thrown away
     * duplicates.  This number isn't really important, it's just helps clarify
     * what this algorithm is doing.
     */
    printf("%d dups\n", dups);

    return 0;
}