Hello

I have a function that takes in an array as a parameter & puts random numbers into the array. I will run this function over 10 times during the program & I want each time I run the program for a different set of numbers to be in the array.

Currently when I run the function repeatedly, the array is output with the same set of random numbers each time.

Is there a way to get the function to output a different set of random numbers each time the function is called?

#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>

using namespace std;

void random(int array[], int max);  // No repeats :D

int main()
{
	int a[6];

            for (int i = 0; i < 10; i++)
	{
		srand(time(NULL));
		random(a,40);

		for (int i = 0; i < 6; i++)
		{
			cout << a[i] << " ";
		}

		cout << endl;
	}

	return 0;
}

void random(int array[], int max) {

	int n;
	int match = 0;     // check if any numbers are repeated
	srand(time(NULL));

	for (int i = 0; i < 6; i++)
	{
		n = (rand()%max)+1;
		for (int j=0; j<6; j++) {
			if (n == array[j]) {
				match++;
			}
		}
		if (match==0) {
			array[i] = n;
		}
		else { array[i] = (n+rand()%max); }

		match = 0;
	}
}

Check your last thread!
http://www.daniweb.com/forums/post936815.html#post936815

I took ur advice, as you can s from my code above where srand(time(null)) is put before the call to the random function, like you said. But the same set of numbers still repeats after every new call.

I said take it out of the loop. In your code it's in the loop in the function random and it's in the loop in main. It shouldn't be in either. Take it out from both of those and seed rand once in main.

Seeding it with a time value that's a number in seconds, I think, will not give you a good random number as each time it's being seeded by the same value so it'll give the same output.

#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>

using namespace std;

void random(int array[], int max);  // No repeats :D

int main()
{
	int a[6];

		srand(time(NULL));

            for (int i = 0; i < 10; i++)
	{
		random(a,40);

		for (int i = 0; i < 6; i++)
		{
			cout << a[i] << " ";
		}

		cout << endl;
	}

	return 0;
}

void random(int array[], int max) {

	int n;
	int match = 0;     // check if any numbers are repeated

	for (int i = 0; i < 6; i++)
	{
		n = (rand()%max)+1;
		for (int j=0; j<6; j++) {
			if (n == array[j]) {
				match++;
			}
		}
		if (match==0) {
			array[i] = n;
		}
		else { array[i] = (n+rand()%max); }

		match = 0;
	}
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.