How do I display a random element of a vector? [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last month.
Improve this question
I am trying to display "first", "among", "shift", "debug", and "craft" randomly, but it prints "shift" every time I run the project. In case this has anything to do with my problem, I'm using Xcode on macOS Ventura.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
vector <string> vec {"first", "among", "shift", "debug", "craft"};
int rand_num = rand() % vec.size();
string word;
word = vec[rand_num];
cout << word;
return 0;
}
I expected it to display "first", "among", "shift", "debug", or "craft" randomly, but it only printed "shift"

The rand() function gives a random value between 0 and RAND_MAX which will be same every time you run the program unless you seed it using the srand() function. Your code does not use srand() so rand_num is initialized with the same value every time you run the program.

rand() generates a pseudo-random sequence of numbers that will be the same given the same seed. Since you aren't explicitly initializing the seed using srand, you keep getting the same random value.
One way of initializing it so it gets a different seed in each execution is to use the current time:
// Must be called before you call rand:
srand (time(NULL));

Related

program get compile successfully but during run time it takes infinite no of values during first while loop [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 days ago.
Improve this question
The programe takes n number of test cases and each test case takes takes 4 values a,b,c,d from user and these values are used to calculate the value of max.
#include<bits/stdc++.h>
using namespace std;
void numofjok(int ar[3], int arr[4]);
int main(){
cout << "Enter the no of test cases:";
int n=0,max=0,al=0,bo=0;
int a,b,c,d;\\user input
int arr[4] ={a,b,c,d}, ar[3]= {al,bo,max};
cin>>n;\\test_cases
while(n--){
cin>>a>>b>>c>>d;\\during runtime it takes infinte no of values.
numofjok(ar,arr);
}
return 0;
}
}
I have tried the taking input using for loop but the problem presist.

OUTPUT ERROR,The problem is to find the sum 5000 digit number cpp [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
This is the code(cpp)
#include <iostream>
#include <string>
#include <numeric>//to import the accumulate function
#include <vector>
#include <algorithm>
using namespace std;
int main(){
vector<long long> vi;
string s; //this contains the long number its better not to type here
int k=0,sum=0;
for(int i=0;i<s.length();i++){
k=(int)s[i]-(int)'0';
cout<<k<<endl;
vi.push_back(k);
}
for(int i:vi){
cout<<i<<endl;
}
cout<<accumulate(vi.begin(),vi.end(),0);
}
whatever i do i get the answer 22660
i tried using without accumulate still 22660 ,i dont know why this happens
I don't understand why you are using std::vector. You could calculate the sum without using the vector:
int k=0,sum=0;
for(int i=0;i<s.length();i++)
{
k = s[i]-'0';
sum += k;
}
Note: if you are a little paranoid of the sum value fitting into an integer, you can use an unsigned integer since digits can't be negative.

Formula used for function rand() in c++

I want to know what is the formula used for generating random numbers using the rand() function in C++. At first I though it would return random numbers every time, but it does not.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
cout << "Hello world!" << endl;
srand(9865);
cout << rand() << "\n";
return 0;
}
Here I thought that, maybe because of given seed number and that unknown formula, it will be showing same number.
But, when i removed "srand(9865);" and execute several times it is showing only "41" as output. Please explain me what is all going on here.
From http://linux.die.net/man/3/rand
"If no seed value is provided, the rand() function is automatically seeded with a value of 1. ", and "..These sequences are repeatable by calling srand() with the same seed value. "
You have to seed your random function with a non static seed every time. One simple but not so accurate solution is to seed it with the clock:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
cout << "Hello world!" << endl;
srand(time(NULL));
cout << rand() << "\n";
return 0;
}
The library specifications don't dictate the formula for the random number generator (it is up to the implementation). The only things specified are that things can be controlled via srand for consistent pseudo-random generation:
In order to generate random-like numbers, srand is usually initialized to some distinctive runtime value, like the value returned by function time (declared in header <ctime>). This is distinctive enough for most trivial randomization needs.
So:
If you initialize srand with a given seed, the following rand calls will be consistent across runs.
If you initialize srand with a time-based seed, the following rand calls will almost surely be different across runs.
If you do not initialize srand, the following calls to rand will use the default initial seed.
Note that in contemporary C++, you should avoid using these ancient functions. See the answers to this question.

random numbers within a function c++

I am trying to better use and understand functions and in this case I need to figure out how to make this function in particular return 2 different random numbers.I have set up the ctime and can successfully call my function and make my variable(message) equal the random number but when I call it again and ask it to print out the newest random number they are both the same.
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int RandomNumberGen (int x);
int main()
{
srand(unsigned(time(0)));
int Ran;
int message;
message = RandomNumberGen (Ran);
cout << "Number 1 " << message << endl;
message = RandomNumberGen (Ran);
cout << "Number 2 " << message << endl;
return 0;
}
int RandomNumberGen (int Ran)
{
unsigned int RandomNum = 0;
RandomNum = rand()%8 + 4;
return RandomNum;
}
As you can see I set the function to output a random number and write it on screen and then I call the same function again and write that one on screen(write the second # on screen).Yet every time I call the function both numbers are written on the screen as the same even though I am generating a random number each time.
I know this is a simple and easy task but please let me know if what I am attempting to do is possible or do I need another separate function for the 2nd number.
My end goal is to base a lot of events and things off of one random number function so I can essentially call the function for a random number and then let it determine what happens next.
I placed in the code as you asked.I hope this is what you meant.I appreciate all the help and am very grateful for the answers.I plan to be using this more so I will be sure to get it right for you guys!
You called srand in the function RandomNumberGen, which is called multiple times. That's wrong, srand should be called only once, try put it in main instead.
Or better, instead of the C library crandom functions, use the methods in random if that's available.
Take a look at this question and particularly the answer. It should clarify some things about srand() and rand()
I quote the answer:
Seed is usually taken from the current time, which are the seconds, as in time(NULL), so if you always set the seed before taking the random number, you will get the same number as long as you call the srand/rand combo multiple times in the same second.
Basically what you should do, is call srand() only once at the beginning of your application and not in the function. Because your function will be called twice at a very short interval. Almost all the time in the same second. Generating the same starting sequence for the rand() function
you shouldn't seed the random number generator with each call, but only once. your two calls to the function probably execute so fast that the value of time(null) is still the same, and the same seed will produce the same pseudo random sequence.
(btw., you should use null or NULL, not 0 for a null pointer, and you do not use the parameter you pass to your randomnumbergen function, so you could just remove it entirely.)

Array of objects always has same random number for each item [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Started to try c++ again with a simple card game. I made a class for each card with two constructors, one with no values creates the card randomly and one that takes in values.
#include <string>
#include <iostream>
#include <stdlib.h> /* srand, rand */
#include <ctime>
#include <sstream>
class Card
{
private:
char suit;
int value;
public:
Card();
Card(char suit, int value);
void SetSuit(char suit);
void SetValue(int value);
...
std::string GetCard() ;
};
Card::Card(char suit, int value)
{
suit= toupper(suit);
this -> suit=suit;
this -> value=value;
}
Card::Card() //create random card
{
srand (time(0));
char suits [4] = {'D','S','H','C'};
int randNum = (rand() % 4);
SetSuit(suits[randNum]);
randNum = (rand() % 12)+2;
SetValue(randNum);
...
std::string Card::GetCard(){
...
return card.str();
}
If I create an array of card objects and then output it every card in the array has the same suit and value. I'm not sure how to get each card to be random the array.
The problem is with:
srand (time(0));
int randNum = (rand() % 4);
Probably on your system, time(0) returns the number of seconds this epoch. So when you call this code multiple times without a second elapsing, it gets the same value. Therefore you get the same random number every time.
You're supposed to do srand just once per program run. And if you need any serious sort of randomness then you need more entropy than just time(0). Even if you fix this, you could still execute your program several times and get the same card sequence every time, if all the runs begin within the same second.
The way that rand() typically works is to generate a long sequence of numbers which is predictable if you know the seed, but hard to predict just from a subset of the number. The srand function says "start the sequence at this point". If you start at the same point each time , you get the same random numbers each time. Further reading
Call srand(time(0)) only once when your application starts, e.g., at the main() function, not whenever any card is created.