SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,kenrick Mock
Chapter:
Function Basics
Exercise:
Programming Projects
Question:13 | ISBN:9780132846813 | Edition: 5

Question

You have four identical prizes to give away and a pool of 25 finalists. The final ists are assigned numbers from 1 to 25. Write a program to randomly select the numbers of 4 finalists to receive a prize. Make sure not to pick the same number twice. For example, picking finalists 3, 15, 22, and 14 would be valid but picking 3, 3, 31, and 17 would be invalid, because finalist number 3 is listed twice and 31 is not a valid finalist number.


TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

C++ program code:

//header section
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
    // Set the seed for the random number generator
    srand(static_cast<unsigned int>(time(nullptr)));

    const int numFinalists = 25;
    const int numPrizes = 4;

    // Create a vector to hold the finalist numbers
    vector<int> finalists(numFinalists);
    for (int i = 0; i < numFinalists; ++i) {
        finalists[i] = i + 1;
    }

    // Shuffle the finalist numbers randomly
    random_shuffle(finalists.begin(), finalists.end());

    // Select the winners
    vector<int> winners(numPrizes);
    for (int i = 0; i < numPrizes; ++i) {
        winners[i] = finalists[i];
    }

    // Sort the winners in ascending order
    sort(winners.begin(), winners.end());

    // Display the winners
    cout << "The winners are: ";
    for (int i = 0; i < numPrizes; ++i) {
        cout << winners[i] << " ";
    }
    cout << endl;

    return 0;
}

 

Output of the program code:

The winners are: 5 9 17 24

 

0 0

Discussions

Post the discussion to improve the above solution.