I'm working on a project currently that involves taking randomly generated numbers, putting them into an array, then using that array throughout the entire program. It's basically supposed to be a number version of wordle. What I'm stuck on right now it trying to make the function to array connection work, and I don't know what I'm doing wrong.
I'm in a beginner course for programming, so I'm probably making a lot of dumb mistakes. The purpose of the function is to generate 5 random numbers between 0 and 9. The I'm supposed to take those numbers and stick then into an array. Then the array needs to be saved so it can be used for a game.
#include <iostream>
#include <random>
#include <chrono>
#include <array>
using namespace std;
//using std::array;
int getRandomDigit() {
std::random_device randomSource;
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
std::default_random_engine engine(seed);
std::uniform_int_distribution<int> uniformDist(0,9);
//for (int i = 0; i < 5; i++) {
int digits[5] = {getRandomDigit(),getRandomDigit(),getRandomDigit(),getRandomDigit(),getRandomDigit()};
return digits[5];
}
//for (int i = 0; i < 5; i++) {
//int randArray[5] = {getRandomDigit(),getRandomDigit(),getRandomDigit(),getRandomDigit(),getRandomDigit()};
int main()
{
//for (int i = 0; i < 5; i++) {
//int randArray[5] = {getRandomDigit(),getRandomDigit(),getRandomDigit(),getRandomDigit(),getRandomDigit()};
//}
cout << digits[1] <<endl;
return 0;
}
This is what I have so far. I compile it, and it gives me an error of "'digits' was not declared in this scope". I'm honestly very lost on how to make this work. The random number generator was given to us by our instructor
Your compilation error "'digits' was not declared in this scope" is because you are using digits in your main function without declaring it first. You only have it declared in getRandomDigit(). Declare your array in main() instead and set it to values that are returned from getRandomDigit(). Additionally, you can not return an array in C++ directly. Focus on returning a single int from the getRandomDigit() function and populating your array in main().
Related
#include <iostream>
#include <vector>
#include <ctime>
#include <string>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main()
{
string Alphabets[26] = { "Hey","How","Are","you","Doing","Today","My","Name",
"Is","John","Its","Great","to","finally","meet","you","today",
"wow","summer","was","long","school","has","started","now"};
string RandString[20];
srand(time(NULL));
for (int k = 0; k < 20; k++) {
int temp = rand() % 26;
RandString[k] = Alphabets[temp];
}
for (string RandomString : RandString ) {
cout << RandomString << endl;
}
for (int i = 20; i >= 0; i--) {
cout << RandString[i] << endl;
}
}
I'm having trouble understanding my code to an extent. Right now, my code is randomly generating 20 strings into an array. I have one range for loop that shows the strings that we're picked by the random string generator. But my issue comes with the last part of the code and that is to reverse it. I believe what I'm doing wrong is that I'm trying to reverse strings that haven't been randomly generated yet. Therefore, I believe that's why nothing appears, and if this is the case, I have forgotten how to take an array that's been fully populated and then assign it to a different variable which 'I think also has to be an array'. I know this is a silly question but could someone tell me why, if this array isn't being populated when called outside of the for loop why is the ranged for loop able to then print it out?
This question already has an answer here:
C++ srand() function in loop [duplicate]
(1 answer)
Closed 1 year ago.
I'm trying to populate a simple array in C++ using a function that generates random numbers within a given range. For whatever reason it is giving me the same random number for each element. I think the problem has something to do with where I'm seeding the random variable.
Any ideas?
#include <iostream> // for user input/output
#include <cstdlib> // for rand/srand functions
#include <ctime> // for time usage
using namespace std;
const int SIZE = 10;
const int MIN = 100;
const int MAX = 200;
int main()
{
int Arr[SIZE];
for (int i = 0; i < SIZE; i++){
Arr[i] = rng(MIN, MAX);
}
for (int j = 0; j < SIZE; j++){
cout << Arr[j] << " ";
}
}
int rng(int lo, int hi){
static bool variable;
variable = false;
if (variable == false){
srand(time(0));
variable = true;
}
return rand() % (hi - lo + 1) + lo;
}
As mentioned in comments, you need to call srand(time(0)); only once, just call it at start of main().
The reason is that rand() itself is just a pseudorandom generator (a simple LFSR in a lot of cases) based on its starting seed. if you reseed algorithm with same number, you will get similar sequence of number from it, so your array will be filled with similar set of numbers.
In addition, it is better to use C++ random generator.
Before I start I must notice that I am a begginer in C++.
I have a code (see below), In this code I have two arrays with 10 random numbers but In tab_A numbers are the same like in tab_B - I don't know how to solve this. Also I don't know how to merge/add/sum these two arrays in new array tab_C and print result.
#include <iostream>
#include <cstdio>
#include <time.h>
#include <cstdlib>
using namespace std;
int gen() {
return rand() % 11;
}
int main()
{
int tab_A[10];
cout<<"TABLICA A DEBUG"<<endl;
srand (time(NULL));
for (int i=0; i<10; i++)
{
tab_A[i] = gen();
cout<<tab_A[i]<<endl;
}
int tab_B[10];
cout<<"TABLICA B DEBUG"<<endl;
srand (time(NULL));
for (int i=0; i<10; i++)
{
tab_B[i] = gen();
cout<<tab_B[i]<<endl;
}
int tab_C[10];
cout<<"TABLICA C DEBUG"<<endl;
int sumAB=0;
sumAB=tab_A[10]+tab_B[10];
tab_C[10]=sumAB;
cout<<tab_C[10]<<endl;
return 0;
}
In the code, you have called srand twice with the same seed. Hence, the numbers that will be randomly generated will be the same. If you want to generate random numbers it is advisable to set seed only once.
Also, there seems to be an issue in the code. C++ has 0-indexing. Hence, the lines
sumAB=tab_A[10]+tab_B[10];
tab_C[10]=sumAB;
cout<<tab_C[10]<<endl;
will give errors.
As the size of tab_C is 10 so the index of the last element would be 9.
I am trying to create different objects, each with an array of structures of numbers with random values. After compiling I am getting the same sequence of number inside the arrays of every object.
Is there a way to create different objects with unique sequences of numbers inside the arrays?
#include <iostream>
#include <time.h>
#include <stdlib.h>
using namespace std;
struct storeTwoValue
{
int x;
int y;
};
class practice{
public:
storeTwoValue storageArray[10];
void valueGenerator()
{ srand(time(NULL));
for (int i = 0; i< 10; i++)
{
storageArray[i].x = rand()%10 +1;
storageArray[i].y = rand()%7 + 1;
}
}
void print()
{
cout<<"x"<<" "<<"y"<<endl;
for (int i = 0; i< 10; i++)
{
cout<<storageArray[i].x <<" ";
cout<< storageArray[i].y << endl;
}
cout<<endl;
}
};
int main()
{
for(int i=0; i<3; i++)
{ practice A;
A.valueGenerator();
A.print();
}
return 0;
}
Move the srand() call into main, i.e. execute it only once.
The way you are using it, it gets called in too short order for each object, at least if you create/initialise them all at start. I.e. they get all initialised while time(0) gives identical seeds, which means that the pseudo random number generator is basically reset (starting same sequence from same initial value).
To verify this, you can (before moving the srand call) extend your loop. If it takes enough time, so that time(0) reliably has different values, you will see groups of objects with same values within the groups, but different across groups.
Calling srand() should be done exactly once, calling it more often does not improve randomness.
This question already has answers here:
srand() — why call it only once?
(7 answers)
Closed 9 years ago.
First off this could be complete rubbish as I am new to C++ classes and have never used a random number generator before. But this is my attempt. It generates a random number between the values that I want, thats fine. but when outputting them via an array, all the random values are the same.
RandomNumberGenerator.h
#pragma once
#include <iostream>
#include <cstdlib>
#include <ctime>
class RandomNumber
{
public:
void randomNumber();
int actualRandomNumber;
};
RandomNumberGenerator.cpp
#include "RandomNumberGenerator.h"
void RandomNumber::randomNumber()
{
srand (time(NULL));
actualRandomNumber = rand() % 66 + 1;
}
Game.h
#include "RandomNumberGenerator.h"
class Game
{
private:
int myNumbers[6];
public:
void createGame();
};
Game.cpp
#include "Game.h"
void Game::createGame()
{
RandomNumber create;
std::cout << "Welcome to your game!" << std::endl;
for (int i = 0; i < 6; i++)
{
create.randomNumber();
myNumbers[i] = create.actualRandomNumber;
}
for (int i = 0; i < 6; i++)
{
std::cout << myNumbers[i] << std::endl;
}
}
main
#include "Game.h"
#include "RandomNumberGenerator.h"
int main()
{
Game play;
play.createGame();
system("pause");
return 0;
}
Thanks in advance for anyones time.
Everytime you call srand(time(NULL)), you set the starting point of your sequence depending on a value that only changes once a second, thus your number only changes once a second (independend from number of calls).
So only calling srand() once will fix your code.
Notice, that both rand() and your actualRandomNumber = rand() % 66 + 1; are really bad regarding their "randomness" (why).
Use the C++ STL instead, consider the example on the bottom of the page (you want the uniform int distribution).
Edit: Typo and link to OneC++ Talk
The pseudo random number generator starts with a certain number and then generates a sequence based on the first number.
When the first number is the same the output sequence will be the same.
To generate different sequences each time you launch your program, the idea is to use the starting time of your program relatively to a specific date in miliseconds.
So the Error in your code is that you placed the srand(time(NULL)) in the function randomnumber() and it's being called in the loop. Because the CPU is so fast the time(NULL) (the first number in the sequence) will return the same value in miliseconds. Thus your having the same sequence.
To solve this place srand(time(NULL)) in main()