Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
Solved

# Random Number Generation from a specified set

Posted on 2003-02-20
Medium Priority
178 Views
How do I go about generating a random number from a specified set?
For instance, I need to generate a number from the set { 1, 4, 7, 10, 13, 16);
0
Question by:skips2ndbase
• 3
• 3

LVL 8

Expert Comment

ID: 7991333
#define setsize 6 // u know ur set size;
int set[]={1,4,7,10,13,16};

srand(time(NULL));

int gimmeRandomFromSet(int *set,int setsize){
int j;
j=(int) (((float)setsize)*(rand()/(RAND_MAX+1.0)));
// above gives u random number between 0 and setsize;
// so ur random number is now..set[j]
return set[j];
}

calll it like this

gimmeRandomFromSet(set,setsize);
0

LVL 8

Expert Comment

ID: 7991337
int randfromset=gimmeRandomFromSet(set,setsize);

now use randfromset
0

LVL 8

Expert Comment

ID: 7991388
#include <iostream>
#include <stdlib.h>

using namespace std;

#define ARRAYSIZE 6

void main()
{
srand(time(NULL));
int set[]={1,4,7,10,13,16};
cout << "Randomly generated " << set[rand()%size] << " from the specified set of numbers." << endl;
}

0

LVL 8

Expert Comment

ID: 7991394
Dang!!! I forgot that I was in the C topic area. "-)

#include <stdio.h>
#include <stdlib.h>
#incldue <time.h>

#define ARRAYSIZE 6

int main()
{
int set[]={1,4,7,10,13,16};
srand(time(NULL));
printf("Randomly generated %i from the specified set of numbers.\n",set[rand()%ARRAYSIZE]);
return 0;
}

Exceter
0

LVL 8

Accepted Solution

Exceter earned 150 total points
ID: 7991399
>> #incldue <time.h>

#include <time.h>
0

LVL 8

Expert Comment

ID: 7994144
hmm i guess my solution was good enough.. whatever followed was just a rewrite..
anyways not for the first time with me
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
The goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.
###### Suggested Courses
Course of the Month11 days, 11 hours left to enroll