Choosing x numbers randomly from a list

Hello,

I have to program a little algorithm, where:

input: int array[1,2,6,34,7,23,54,33,98,13]
(the input is an array, with x random numbers)

output: int array[4,23,33]
(the output is an array, whit y random numbers, where y<x, and each number is choosed from the initial array only once, there can not be duplication)

I have written one version, but maybe there are another tips/tricks, how to solve this issue...
As far as I know, the while is a bit dangerous to use in these cases (to prevent infinite loop)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <time.h>	

using namespace std;

int main()
{	

	int kitchen_max[9] = {10,15,22,45,51,69,83,92,100};	// initial array with 9 numbers
	int kitchen_now[5];	// new array to store the randomly choosed 5 numbers
	
	// initialize the array with zero values
	for (int i=0;i<5;i++)
		kitchen_now[i]=0;
		
	// while the last member of the array 'kitchen_now' is zero...
	while(kitchen_now[4]==0)
	{
		srand ((int)time(NULL));
		int actual_number = rand() % 9;

		// we choosed the 'actual_number'th member of the initial array
		actual_number = kitchen_max[actual_number];
		
		// search for free place to insert randomly choosed number from array
		for (int i=0;i<5;i++)
		{	
			if (kitchen_now[i] == 0)
			{			
				// check, if the array 'kitchen_now' does not contains the current value
				int j = 0;
				while (j<5)
					if (kitchen_now[j] == actual_number)
						j = 100;
					else 
						j++;

				if (j != 100)
					kitchen_now[i] = actual_number;
			}
		}
	}

	// print out the result array
	for (int i=0;i<5;i++)
		cout << i << ". number: " << kitchen_now[i] << endl;
}
Last edited on
Use random_shuffle() on the array and then just iterate through the array. :-)
and anyway, what is this functions call used for?

1
2
		srand ((int)time(NULL));
		int actual_number = rand() % 9;


why is not enough simply call this line?

int actual_number = rand() % 9;

why is this important, and what is the meaning of this line exactly? srand ((int)time(NULL));
http://www.cplusplus.com/reference/clibrary/cstdlib/srand/

you have to seed the random generator that's why you use srand() func.

another way to do it is

1
2
3
4
5
6
7
8
while(kitchen_now[4]==0)
	{
		srand ((int)time(NULL));
		//int actual_number = rand() % 9;

		// we choosed the 'actual_number'th member of the initial array
		actual_number = kitchen_max[rand()%9];
		


what i know the above code should work since rand() returns an integer.

Last edited on
hello, thanks for your answer, but unfortunately my english is not enough good, can you please describe more these "seed" process, what is needed?

Topic archived. No new replies allowed.