Rand() help

Ok so I have been working with rand and here is what i dont get, the book for our school does not explai it well so I need some of you to explain if you do not mind here is a simple code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include "stdafx.h"
#include<iostream>
#include<ctime>
using namespace std;



int main()
{

	srand(time(0));

	int num[]={1,2,3,4,5,4};

	for(int i =0;i<5;i++)
	{
		num[i]= rand() % 5 + 1;

		cout<<num[i];
	}
	system("pause");
	return 0;
}




Ok my thing is after you put rand() and then the NUMBER what does the number do i understand the +1 starts it passed 0? i guess i do not understand this entire line

rand() % 5 + 1;
Rand() generates a random number. It can be any number big or small. The % 5 gets the remainder when you divide by 5. If you divide by 5 its possible to get a remainder 0-4 so any number % 5 = 0 through 4. And since your looking for numbers 0-5 you add 1 to the remainder
okso how do you determine what number to use after the rand() %
Depends what random numbers your looking for. If you need numbers 1-100 its
rand() % 100 + 1
Also your missing
#include <cstdlib>
closed account (j3Rz8vqX)
As football52 stated:

-rand() return a random number of any given size, randomly.

-% is the modular arithmetic symbol, it subtracts by the next number till it can no longer and take the result; example: 13%3=10%3=7%3=4%3=1.

-the last value would add to the arithmetic last; because modulo has priority compare to addition. Same applies to multiplication before subtraction.
http://www.cplusplus.com/doc/tutorial/operators/
ok when i do this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include "stdafx.h"
#include<iostream>
#include<ctime>
#include <cstdlib>
using namespace std;



int main()
{

	srand(time(0));

	int num[]={1,2,3,4,5,4};

	for(int i =0;i<5;i++)
	{
		num[i]= rand() % 6 ;

		cout<<num[i]<<endl;
	}
	system("pause");
	return 0;
}



why doesnt it just randomize the numbers in my array?
closed account (j3Rz8vqX)
What does your output display?

I bet: random numbers between 0 and 6.

Edit:
why doesnt it just randomize the numbers in my array?


Are you referring to randomly sorting your array?

That isn't what it's doing.

It is randomly generating a value and you're assigning it your variable at array indexed i.
Last edited on
When you set num = rand() % 6; you are completly ignoring the numbers you have already set for the numbers in your array.

What are you trying to achieve? A random set of numbers in a random order or just one random number. The way you have it, it is only generating one random number then it loops and generates another random number.
Just so that there's no possibility for confusion.
Here's how rand() works:

rand() will return a pseudo-random number between zero and RAND_MAX.

RAND_MAX is a macro that's defined in the cstdlib header. What this value is, is library dependent, but it's guaranteed to to be at least 32767 on any standard library implementation.

On my system, RAND_MAX is defined in stdlib.h, which is included by cstdlib, but that's a technicality.
On my system, RAND_MAX is defined as 0x7fff, which is equivalent to 32767.

Therefore, if you write:

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <cstdlib>

int main() {

	int value = rand();

	std::cout << value << std::endl;

	std::cin.get();
	return 0;
}


It should print some value between zero and whatever your definition of RAND_MAX is. For me, it prints out 41.

However, it will always print the same number, regardless of how many times we run the program. This is where the "pseudo" part comes in. Before you use rand(), you have to "seed" it with srand().
rand() doesn't really return a random number. It returns the result of a seemingly random calculation. One of the variables involved in this calculation is the "seed", which means that if you want "random" numbers, you need to provide a seed that's different every time you run the program.

This can be achieved by providing the system time as a seed, since the system time will be different practically every time the program is executed, which is good enough for most beginner purposes.

Typically, one seeds rand() at the beginning of the program, and you must only do so once.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <ctime>

int main() {

	srand(time(0));

	int value = rand();

	std::cout << value << std::endl;

	std::cin.get();
	return 0;
}


This should print a different value every time the program is executed.

The values that rand() returns to us only become really useful, when it allows us to generate numbers within a certain range.

We can make use of the modulus operator (%). The modulus operator finds the remainder of a division of one number by another.
Given two integers 'a' (the dividend), and 'n' (the divisor), the expression "5 mod 2" would evaluate to 1, because 5 divided by 2 leaves a quotient of 2 and a remainder of 1.

This allows us to effectively "limit" the numbers being generated with rand(). To be more specific, our random number will be the result of the division of the value returned by rand(), by the largest, maximum value from our desired range.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <ctime>

int main() {

	srand(time(0));

	int value = rand() % 10;

	std::cout << value << std::endl;

	std::cin.get();
	return 0;
}


This will print a "random" number between zero and ten (0-9).
This is fine as long as your desired number range is above zero.

Anyways, I hope you realize why your snippet is wrong. As the others have already stated, what you're doing is assigning new "random" values to each element of the array. You aren't actually "randomly" shuffling the order of the elements if that's what you were trying to achieve.
ok so now i understand about the number after the % and i get what that does but how would i make my array numbers come up as random
closed account (j3Rz8vqX)
You can sort your array before you print it to produce what you may be attempting:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// random_shuffle example
#include <iostream>     // std::cout
#include <algorithm>    // std::random_shuffle
#include <ctime>        // std::time
#include <cstdlib>      // std::rand, std::srand

// random generator function:
int myrandom (int i) { return std::rand()%i;}

int main () {
  //std::srand ( unsigned ( std::time(0) ) );
  int a[10];

  // set some values:
  for (int i=0; i<10; ++i)
    a[i]=i; // 1 2 3 4 5 6 7 8 9

  // using built-in random generator:
  std::random_shuffle ( &a[0], &a[10]);

  // using myrandom:
  std::random_shuffle ( &a[0], &a[9], myrandom);

  // print out content:
  std::cout << "My array contains:";
  for (int i=0;i<10; ++i)
    std::cout << ' ' << a[i];

  std::cout << '\n';

  return 0;
}


The above is a modified version of:
http://www.cplusplus.com/reference/algorithm/random_shuffle/
that is passing an array argument instead of vector.

The first call with 2 arguments call the default random shuffle operation.
The second call with 3 arguments call random shuffle with an implemented comparison option; passing a function).

If you want to randomly print data from your array with possible repeating values, a solution could be:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// random_shuffle example
#include <iostream>     // std::cout
#include <algorithm>    // std::random_shuffle
#include <ctime>        // std::time
#include <cstdlib>      // std::rand, std::srand

int main () {
  //std::srand ( unsigned ( std::time(0) ) );
  int a[10];

  // set some values:
  for (int i=0; i<10; ++i)
    a[i]=i; // 1 2 3 4 5 6 7 8 9

  // print out content:
  std::cout << "My array contains:";
  for (int i=0;i<10; ++i)
    std::cout << ' ' << a[rand()%10];

  std::cout << '\n';

  return 0;
}


All of the supplied code were modified versions of:
http://www.cplusplus.com/reference/algorithm/random_shuffle/
Topic archived. No new replies allowed.