Basic C++ Programming: a word game where user memorises five random words from fifty stored words [on hold] - c++

I'm a beginner in programming and I have very basic knowledge on it. I am trying to write a program that randomly picks five words from fifty stored words. The program is then supposed to display the five words and the player has to memorise it, then clears the words, then the user will input the given words.
I know I have to use a 2D array for this but I couldn't figure out how to make the program pick out the random words.

One way to get k random strings (k=5) from a string array is by using shuffle function as follows:
#include <algorithm> // std::shuffle
#include <random> // std::default_random_engine
#include <chrono> // std::chrono::system_clock
#include <iostream>
#include <string>
#include<vector>
using namespace std;
int main()
{
vector<string> words(50);
//code which initializes words comes here
//shuffles the array
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
shuffle(words.begin(), words.end(), std::default_random_engine(seed));
//prints 5 randomally selected words
for (int i = 0; i < 5; i++)
cout << words[i] << endl;
return 0;
}
If you prefer using an array instead of a vector, change the following 2 lines:
string words[50]; //init
shuffle(begin(words), end(words), std::default_random_engine(seed)); //shuffle

Related

How do I store a random number in C++

So far, I have made a program that creates a random number using srand and rand.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(time(0));
for(int x = 1; x<25;x++) {
cout << 1+ (rand()%6);
}
}
How do I store the random number using int?
How do I store the random number using int?
As mentioned in my comment, that's simply done assigning an int variable instead of outputting it:
int myRandValue = 1+ (rand()%6);
But it sounds like you want to have the whole set of generated values available for use after generating them.
You can simply store your random numbers in a std::vector<int> like this:
std::vector<int> myRandValues;
for(int x = 1; x<25;x++) {
myRandValues.push_back(1+ (rand()%6));
}
and later access them from another loop like
for(auto randval : myRandValues) {
cout << randval << endl;
}

Generating random non repeating number array in C++

I need to generate random non repeating number array in C++, in this part of code I generate random numbers using, srand function, but some of the numbers are repeating. The main task is to generate random numbers for lottery ticket, so I need to generate numbers until golden number which is marked as int golden.
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
int main()
{
int golden = 31;
int i = 0;
int array[35];
srand((unsigned)time(0));
while(i != golden){
array[i] = (rand()%75)+1;
cout << array[i] << endl;
i++;
}
}
One strategy is to populate an array with numbers from 1 to 75, and then use std::random_shuffle() on it. You can then read the numbers from the array until you hit the golden number.

How to implement a randomized multi-response in C++

I am creating a text-based game in C++. I am wondering, however, if there is a way to randomize a a response from a set amount of responses.
Say I had a question, and the player answered incorrectly, I want the game to reply with a set response with something along the lines of "Sorry, that is invalid".
However, this does not add much personality to the game, and because the computer in this case is an AI in this particular game, when you type something wrong I am going to have the computer say 'I do not understand', 'What are you talking about', and a few other responses.
Now my question is, how can I make it randomly select a reply out of those responses I have?
Given an array of responses:
int numResponses = 10;
std::string[] responses = { // fill responses }
You can use <random>, here's setting up your random generator:
std::random_device device;
std::mt19937 generator(device());
std::uniform_int_distribution<> distributor(0, numResponses - 1);
and somewhere in your code:
if(badresponse)
{
int index = distributor(generator);
std::cout << responses[index];
}
Here's another example, using srand with the current time as the seed:
#include <cstdlib>
#include <iostream>
#include <ctime>
#include <string>
#include <vector>
using namespace std;
int main()
{
// Use c++11 initializer list for vector
vector<string> responses{"Response A", "Response B", "Response C"};
// use current time as random seed
srand(time(0));
int r = rand() % responses.size();
cout << responses[r] << endl;
}
Note: the quality of random numbers generated by 'rand' isn't as good as some other random number generators, but for such a simple example its probably OK.

Issue with Random Number Generator in a Class [duplicate]

This question already has an answer here:
srand() — why call it only once?
7 answers
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.
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()
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

ifstream random integers?

I have been trying to read in integers from a file do some operations and output them to another file. When I input the integers into an array and then print out the result of come up with random numbers. Is this something to do with ifstream that I don't understand or am I missing something obvious?
#include<iostream>
#include<fstream>
using namespace std;
int main(){
int i=0, test[100];
ifstream reader("in.txt");
while(!reader.eof()){
reader>>test[i];
i++;
}
for(int x=0; test[x]!=-1; x++)
cout<<test[x]<<endl;
return 0;
}
in.txt sample:
1 4 3 2 9 8 18 22 0
2 4 8 10 0
7 5 11 13 1 3 0
-1
the 0 and -1 are sentinels for eol and eof respectively
If there is a much simpler way of doing this I would also like to know that. I am rather new to C++ and am hating the way arrays behave vs other languages.
sizeof(test)/sizeof(test[0])
This is a compile-time computation: it will always result in 100. If you want to know how many integers you actually read, you need to keep track of that yourself (or use a container that keeps track of it for you, like a std::vector).
In addition, testing .eof() in the loop condition is incorrect and the loop will not terminate at the correct time. If an extraction fails, the fail state on the stream will be set and further extractions will fail. The correct way to do this is:
// make sure to test the array bound and test that the extraction succeeded:
while((i < 100) && (reader >> test[i]))
{
i++;
}
You can then test the state of the stream to determine whether the loop ended due to an extraction failure or because EOF was reached. If neither was the case, then i should be 100 and you'll have filled the array.
You can read this article for details as to why this is the correct way to do this.
The obvious simpler way would be to use std::vector:
#include <vector>
#include <iostream>
#include <algorithm>
#include <numeric>
#include <fstream>
#include <iterator>
int main() {
std::vector<int> test;
std::ifstream reader("in.txt");
// read the data into the vector:
std::copy(std::istream_iterator<int>(reader),
std::istream_iterator<int>(),
std::back_inserter(test));
// show the data in the vector:
std::copy(test.begin(),
test.end(),
std::ostream_iterator<int>(std::cout, "\t"));
// Just for fun, display the average of the numbers:
std::cout << "Mean = "
<< std::accumulate(test.begin(), test.end(), 0) / test.size();
return 0;
}
Use a vector rather than a array.
vector<int> test
Are there actually 0's and a -1 in the file's text? I may misunderstand you on that point, but they shouldn't literally be in the text file.
So, try this:
#include<iostream>
#include<fstream>
#include<vector>
using namespace std;
int main(){
int i=0, tmp;
vector<int> test;
ifstream reader("in.txt");
while((i < 100) && (reader >> tmp))
{
test.push_back(tmp);
i++;
}
for(int x=0; x < test.size(); x++)
cout<<test[x]<<endl;
return 0;
}
Your biggest flaw in your code is that you're using the size of the array after you set it to 100. This isn't the same as the number of integers read in, so it'll keep printing all 100 items in the array.
Edit added suggestion from other answer

Resources