Guys how can i make 1 variable appropriate random element from an array for example
1 2 3 4 5 6
#nclude <iostream>
usingnamespace std;
int main ()
{int Deck[52]={2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5}// this is a deck of cards
a=(random element from the array "Deck")// a= we put random element from the array
cout<<a<<endl;
Getting a random element from an array is as easy as getting a random index. Since the indices of an array range from 0 to n - 1, it's as simple as getting a random integer in said range.
#include <iostream>
#include <random>
usingnamespace std;
int main() {
// Set up the deck
constint N = 52; //size of 'deck'
int deck[N];
//TODO: fill deck...
// Create a (pseudo) random number generator (C++11 style)
random_device dev;
uniform_int_distribution<> random(0, N - 1);
// Pick then print a random element from the deck
int index = random(dev); //generate a random number
cout << deck[index] << endl; //then get the random element, and print it
return 0;
}
I want to put an elemet from the array in the index and then make different task depending on the element of the index.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
usingnamespace std;
#include <random>
#include <string>
string Deck [8]={"2s","2k","2kp","2p","3s","3k","3kp","3p"};
int main ()
{
constint n=8;
random_device dev;
uniform_int_distribution<> random(0, n - 1);
int index=random(dev); string a;
a=Deck[index];
if (a=2s) cout<<"Two of spade"<<a<<endl;//2s is two of spade
if (a=2k) cout<<"Two of diamond"<<a<<endl;//2k is two of diomond
if (a=2kp) cout<<"Two of heart "<<a<<endl;//2kp is two of heart
if (a=2p) cout<<"two of clubs"<<a<<endl;//2p is Two of clubs
else cout<<"you hit tree you loose"<<a<<endl;
return 0;
}
Should work. You just want to replace a=2s with a=="2s". Also, whenever you have a sequence of if-statements that are mutually exclusive, you optimize performance (and follow convention) by instead writing the first as if and all the following as else if, except the last which is simply else as you have it.
#include <iostream>
#include <random>
#include <string>
usingnamespace std; //always put using after the includes!
string Deck [8]={"2s","2k","2kp","2p","3s","3k","3kp","3p"};
constint n=8; //should be defined in the same scope as the array
int main ()
{
random_device dev;
uniform_int_distribution<> random(0, n - 1);
int index=random(dev); string a;
a=Deck[index];
if (a=="2s") cout<<"Two of spade"<<a<<endl;//2s is two of spade
elseif (a=="2k") cout<<"Two of diamond"<<a<<endl;//2k is two of diomond
elseif (a=="2kp") cout<<"Two of heart "<<a<<endl;//2kp is two of heart
elseif (a=="2p") cout<<"two of clubs"<<a<<endl;//2p is Two of clubs
else cout<<"you hit tree you loose"<<a<<endl;
return 0;
}
What exactly is the question, or does that answer it?