One easy way to achieve this would be as follows:
- Start with your array of 40 questions (strings).
- Initialise a counter to the number of strings (40)
- Select a random string in the range 1 to 40 (e.g. string 10)
- Swap the selected string (10) with the last unused string (40)
- Output string 40
- decrement the number of strings (to 39)
The string you used is now outside the range (as string 40)
- Select a random string in the range 1 to 39 (e.g. string 26)
- Swap the selected string (26) with the last unused string (39)
- Output string 39
- decrement the number of string to 38
The used strings are at positions 39 and 40, outside of the range
- repeat as required, handle the condition whereby zero strings are left
It sounds more complicated than it really is, here's a function that achieves it (using a vector of strings):
string getQuestion(vector<string>& v, int& numberOfStrings)
{
// handle errors
if(numberOfStrings <= 0) return "error";
if(numberOfStrings > v.size()) return "error";
// select a random number in the range 0 - numberOfStrings-1
int next = rand() % numberOfStrings;
// decrement the number of strings
numberOfStrings--;
// swap it with the last unused string
swap(v[next], v[numberOfStrings]);
// retrieve the string
return v[numberOfStrings];
}
You populate your vector with strings, then set an integer variable equal to the number of strings, and off you go - make calls to the getQuestion() function.
Here's a demo program:
#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
#include <algorithm>
using namespace std;
string getQuestion(vector<string>& v, int& numberOfStrings)
{
if(numberOfStrings <= 0) return "Error";
if(numberOfStrings > v.size()) return "Error";
int next = rand() % numberOfStrings;
numberOfStrings--;
swap(v[next], v[numberOfStrings]);
return v[numberOfStrings];
}
int main()
{
vector<string> q;
q.push_back("One");
q.push_back("Two");
q.push_back("Three");
q.push_back("Four");
q.push_back("Five");
q.push_back("Six");
q.push_back("Seven");
q.push_back("Eight");
q.push_back("Nine");
q.push_back("Ten");
int num=q.size();
cout << getQuestion(q,num) << endl;
cout << getQuestion(q,num) << endl;
cout << getQuestion(q,num) << endl;
cout << getQuestion(q,num) << endl;
cout << getQuestion(q,num) << endl;
cout << getQuestion(q,num) << endl;
cout << getQuestion(q,num) << endl;
cout << getQuestion(q,num) << endl;
cout << getQuestion(q,num) << endl;
cout << getQuestion(q,num) << endl;
cout << getQuestion(q,num) << endl;
cout << getQuestion(q,num) << endl;
}