In: Computer Science
In C++, Write the following program using a vector:
A common game is the lottery card. The card has numbered spots of which a certain number are selected at random. Write a Lotto() function that takes two arguments. The first should be the number of spots on a lottery card and the second should be the number of spots selected at random. The function should return a vector object that contains, in sorted order, the numbers selected at random. Use your function as follows:
Vector winners;
winners = Lotto(51,6);
This would assign to winners a vector that contains six numbers selected randomly from the range 1 through 51.
Also write a short program that lets you test the function,
Thanks for the question.
Here is the completed code for this problem.
Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change.
If you are satisfied with the solution, please rate the answer.
Thanks
===========================================================================
//Header files for I/O,vector use and for shuffling and
sort
#include <iostream>
#include<vector>
#include<algorithm>
using namespace std;
//Function prototype
vector<int> Lotto(int, int);
//Test
int main()
{
//Declare a vector
vector<int> winners;
//Call function to get winners lotto
winners = Lotto(51, 6);
//Display lotto values
for (int i = 0; i < winners.size(); i++) {
cout << winners.at(i)
<< " ";
}
cout << endl;
}
/*
Function to generate random lotto values
Take maximum of random number and count of lotto
number as parameter
Return winners lotto vector
*/
vector<int> Lotto(int maxRand, int cnt) {
//Return vector
vector<int> winners;
//Tempory vector
vector<int> temp;
//Put 1 to maxRand numbers
for (int i = 1; i <= maxRand; i++) {
temp.push_back(i);
}
//Shuffle the vector
random_shuffle(temp.begin(), temp.end());
////Put first cnt of values into winners lotto
for (int i = 0; i < cnt; i++) {
winners.push_back(temp.at(i));
}
//Sort the vector ascending order
sort(winners.begin(), winners.end());
//Return resulting vector
return winners;
}
-----------------------------------------
Please appreciate this help with an up vote !!
thank you so much : )