Looping through an array problem

Oct 16, 2013 at 10:58am
Hi everyone! I'm trying to loop through an array (initialised to zero) 5 times at random positions in the array, then place a number count in that position. i.e. 1 - 5 in random positions within the array. Each position in the array is checked if it's available first. If not available, I want to find another random position that is available. My code below runs fine except sometimes it doesn't have all five random positions in the array. i.e. sometimes it only will have 3 or 4 random positions and not the 5 I'm after....

Any clues or advice please.

Many Thanks

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
50
51
52
53
// Compiler = MSV C++ 2010 Express
// Platform = Windows 7

#include <iostream>
#include <ctime>
#include <iomanip>
#include <cstdlib>

using namespace std;

int main()
{
	int GridArray[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};	
	int GridPos = 0;	
	int Num = 0;
	char ch = 'y';

	bool IsGridPosAvail = false;

	srand((unsigned)time( NULL ));
	do
	{
		for(int i = 0; i < 5; i++)
		{
			IsGridPosAvail = false;
			do
			{
				GridPos = (rand()% 16);
				if(GridArray[GridPos] == 0)
				{
					IsGridPosAvail = true;
					GridArray[GridPos] = Num+1;
					Num++;
				}				
			}while(IsGridPosAvail = false);
		}
		for(int i = 0; i < 16; i++)
		{
			cout << setw(3) << GridArray[i] << " ";		
		}	

		for(int i = 0; i < 16; i++)
		{		
			GridArray[i] = 0;
		}
		Num = 0;
		cout << endl;
		cin >> ch;
	}while(ch == 'y');          //Only placed in code for testing perposes
                                    
	cin.ignore();
        return 0;
}
Oct 16, 2013 at 11:14am
num = 1;
while ( num < 6 )
  pos = ...
  if ok, write and increase

Oct 16, 2013 at 11:21am
Many thanks!!! That works perfectly.
Topic archived. No new replies allowed.