-
Random Nos
I want to jumble up numbers from 1 to 16 and store them in an array for a game i'm planning. I have tried various approaches but nothing seems to work. This is how i am generating a random no:
srand((unsigned)time(NULL));
int random_no=rand()%16;
random_no++;
Any ideas??
-
//Here this should do what you are looking for:
#include<iostream>
using std::cout;
using std::endl;
#include<cstdio>
#include<ctime>
const int MAX = 10;
main()
{
int game_numbers[MAX];
srand((unsigned)time(NULL));
for(int i =0; i < MAX; i++)
{
game_numbers[i] = (rand()%16) + 1;
}
for(i = 0; i < MAX; i++)
{
cout << game_numbers[i] << endl;
}
return (0);
}
-
Code:
#include <iostream>
#include <string>
#include <ctime>
using namespace std;
#define MAX 16
#define SWAPS 50
int main()
{
int nums[MAX],i,place1,place2,temp;
//seed the rand function
srand(time(NULL));
//initalize the array with 1..16
for( i=0 ; i<MAX ; i++)
{
nums[i]=i+1;
}
// loop for as many swaps that we want to do
for( i=0 ; i<SWAPS ; i++)
{
//place1 and place2 are random places in the array
place1 = rand() % MAX;
place2 = rand() % MAX;
//save the var at place 1
temp = nums[place1];
//move the var from place2 to place1
nums[place1] = nums[place2];
//move the old place1 to place 2
nums[place2] = temp;
}
for( i=0 ; i<MAX ; i++)
{
cout << "i is " << i << ":" << nums[i] << endl;
}
return 0;
}
That is a crude yet effective numer mixer-uper :)
Change SWAPS if your numbers aren't mixed up enough