Jump to content

I am supposed to write a function that generates a random number between numbers that are parameters.  So when using this function, for example, if I want a number between 1 and 10, I would type

random(1,10).  

Can someone show me how to do this?  Any help is much appreciated

Processor Intel Core i5-4690K CPU Cooler Cooler Master Hyper 212 EVO Motherboard MSI Z97-G45 RAM 8GB G.Skill Ripjaws X Storage Samsung 850 EVO 250GB SSD WD Caviar Blue 1TB HDD Graphics Card EVGA GeForce GTX 970 Case NZXT Phantom (Black) PSU Corsair CX600M Operating System Windows 10 Monitor BenQ GL2760H Headset Skullcandy PLYR 1 & Sennheiser Momentum

 

Link to comment
https://linustechtips.com/topic/675643-c-homework-please-help/
Share on other sites

Link to post
Share on other sites

http://www.cplusplus.com/reference/cstdlib/rand/

 

If your interval is n numbers (eg 4 to 10 inclusive, n=7) then you do modulus n, like this:

%n

Where n is (b-a+1)

 

Then since rand starts from 0, you want to add the minimum number (in this case 4) to the result, so that instead of 0-6 it goes 4-10.

 

The end result would be 

rand() %(b-a+1) +a

 

If you want it to not be inclusive, and only do what is between a and b, then just do

rand() %(b-a-1) +a+1

 

I think you get the idea :)

NEW PC build: Blank Heaven   minimalist white and black PC     Old S340 build log "White Heaven"        The "LIGHTCANON" flashlight build log        Project AntiRoll (prototype)        Custom speaker project

Spoiler

Ryzen 3950X | AMD Vega Frontier Edition | ASUS X570 Pro WS | Corsair Vengeance LPX 64GB | NZXT H500 | Seasonic Prime Fanless TX-700 | Custom loop | Coolermaster SK630 White | Logitech MX Master 2S | Samsung 980 Pro 1TB + 970 Pro 512GB | Samsung 58" 4k TV | Scarlett 2i4 | 2x AT2020

 

Link to comment
https://linustechtips.com/topic/675643-c-homework-please-help/#findComment-8699452
Share on other sites

Link to post
Share on other sites

Yep, rand function.

Give me a bit, I got my C++ book laying about since I just finish up that class.

 

Better way to describe that function when doing a range.

 

lowerBound + rand()%(upperBound - lowerBound + 1)

 

Ex:

cout << 1 + rand()%(6 - 1 + 1);

displays a random integer from 1 through 6.

 

Hmmm, if reading your post right you need to build a value returning function named random that has the rand function in it.  That way you don't have to keep typing the rand with the range, correct?

 

If so, this is how you go about doing it.

//function definitions

int random (int lowerBound, int upperBound)

{

     int randNum = 0;

     randNum = lowerBound + rand()%(upperBound - lowerBound + 1);

     return randNum;

}  //end of random function

 

There you can just use that function without having to type that blasted rand function about.  Could probably build it as a void function as well.

 

2023 BOINC Pentathlon Event

F@H & BOINC Installation on Linux Guide

My CPU Army: 5800X, E5-2670V3, 1950X, 5960X J Batch, 10750H *lappy

My GPU Army:3080Ti, 960 FTW @ 1551MHz, RTX 2070 Max-Q *lappy

My Console Brigade: Gamecube, Wii, Wii U, Switch, PS2 Fatty, Xbox One S, Xbox One X

My Tablet Squad: iPad Air 5th Gen, Samsung Tab S, Nexus 7 (1st gen)

3D Printer Unit: Prusa MK3S, Prusa Mini, EPAX E10

VR Headset: Quest 2

 

Hardware lost to Kevdog's Law of Folding

OG Titan, 5960X, ThermalTake BlackWidow 850 Watt PSU

Link to comment
https://linustechtips.com/topic/675643-c-homework-please-help/#findComment-8699606
Share on other sites

Link to post
Share on other sites

Just now, fizzlesticks said:

This is C++ not C, rand is horrible and shouldn't be used.

http://www.cplusplus.com/reference/random/

I wouldn't use it if it wasn't required for this assignment

Processor Intel Core i5-4690K CPU Cooler Cooler Master Hyper 212 EVO Motherboard MSI Z97-G45 RAM 8GB G.Skill Ripjaws X Storage Samsung 850 EVO 250GB SSD WD Caviar Blue 1TB HDD Graphics Card EVGA GeForce GTX 970 Case NZXT Phantom (Black) PSU Corsair CX600M Operating System Windows 10 Monitor BenQ GL2760H Headset Skullcandy PLYR 1 & Sennheiser Momentum

 

Link to comment
https://linustechtips.com/topic/675643-c-homework-please-help/#findComment-8699682
Share on other sites

Link to post
Share on other sites

The easiest way of doing it is definitely with modulo as @Enderman described, and you should probably stick to it.

 

Just for the sake of it and to enlighten our knowledge in generating random numbers in C++, let's cover other ways of doing it D:.

 

1.You could generate a random normalized value then scale it to your interval. To get a normalized random value you divide the result of your rand function by RAND_MAX ( the maximum rand() can return), then to scale it you multiply with the difference between the heads of the interval and add the left head of the interval to bring it into place. Pretty much :

(float)rand()/RAND_MAX*(dr-st+1)+st

This will generate a real number, keep in mind.

 

2.Let's assume you want just random integers. It's pretty obvious that rand()%n will not give you a uniform distribution for numbers in the range [0,n]. Not only that, but you don't know if the moduli of rand() are, indeed, random, they could maybe go 0,1,2,..., which might be uniform, but it's not random. So we can safely assume that rand() produces a Poission distribution. This implies that you can achieve a uniform distribution and scattered values for a finite set of values.

Anyway, using floating point numbers could be somewhat ok, but it suffers from rounding errors in principle. So to achieve this using only integer operations we could do something like this :

long random(long min, long max)
{
    long x;
    max=max-min;
    unsigned long num_bins=(unsigned long)max+1,num_rand=(unsigned long)RAND_MAX+1,bin_size=num_rand/num_bins,defect=num_rand%num_bins;    
    do x = rand();    while (num_rand - defect <= (unsigned long)x);
    return x/bin_size+min;
}

3. C++11 introduced standardized pseudo-random number generators in the form of <random>.

Not going too much in depth, code would look like this :

std::random_device rd;
std::mt19937 mt(rd());
std::uniform_real_distribution<int> dist(1.0, 10.0); // or whatever your interval is
//to get a random number you simply do :
dist(mt);

 

i5 4670k @ 4.2GHz (Coolermaster Hyper 212 Evo); ASrock Z87 EXTREME4; 8GB Kingston HyperX Beast DDR3 RAM @ 2133MHz; Asus DirectCU GTX 560; Super Flower Golden King 550 Platinum PSU;1TB Seagate Barracuda;Corsair 200r case. 

Link to comment
https://linustechtips.com/topic/675643-c-homework-please-help/#findComment-8699784
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×