Pick randomly from array


Hello,

I was wondering if there is a way of randomly picking a number from the following array... BUT... only picking each number once....

const char arrayNum[4] = {'1', '3', '7', '9'};


Thanks...


Hi Yoshima, there are a few ways to go about this, I'll show you what I think is the easiest. First you need to import the headers <stdlib.h> and <time.h> (the reason behind needing time will be clear in a moment). Every time you generate a random number in windows, it uses a pre-determined algorithm to produce the number. This means the "Random" number will be the same every time you run your program. In order to make your "random" number truely random, we will use the current time as the random seed and then use some basic algebra to reduce the number down to the range we need it in. In this case we will generate a random number between 0 and 3 that we will use as an index for your array. Here is an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <stdlib.h>
#include <time.h>

int main ()
{
  srand ( time(NULL) ); //initialize the random seed
  

  const char arrayNum[4] = {'1', '3', '7', '9'};
  int RandIndex = rand() % 4; //generates a random number between 0 and 3
  cout << arrayNum[RandIndex];
}
ok.. cool...

but I was also wondering if I could generate a random sequence from the array so that each number appears in the sequence and only appears once....

eg...

'1', '9', '3', '7'
or
'9', '3', '7', '1' ... and so on...
If you are using C++:

std::random_shuffle(array, array+SIZE);

If you are using C, then just randomly swap two elements in the array a couple times.
Great... thanks firedraco... that worked...

for those who are interested... I used this...

1
2
3
4
#include <algorithm>

char cornerMoves[4] = {'1', '3', '7', '9'};
random_shuffle(&cornerMoves[0], &cornerMoves[3]);
This wouldn't happen to be a tick-tac-toe engine would it? lol
closed account (D80DSL3A)
@firedraco. Nice! How big is that magic bag of functions? I'll be looking into it!
The need to randomize elements has come up in my game projects for Scrabble (scramble the tile pool after filling it with the required distribution of letters) and in minesweeper to place the mines on the field. My take at re-inventing the wheel:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// places randomly selected  element at end of array
// then shrinks array by 1 element. Done when only 1 element is left
void RandomElements(int* v, int n)
{
	int temp = 0;
	int ridx = n-1;

	for(int j=(n-1); j>1; j--)// one pass through array
	{
		ridx = rand()%(j+1);// index = 0 to j
		temp = v[ridx];// value will be moved to end element
		v[ridx] = v[j];// end element value in random spot
		v[j] = temp;// selected element moved to end. This value is final
	}
	return;
}
Topic archived. No new replies allowed.