I am trying to have my program randomly select a number from the numbers 4, 5, and 8. These numbers come from the length of 3 strings I have. You can see the code below. Can anyone please assist me in going about this?
1 2 3 4 5 6 7 8 9
int lengthR;
int lengthP;
int lengthS;
string Rock = "Rock";
string Paper = "Paper";
string Scisors = "Scissors";
lengthR = Rock.size();
lengthP = Paper.size();
lengthS = Scisors.size();
It can be done by making a random select function, which generates a random number from one to three and then, according to the generated number returns a specified number.
#include<iostream>
#include<random> //for rand() and srand()
#include<time.h> //for time()
usingnamespace std;
int random_select(){ //function for randomized selection
int n = 1+rand()%3; //here, it gives to n a random value from 1 to 3
if (n==1){
return 4;
}
elseif(n==2){
return 5;
}
elseif(n==3){
return 8;
}
}
int main(){
srand(time(NULL));
string rock = "rock";
string paper = "paper";
string scissors = "scissors";
int rock_l = rock.size();
int paper_l = rock.size();
int scissors_l = scissors.size();
int checker = random_select();
if (chcker == rock_l){
//do whatever
}
elseif(checker == paper_l){
//do whatever
}
else{
//do whatever
}
}
@Thomas1965
I believe your code is quite impractical. I've made a code to see the probability of using simple rand() without limits and I've ran it 10-20 times.
1 2 3 4 5 6 7 8 9 10 11
int main(){
srand(time(NULL));
int counter = 0;
for (int i=0; i<100000; i++){
int k = rand();
if (k==4 || k==5 || k==8){
counter++;
}
}
cout<<counter;
}
Counter takes numbers in the range from 1 to 20. So, you're while loop can run 100000 times before it finds 4 or 5 or 8.
when writing some code for a beginner my primary aim is that it is easy to understand.
To test I ran the function 100 times and the results appeared instantaneous on the screen.
I prefer Chervil's solution which is compact and efficient, but for a beginner it is not so obvious how it works.