//Sam Trivikraman CS1A Chapter 8, p. 487, #3
//
/*
******************************************************************************
Find Winning Lottery Ticket Numbers (Modification)
_______________________________________________________________________________
This program finds whether or not the provided lottery tiocket number is a valid
number in that week's set of tickets.
_______________________________________________________________________________
INPUT
the user's ticket : The ticket number that the program is seraching for (user input)
OUTPUT
valid/invalid : Whether or not the number that is inputted is in the array
_______________________________________________________________________________
*******************************************************************************
*/
//
#include <iostream>
using namespace std;
//The function which contains a binary search
int binSearch(int arr[], int num, int SIZE)
{
//Data Dictionary
int firstPos = 0; // The position of the first slot in the array
int lastPos = SIZE - 1; // The position of the last slot in the array
int middlePos; // The position of the middle slot in the array
int position = -1; // A temporary variable of the position
bool found = false; //Used to see if the value was found in the array
//Implement the binary search to find the value the user inputted
while (!found && firstPos <= lastPos)
{
middlePos = (firstPos + lastPos) / 2;
if(arr[middlePos] == num)
{
found = true;
position = middlePos;
}
else if(arr[middlePos] > num)
{
lastPos = middlePos - 1;
}
else
{
firstPos = middlePos + 1;
}
//return the position where the ticket number was found
return position;
}
return 0;
}
int main() {
//Data Dictionary
int userTicketNum; //INPUT the user's ticket number
int SIZE = 10; //CONSTANT the size of the array
//INPUT the array with ticket values
int tickets[SIZE] = {13579, 26791, 26792, 33445, 55555, 62483, 77777, 79422, 85647,93121};
int results; //INPUT contains the final results from the binary search
//Get inout from user (the user's ticket number)
cout << "Please enter your ticket number." << endl;
cin >> userTicketNum;
//Check and output whether or not the ticket number is valid
results = binSearch(tickets, userTicketNum, SIZE);
if(results == -1)
{
cout << "This ticket number is invalid" << endl;
}
else
{
cout << "This ticket number is valid" << endl;
}
return 0;
}