fork download
  1. //Nathan Dominguez CSC5 Chapter 8, P.487, #3
  2. //
  3. /*******************************************************************************
  4.   *
  5.   * Determine Lottery Winner with Binary Search
  6.   * ____________________________________________________________________________
  7.   * This prorgam will prompt the user to enter this week's winning 5-digit
  8.   * numbers. The program will then use a binary search to validate the numbers
  9.   * to the list of numbers given.
  10.   * ____________________________________________________________________________
  11.   * INPUT
  12.   * lottoInput : Lotto number input
  13.   *
  14.   * OUTPUT
  15.   *
  16.   *
  17.   * CONSTANT
  18.   * tickets : The lotto number array
  19.   *
  20.   *****************************************************************************/
  21.  
  22. //PROTOTYPE BinSearchNum()
  23. bool BinSearchNum (const int tickets[], int lottoInput);
  24.  
  25. #include <iostream>
  26. #include <iomanip>
  27. using namespace std;
  28.  
  29. int main() {
  30. //CONSTANT - The lotto number array
  31. const int tickets[10] = {13579, 26791, 26792, 33445, 55555,
  32. 62483, 77777, 79422, 85647, 93121};
  33. int lottoInput; //INPUT - Lotto number input
  34.  
  35. //INPUT - enter number
  36. cout << "Please Enter Your Lotto Number: ";
  37. cin >> lottoInput;
  38. cout << lottoInput << endl;
  39.  
  40. //OUTPUT - output if winner or not
  41. if (BinSearchNum(tickets, lottoInput))
  42. {
  43. cout << "You have the winning ticket!";
  44. }
  45. else
  46. {
  47. cout << "You do not have the winning ticket! Sorry!";
  48. }
  49.  
  50. return 0;
  51. }
  52.  
  53. //FUNCTION - compare numbers to see if input choice is a winner
  54. bool BinSearchNum (const int tickets[], int lottoInput)
  55. {
  56. int size = 10;
  57. int numFirst = 0;
  58. int numLast = size - 1;
  59. int numMid;
  60. //
  61. //LOOP - sort numbers and put them in order
  62. while (numFirst <= numLast)
  63. {
  64. numMid = (numFirst + numLast) / 2;
  65. if (tickets[numMid] == lottoInput)
  66. {
  67. return true;
  68. }
  69. else if (tickets[numMid] > lottoInput)
  70. {
  71. numLast = numMid - 1;
  72. }
  73. else if (tickets[numMid] < lottoInput)
  74. {
  75. numFirst = numMid + 1;
  76. }
  77. }
  78. return false;
  79. }
Success #stdin #stdout 0s 5292KB
stdin
93121
stdout
Please Enter Your Lotto Number: 93121
You have the winning ticket!