How to make the code with Random numbers and Time Executation?

#include <iostream> /* cout */
#include <cstdlib> /* srand, rand */
#include <ctime> /* time() */
#include <list> /* list */

#define BASE 10 // # of buckets to use
#define ARRAY_SIZE 50 // max # of elements in array

using namespace std;

// function prototypes
void radix(int* nums, int length, int max);

int main() {
    int nums[ARRAY_SIZE];
    int i;
    int max=0;
    srand(time(NULL));

    // store random numbers to array, print their current order
    cout << "Before:\r\n";
    for (i=0; i<ARRAY_SIZE; i++) {
        // generate random #, 1-1000
        nums[i] = rand()%1000 + 1;

        // determine max element upon addition to array
        max = (nums[i] > max)? nums[i]: max;
        cout << "\t" << nums[i] << "\r\n";
    }
    cout << endl << endl;

    // sort using radix algorithm, passing max element
    radix(nums,ARRAY_SIZE,max);

    // print sorted array
    cout << "After:\r\n";
    for (int i=0; i<ARRAY_SIZE; i++)
        cout << "\t" << nums[i] << "\r\n";

    return 0;
}

void radix(int* nums, int length, int max) {
    list<int> bucket[BASE];
    int i;

    // iterate through each radix until n>max
    for (int n=1; max >= n; n *= BASE) {
        // sort list of numbers into buckets
        for (i=0; i<length; i++)
            bucket[(nums[i]/n)%BASE].push_back(nums[i]);

        // merge buckets back to list
        for (int k=i=0; i<BASE; bucket[i++].clear())
            for (list<int>::iterator j = bucket[i].begin(); j != bucket[i].end(); nums[k++] = *(j++));
    }
}

Recommended Answers

Did you copy this code from somewhere? I have a hard time believing that you could produce this code and not know how to generate random numbers.

Jump to Post

So what is your problem now??
Do you have any issues??

Jump to Post

All 5 Replies

Did you copy this code from somewhere? I have a hard time believing that you could produce this code and not know how to generate random numbers.

Yes I sow it in one website, but how can I do it with random numbers? Can You help me

Line 24 of the code you posted rand()%1000 + 1; is generating random numbers.
rand() function generates a random number, %1000+1 makes sure that you get a number not exceeding 1000. SO you get a random number not exceeding 1000

So what is your problem now??
Do you have any issues??

No it's ok thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.20 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.