The Price Is Right

 

Modules - Structured Programming 2

 

Teacher’s Notes:

========================================================================

This is a good exercise that requires a little more thinking behind the logical structures than most simple problems.

 

Assignment:

========================================================================

 

The Price is Right

In a famous game show, a number of contestants must guess the price of a given product. The person with the closest guess without going over is considered to be the winner. Any guess that is over the actual price is not counted. The contestants must make a guess g such that g > 0.

In this problem, you will be given the actual price of the item p where p > 0, and a number n of contestants that are guessing the price. Following this, you will be given the names and guesses for each contestant. Following this, your program must output the name of the winning guesser.

You may assume that someone will always win the guess (The situation where everyone guesses higher than the price or everyone ties does not occur). Error traps and prompts are not required.

Sample Input 1

500

3

Gavin

501

Mariam

490

Nedj

450

Sample Output 1

Mariam

Explanation of Sample Output 1

Gavin's guess was higher than the actual price of $500 so his guess is not counted. Mariam's guess was only $1 away from the actual price and Nedj's guess was $50 away. Thus, Mariam has the closest guess.

 

Solution (C++):

========================================================================

 
#include <iostream>
 
using namespace std;
 
int main() {
 
int price, numberOfGuessers, currentGuess = 0, closestGuess = 0;
string currentName, closestName;
 
cin >> price;
cin >> numberOfGuessers;
 
for(int x = 0; x < numberOfGuessers; x++){
    cin >> currentName;
    cin >> currentGuess;
    if(currentGuess <= price && price - currentGuess < price - closestGuess){
      closestGuess = currentGuess;
      closestName = currentName;
    }
    
  }
  cout << closestName << endl;
  
}