Skip to main content
GameDev.net gamedev.net
🔒 Locked

Question about Arrays.

Started by Toti Jun 16, 2002 at 9:34 AM 4 replies 450+ views
Original Post
Toti
Toti
I was just wondering if there is any way to take a set of numbers and randomly place them in an array. For example, I would take the numbers 1 through 10 and randomly place them in array[10]. Thanks. Toti Mannino
Toti M.
erjo
erjo

  
char Array[10];
int num;
for( int i = 0; i < 10; i++ )
Array[i] = 0;
for( i = 0; i < 10; i++ )
{
num = rand()%9;
while( Array[num] != 0 )
num = rand()%9;
Array[num] = i+1;
}

Or am I totally wrong?

Eric

Toti
Toti
Ah, I''ve seen the rand() function before but never knew how it worked. I suppose I should get on the ball about these things.

Toti Mannino
Toti M.
alvaro
alvaro
Try this:


  
int Array[10];

// Initialize to the desired set of numbers

for(int i=0;i<10;++i)
Array[i]=i+1;

// Shuffle

for(int i=9;i>0;--i){
int j=rand()%(i+1);
int temp=Array[i];
Array[i]=Array[j];
Array[j]=temp;
}



SabreMan
SabreMan

  
#include <algorithm>

#include <vector>

#include <iostream>

#include <cstdlib>

#include <ctime>

using namespace std;

int main()
{
vector<int> v;

for(int i=0; i<10; ++i)
v.push_back(i);

srand(time(0));
random_shuffle(v.begin(), v.end());

for(vector<int>::const_iterator it = v.begin(); it != v.end(); ++it)
cout << *it << "\n";
}
Toti
Toti
Thanks for your help. =]

Toti Mannino
Toti M.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.