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:
Stuart Reges, Marty Stepp
Chapter:
Arrays
Exercise:
Exercises
Question:12 | ISBN:9780136091813 | Edition: 2

Question

Write a method called priceIsRight that mimics the guessing rules from the game show The Price is Right. The method accepts as parameters an array of integers representing the contestants’ bids and an integer representing a correct price. The method returns the element in the bids array that is closest in value to the correct price without being larger than that price. For example, if an array called bids stores the values {200, 300, 250, 1, 950, 40}, the call of priceIsRight(bids, 280) should return 250, since 250 is the bid closest to 280 without going over 280. If all bids are larger than the correct price, your method should return -1.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Implementation of priceIsRight method:

	public static int priceIsRight(int[] bids, int rightPrice)
	{
		int closest = -1;
		
		for(int i = 0; i < bids.length; i++)
		{
			if(bids[i] <= rightPrice && bids[i] > closest)
			{
				closest = bids[i];
			}
		}
		
		return closest;
	}
0 0

Discussions

Post the discussion to improve the above solution.