Eng-Tips is the largest engineering community on the Internet

Intelligent Work Forums for Engineering Professionals

two quick questions

Status
Not open for further replies.

tbwttihs

Mechanical
Aug 4, 2003
20
0
0
US
firstly, im trying to generate 'random' numbers between zero and 49 (guess what for). currently im using:

time_t t;
srand(unsigned (time(&t)));
int num = (rand() % 49);

but as that stands, the numbers im getting dont seem very random. in fact they seem like theyre just being plucked from a sequential count through 0 - 49. also, its wasting a lot of time in my while loop becuase the same number will be generated lots of times before it changes. what more effective way is there of achieving this?

also, i have a simple array which im putting these numbers into "numbers[6]". for my 6 numbers. what sorta syntax would i need to use to sort it into ascending order using the qsort() function? or failing that, what other simple sort algorithms are there that could be used?

cheers,

craig.
 
Replies continue below

Recommended for you

answer to ur second question:

why not use a simple sorting alg like bubble sort or selection sort and get done with it, and ur array size seems to b really small and no optimization is needed.
 
The algo below is what I use for picking unique cards in the card games I used to write in Uni. Basically pick one and put the one at the end in its position.
You could use selection sort to sort the numbers.
Code:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>

#define NOTPICKEDMAX 50
#define PICKEDMAX 6
int main(int argc, char* argv[])
{
    int notpicked[NOTPICKEDMAX], n, p, remain, picked[PICKEDMAX], temp;
    
    srand (time (0));
    
    // Set up a list of numbers we can pick
    for (n = 1; n < NOTPICKEDMAX; n++)
        notpicked[n] = n;
    
    remain = NOTPICKEDMAX;
    for (p = 0; p < PICKEDMAX; p++)
    {
        // Get a number
        remain--;
        n = rand () % remain + 1;
        picked[p] = notpicked[n];
        
        // Move the one that we did not choose to the vacant position
        notpicked[n] = notpicked[remain];
    }
    
    // Sort the numbers in order
    for (p = 0; p < PICKEDMAX - 1; p++)
    {
        for (n = p + 1; n < PICKEDMAX; n++)
        {
            if (picked[p] > picked[n])
            {
                temp = picked[n];
                picked[n] = picked[p];
                picked[p] = temp;
            }
        }
    }
    
    // Print it out
    for (p = 0; p < PICKEDMAX; p++) 
        printf ("%d ", picked[p]);
    printf ("\n");
    return 0;
}
 
Status
Not open for further replies.
Back
Top