View Single Post
  #1   Spotlight this post!  
Unread 30-07-2012, 19:50
Zholl Zholl is offline
Registered User
AKA: Chris Sherwood
FRC #2996 (Cougars Gone Wired)
Team Role: Alumni
 
Join Date: Dec 2008
Rookie Year: 2008
Location: Colorado Springs
Posts: 267
Zholl is a splendid one to beholdZholl is a splendid one to beholdZholl is a splendid one to beholdZholl is a splendid one to beholdZholl is a splendid one to beholdZholl is a splendid one to beholdZholl is a splendid one to beholdZholl is a splendid one to behold
Replacing duplicates in a randomly generated array

Hello all! I've been working on a small C program to help me study. The basic idea is that I can randomly generate a problem set from a given range of questions in a textbook to a size I choose, and have the program spit out that set in numerical order (yes, I do realize that there are much easier ways to do this. I chose to use this as an opportunity to practice some coding as well ). The only issue I've had is that the rand function does spit out duplicate numbers when I run it, so I'm wondering if anyone has any suggestions on how to remove and replace duplicate numbers within an array.

If it helps I've also attached my code thus far. It's nothing too complex, but then I'm also majoring in EE, not Comp Sci, so I haven't had much occasion to learn anything more advanced

Code:
/* Generate random problem set for a given range

input minimum number
input max number
input set size
generate problems of number set size within range
output in numerical order */

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void) {
	int setSize, max, min; //inputs
	int set[30] = {0}; //starting array
	int range; //range for random generation
	int gen, i, j, k; //indexes
	int temp; //bubble sort temporary storage

	//collect inputs
	printf("Minimum problem number: ");
	scanf("%d", &min);
	printf("Maximum problem number: ");
	scanf("%d", &max);
	printf("Size of problem set: ");
	scanf("%d", &setSize);

	//calculate range for generation
	range = max - min;
	//seed random number generator
	srand(time(NULL));

	//generate problem set to given size 
	for (gen = 0; gen < setSize; gen++) {
		set[gen] = ((rand() % range) + min); //rand generates 0 to range, adding min compensates for bottom edge of problem range
	}

	//bubble sort from least to greatest
	for (i = 29; i > 0; i--) {
		for (j = 1; j <= i; j++) {
			if (set[j-1] > set[j]) {
				temp = set[j-1];
				set[j-1] = set[j];
				set[j] = temp;
			}
		}
	}

	//display problem set, excluding 0s
	for (k = 0; k <= 30; k++) {
		if (set[k] > 0) {
			printf("%d\n", set[k]);
		}
	}
}