Thread: Random Nos

  1. #1
    Unregistered
    Guest

    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??

  2. #2
    Unregistered
    Guest
    //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);
    }

  3. #3
    Registered User
    Join Date
    Dec 2001
    Posts
    194
    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

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Lesson #3 - Math
    By oval in forum C# Programming
    Replies: 2
    Last Post: 04-27-2006, 08:16 AM
  2. Another brain block... Random Numbers
    By DanFraser in forum C# Programming
    Replies: 2
    Last Post: 01-23-2005, 05:51 PM
  3. How do I restart a random number sequence.
    By jeffski in forum C Programming
    Replies: 6
    Last Post: 05-29-2003, 02:40 PM
  4. Replies: 3
    Last Post: 01-14-2002, 05:09 PM
  5. Best way to generate a random double?
    By The V. in forum C Programming
    Replies: 3
    Last Post: 10-16-2001, 04:11 PM