fork download
  1. #include <iostream>
  2. #include <ctime>
  3. #include <cstdlib>
  4. #include <algorithm> // std::random_shuffle
  5. #include <iterator> // std::begin, std::end
  6.  
  7. int main()
  8. {
  9. const int N = 5 ;
  10. std::srand( std::time(0) ) ;
  11.  
  12. // the actual results are the five numbers at the beginning of the array
  13. int lottoresults[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 } ;
  14.  
  15. // generate 5 non-repeating numbers for lottoresults by
  16. // generating a random permutation of the elements in the array
  17. // and then picking the first five
  18. // see: http://e...content-available-to-author-only...e.com/w/cpp/algorithm/random_shuffle
  19. std::random_shuffle( std::begin(lottoresults), std::end(lottoresults) ) ;
  20.  
  21. // or: std::random_shuffle( lottoresults, lottoresults+10 ) ; // legacy C++
  22.  
  23. // print them out
  24. std::cout << "lotto winning numbers: " ;
  25. for( int i = 0 ; i < N ; ++i ) std::cout << lottoresults[i] << ' ' ;
  26. std::cout << '\n' ;
  27.  
  28. // numbers entered by the user
  29. int userinput[N] = { 5, 9, 0, 8, 1 } ; // say, as an examplew
  30. std::cout << "user input: " ;
  31. for( int i = 0 ; i < N ; ++i ) std::cout << userinput[i] << ' ' ;
  32. std::cout << '\n' ;
  33.  
  34. // check for matching numbers
  35. int cnt_matches = 0 ; // #matches
  36.  
  37. std::cout << "matching numbers: " ;
  38. for( int i = 0 ; i < N ; ++i ) // for each number entered by the user
  39. {
  40. const int user_num = userinput[i] ;
  41.  
  42. // check if the number number entered by the user is a winning number
  43. // (could use std::find() instead of writing a loop of out own)
  44. for( int j = 0 ; j < N ; ++j ) // for each winning number
  45. {
  46. if( user_num == lottoresults[j] ) // is it the same as user_num?
  47. {
  48. // yes, we got a match
  49. ++cnt_matches ;
  50. std::cout << user_num << ' ' ;
  51. }
  52. }
  53. }
  54.  
  55. std::cout << "\nnumber of matches: " << cnt_matches << '\n' ;
  56. }
  57.  
Success #stdin #stdout 0s 3296KB
stdin
Standard input is empty
stdout
lotto winning numbers: 3 2 8 4 0 
user input: 5 9 0 8 1 
matching numbers: 0 8 
number of matches: 2