randomizer only generating up to 99 c++ - c++

So I am trying to generate 10,000 random numbers from 1-100, but it is only generating up to 99 numbers because when I display it I can only see from 1-99, unless it is my code for finding it. What is happening in my code is i am trying to find how many times the number is generated. Basically a frequency/histogram.
EDIT:I am generating 100, but its not displaying, i get a error
Here is my code:
vector<int> vint;
for (int i = 0; i < 10000; i++)
{
int x = (rand() % 100) + 1;
vint.push_back(x);
}
frequency(vint);
void frequency (vector<int> v1)
{
int counter = 1;
int max = 0;
int mode = v1[0];
int numbercheck = 0;
for (int pass = 0; pass < 10000-1 ; pass++)
{
if (v1[pass] == v1[pass + 1])
{
counter++;
numbercheck++;
}
else
{
cout << v1[pass] << ": " << counter << "..................." << endl;
counter = 1;
}
}

If you are using a c++11 compatible compiler then avoid using rand() and use the Mersenne-Twister engine instead for higher quality random sequences. Here is a code snippet example:
#include <random>
int main(void) {
std::random_device rd; // for random seed
std::seed_seq seed{rd(), rd(), rd(), rd(), rd(), rd(), rd(), rd()};
std::mt19937 eng(seed);
const int min = 1;
const int max = 100;
// used to generate ints in interval [min,max] (inclusive)
std::uniform_int_distribution<int> dist(min,max);
int randomInt = dist(engine); // generate random int using dist and mtengine
return 0;
}
See this (entertaining) video for some reasons on why rand() is bad:
https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful

You should accept ArchBishop's answer. Here is a simpler program for you.
#include <iostream>
#include <vector>
#include <cstdlib>
using namespace std;
int main()
{
vector<int> vint;
for(int i=0; i<10000; ++i)
{
vint.push_back(rand()%100 + 1);
}
for(const auto&e: vint)
cout << e << endl;
return 0;
}
It generated 100 for me but might not generate for you.

Related

Generate random number but required to have a certain number

I am trying to create a sequence of 4 different numbers and randomly generated from 0 to 100 but it must have number 86, here is what I did:
#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
srand((unsigned) time(NULL));
// Loop to get 3 random numbers
for(int i = 0; i < 3; i++)
{
int random = rand() % 101;
// Print the random number
cout << random << endl;
}
cout << 86 << endl;
}
But I don't want to put 86 at the end, are there any ways to place it at any random position in the sequence ? Thank you
My approach using modern C++
#include <algorithm>
#include <iostream>
#include <array>
#include <random>
namespace {
std::default_random_engine generator(std::random_device{}());
int random(int min, int max) {
return std::uniform_int_distribution<int>{min, max}(generator);
}
}
int main() {
std::array<int, 4> elements = {86};
for (int i = 1; i < elements.size(); ++i) {
elements[i] = random(0, 100);
}
std::shuffle(elements.begin(), elements.end(), generator);
for (int nbr : elements) {
std::cout << nbr << "\n";
}
return 0;
}
You can do exactly as you said - place it in a random position. First, you store the four numbers to be generated in an array; then, you decide which position is 86; then, you fill the rest and print it.
int main()
{
srand((unsigned) time(NULL));
int nums[4];
int loc86 = rand() % 4;
for(int i = 0; i < 4; i++)
{
nums[i] = i != loc86 ? rand() % 101 : 86;
}
for(int i = 0; i < 4; i++)
{
// Print the random number
cout << num[i] << endl;
}
}
A bit offtopic, but if you really care about precision of the random number generation (and that it approaches uniform random distribution well enough), you might use pragmatic c++ random number generators as described here.
Two approaches
#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
srand((unsigned) time(NULL));
// Take a random position
const int j = rand() % 4;
// Loop to get 3 random numbers
for(int i = 0; i < 4; i++)
{
if (i == j)
cout << 86 << endl;
else
cout << rand() % 101 << end;
}
}
#include<iostream>
#include<algorithm>
#include<cstdlib>
using namespace std;
int main()
{
srand((unsigned) time(NULL));
// Fill and shuffle the array
int r[4] = {86, rand() % 101, rand() % 101, rand() % 101};
std::shuffle(std::begin(r), std::end(r));
for(int i = 0; i < 4; i++)
cout << r[i] << end;
}

Generating a random value array without repeating

I want to make a method that generates an array with random values between 0 and 6 in it without repeating those values.
This is what I've got:
void randomArray(){
randNum = rand() % 6;
code[0] = randNum
for (int i = 1; i < 4; i++){
randNum = rand() % 6;
code[i] = randNum;
while (code[i] == code[i - 1]){
randNum = rand() % 6;
code[i] = randNum;
}
}
}
But I'm getting repeated values on the random-generated array.
PD: I also need to use a similar method to make an array of enum's.
You could do something like this:
int randomFromSet(std::vector<int>&_set)
{
int randIndex = rand() % _set.size();
int num = _set[randIndex];
_set.erase(_set.begin() + randIndex);
return num;
}
This chooses a random int from a provided set of numbers, and removes that choice from the set so that it can't be picked again.
Used like so:
std::vector<int> mySet {0,1,2,3,4,5,6};
std::cout<<randomFromSet(mySet)<<'\n;
#include <random>
#include <vector>
#include <numeric>
#include <iostream>
using std::cout;
using std::endl;
int main() {
const int sz = 7;
std::vector<int> nums(sz);
std::iota(std::begin(nums), std::end(nums), 0);
std::default_random_engine re;
int i = 8;
while(--i > 0) {
auto my_set{ nums };
std::shuffle(my_set.begin(), my_set.end(), re);
for (auto x : my_set) {
cout << x << " ";
}
cout << endl;
}
}
Im new to c++ , can I add my answer too?
its c-style c++ sorry for that.but its easy to code and to understand at the same time.
#include <iostream> //std::cout
#include <ctime> //time() function
#include <cstdlib> //rand() and srand() functions
void rand_gen(unsigned int arr[],unsigned int sizeofarray)
{
srand((unsigned int)time(0);
for (unsigned int c = sizeofarray ; c > 0 ; c--)
{
unsigned int r = rand()%sizeofarray;
if (arr[r] != 404)
{
std::cout<<"Try No."<<(sizeofarray+1)-c<<" : "<<arr[r]<<"\n";
arr[r] = 404;
} else { c++; }
}
}
int main()
{
unsigned int n[7]={0,1,2,3,4,5,6};
rand_gen(n,7);
std::cin.get();
return 0;
}

Generate different random numbers

I want to generate different random numbers . I used srand and rand , but in my output some numbers are identical .
This is my output :
How to do with srand to generate different numbers ?
#include<iostream>
#include<time.h>
#include <windows.h>
int main(){
time_t t;
std::vector<int> myVector;
srand((unsigned)time(NULL));
for (int i = 0; i < 40; i++){
int b = rand() % 100;
myVector.push_back(b);
std::cout << myVector[i] << std::endl;
}
Sleep(50000);
}
One easy way is to add all numbers from 0-99 to a vector and shuffle it, then you can get as many (up to 100) non repeating random numbers as you require.
#include <algorithm>
#include <chrono>
#include <iostream>
#include <random>
#include <vector>
int main(void) {
std::vector<int> numbers;
for(int i=0; i<100; i++) // add 0-99 to the vector
numbers.push_back(i);
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
std::shuffle(numbers.begin(), numbers.end(), std::default_random_engine(seed));
for(int i=0; i<40; i++) // print the first 40 randomly sorted numbers
std::cout << numbers[i] << std::endl;
}
You could use a set:
std::set<int> numbers;
while (numbers.size() < 40)
{
numbers.add(rand() % 100);
}
and then copy it into a vector if necessary.
srand number generator can give identical numbers.
You could implement a solution which deletes duplicates not adding them to the vector. For example:
#include <iostream>
#include <algorithm>
#include <vector>
int main()
{
std::vector<int> myVector;
srand((unsigned)time(NULL));
while(myVector.size() < 40)
{
int b = rand() % 100;
if ( !(std::find(myVector.begin(), myVector.end(), b) != myVector.end()))
{
myVector.push_back(b);
std::cout << myVector.at(myVector.size()-1) << std::endl;
}
}
Sleep(50000);
return 0;
}
An easy way of getting rid of duplicates is using std::unique in <algorithm>.
Here is an example of that in use:
#include <vector>
#include <iostream>
#include <algorithm>
#include <random>
int ran(int min, int max)
{
std::random_device r;
std::mt19937 gen(r());
std::uniform_int_distribution<> dis(min, max);
return dis(gen);
}
int main()
{
const int fill_size = 10;
const int min = 1; // min random number
const int max = 100; // max random number
std::vector<int> vec;
while (vec.size() != fill_size) {
vec.emplace_back(ran(min, max)); // create new random number
std::sort(begin(vec), end(vec)); // sort before call to unique
auto last = std::unique(begin(vec), end(vec));
vec.erase(last, end(vec)); // erase duplicates
}
std::random_shuffle(begin(vec), end(vec)); // mix up the sequence
for (const auto& i : vec) // and display elements
std::cout << i << " ";
}
As for me, the idea of using set is not so good, because the generating time of every new value increases. If you have enough memory it seems that usage of an array can be preferable.
In the next code, I don't use shuffle, instead, I use a random function just size times to choose one value. I add it to the destination vector, then in the source array, swap the value with the last element and decrease arr_size.
/*
* Return random unsigned int value using intrinsic
* */
unsigned getRandom() {
unsigned val;
_rdrand32_step(&val);
return val;
}
/*
* Return a vector<int> of uniq numbers in a range of [min ... max).
*
* #param min - min value.
* #param max - max value.
* #param size - amount of uniq numbers (size <= max-min).
* */
vector<int> getUniqNumbers(int min, int max, unsigned size) {
int arr_size = max - min;
int *a = new int[arr_size];
for (int i = 0; i < arr_size; i++) {
a[i] = min + i;
}
vector<int> numbers(size);
for (int i = 0; i < size; i++) {
unsigned u_rand = getRandom() % arr_size;
numbers[i] = a[u_rand];
a[u_rand] = a[--arr_size];
}
delete[] a;
return numbers;
}
You can easily achieve a unique set of random numbers writing:
#include<iostream>
#include<vector>
int main(){
std::vector<int> myVector;
srand((unsigned)time(NULL));
for (int i = 0; i < 40; i++) {
int b = rand() % 100;
if(!std::find(std::begin(myvector),std::end(myvector),b)) {
myVector.push_back(b);
std::cout << myVector[i] << std::endl;
}
}
}
This is a statistical (mathematical) issue. Random numbers may be identical to eachother. If you need unique numbers, you must check to see if they are used before. For example like this:
for (int i = 0; i < 40; i++){
int b = rand() % 100;
for (int j = 0; j < i; j++){
if(myVector[j]==b)i--;
else{
myVector.push_back(b);
std::cout << myVector[i] << std::endl;
}
}
}

Generate numbers between -30 and 30 using C++

I'd like to generate numbers between -30 and 30.
I already tried the solution in Generating random integer from a range and it gave me these results:
111875657664
151875657664
211875657664
-41875657664
-151875657664
171875657664
-201875657664
-131875657664
-301875657664
-271875657664
This is my function:
int Random::genRandom() {
int rnd;
rnd = (rand()%61)-30;
return rnd;
}
This is the main source file:
#include "Random.h"
#include <iostream>
using namespace std;
int main() {
Random random;
int randomas;
for(int i=0; i<10; i++) {
randomas = random.genRandom();
cout << randomas << "\n";
}
return 0;
}
What should I do?
Try this:
srand (time(NULL));
for(int i = 0; i < 10; i++)
{
int rnd;
rnd = rand() % (60) - 30;
cout << rnd << std::endl;
}
Working example here
This does nothing to solve the OP's bizarro number problem (which I can't seem to reproduce), but just to get this out there. C++11 and better provide a number of different ways to resolve the rand sucks issue.
I, for one, welcome our new random number generating overlords.
#include <iostream>
#include <random>
int main()
{
std::random_device device;
// build a random number generator for seeding
std::default_random_engine engine(device());
// nothing fancy. Assuming the compiler implementors know what they are doing
// seeding it with a nice random number from above.
std::uniform_int_distribution<int> distribution(-30, 30);
// generate uniformly distributed numbers from -30 to 30
int randomas;
for(int i=0; i<10; i++) {
randomas = distribution(engine); // Bless me with a number, divine masters!
std::cout << randomas << "\n"; // Witness the number all shiny and chrome!
}
return 0;
}
Try this code. It is an application of a linear congruence generator to your problem. The generator has very good properties.
#include <iostream>
int main( int argc,char** argv )
{
//the seed, an arbitrary initial value
int seed = 338;
//these constants define a linear congruence generator
int modulus = 2147483399;
int multiplicator = 40692;
int m = 52774;
int l = 3791;
//additional variables
double max = static_cast<double>( modulus );
double value;
//number of random numbers
int N = 20;
//random number generation
int lcg_value = seed;
int k1;
int z;
for( int i = 0; i < N; ++i )
{
k1 = lcg_value / m;
z = multiplicator * ( lcg_value - k1 * m ) - k1 * l;
if( z < 0 )
{
z = z + modulus;
}
lcg_value = z;
//random number, lies between 0.0 and 1.0
value = static_cast<double>( lcg_value ) / max;
//print random number, lies between -30.0 and 30.0
std::cout << ( 60.0 * value - 30.0 ) << std::endl;
}
return( 0 );
}

Rolling dice for an array

What I need this program to do is roll 36000 2d6, output the results of each value and how often it occurs in a table format. Unfortunately I'm unfamiliar with how arrays work. This is what I have so far:
int DiceArray()
{
int rollOne = 0;
int rollTwo = 0;
int countrolls = 0;
int sum = 0;
for (countrolls=1; countrolls<=36000; countrolls++)
{
rollOne = (rand() % 6) + 1;
rollTwo = (rand() % 6) + 1;
sum = rollOne+rollTwo;
}
}
So, I need an array for the dice results which I'm guessing is gonna look like result[11] because it lists 2 through 12 for the sum of the dice. Then I'm gonna have to make the array multidimensional; I'll need a second column for the results.
So, for instance, the result of two would occur we'll say 700 times. So I'd need something like outcome[2]. Is that right? And how would I get the right values for my array, anyways?
I suppose for the result array I just list them like so since they'll always be the same: {2, 3, 4,... 12}
But how do I output my sum to array?
Not sure, what you're asking, but it seems like you need a simple histogram. Like this:
void DiceArray()
{
int rollOne = 0;
int rollTwo = 0;
int sum = 0;
// This array holds histogram. hist[0] and hist[1] are always zero.
int hist[13] = { 0 };
for (int countrolls = 0; countrolls < 36000; ++countrolls)
{
rollOne = (rand() % 6) + 1;
rollTwo = (rand() % 6) + 1;
sum = rollOne+rollTwo;
hist[sum]++;
}
for (int i = 2; i <= 12; ++i)
{
std::cout << i << ": " << hist[i] << std::endl;
}
}
This function prints the following:
2: 949
3: 1974
4: 2898
5: 3987
6: 5133
7: 6088
8: 4944
9: 3976
10: 3075
11: 1991
12: 985
Something like this should work:
#include <iostream>
#include <random>
#include <array>
std::array<std::size_t, 13> DiceArray(const std::size_t count)
{
std::random_device device;
std::mt19937 engine(device());
std::uniform_int_distribution<std::size_t> distribution(1, 6);
std::array<std::size_t, 13> result = {};
for (std::size_t i = 0; i < count; ++i) {
++result[distribution(engine)+distribution(engine)];
}
return result;
}
int main(int argc, char* argv[])
{
auto result = DiceArray(36000);
for (std::size_t i = 0; i < result.size(); ++i) {
std::cout<<i<<" "<<result[i]<<std::endl;
}
return 0;
}
Your idea of result[11]; would work. You would have to zero-initialize it too.
int result[11] = {0};
Keep in mind that arrays are zero-based. So this array would cover the range of 0-10. You can work with that by subtracting off the minimum dice roll. Increment the corresponding array location for each roll in your loop:
++result[sum-2];
Accessing the value again requires subtracting the minimum dice roll:
int numTwos = result[2-2];
int numTens = result[10-2];
This is a C++11 answer. Based off this stack overflow answer
typedef std::mt19937 MyRNG; // the Mersenne Twister with a popular choice of parameters
std::vector< unsigned > DiceArray(
unsigned how_many_rolls, unsigned dice_count,
MyRNG& rng
)
{
// d6!
std::uniform_int_distribution<uint32_t> d6(1,6);
std::vector< unsigned > retval;
retval.resize( dice_count * 6+1 );
for (unsigned count = 0; count < how_many_rolls; ++count)
{
unsigned sum = 0;
for(unsigned i = 0; i < dice_count; ++i) {
sum += d6(rng);
}
retval[sum] += 1;
}
return retval;
}
And next we use it:
int main(int argc, char* argv[])
{
MyRNG rng;
uint32_t seed_val = 0; // populate somehow -- as `0` it will replicate the same sequence each time. A common trick is to grab the current time or some other source of entropy
rng.seed(seed_val); // avoid calling this more than once per experiment. It resets the RNG, if you call it again it will repeat the same sequence of numbers as the first time.
std::vector<unsigned> result = DiceArray(36000, 2, rng);
for (unsigned i = 0; i < result.size(); ++i) {
std::cout << i <<": " << result[i] << "\n";
}
}