fork download
  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <ctime>
  4. #include <cstring>
  5. #include <string>
  6. #include <algorithm>
  7. #include <iterator>
  8.  
  9. int main()
  10. {
  11. // the hard, inefficient way
  12. {
  13. enum { N = 7, M = 13 } ;
  14. char dest[N][M] = { "zero", "one", "two", "three", "four", "five", "six" } ;
  15.  
  16. std::srand( std::time(nullptr) ) ;
  17.  
  18. for( int i = N-1 ; i > 0 ; --i ) // fisher yates shuffle
  19. {
  20. const int pos = std::rand() % (i+1) ;
  21. char temp[M] ;
  22. std::strcpy( temp, dest[pos] ) ;
  23. std::strcpy( dest[pos], dest[i] ) ;
  24. std::strcpy( dest[i], temp ) ;
  25. }
  26.  
  27. for( const char* cstr : dest ) std::cout << cstr << ' ' ;
  28. std::cout << '\n' ;
  29. }
  30.  
  31. // the simple, efficient way
  32. {
  33. enum { N = 7 } ;
  34. std::string dest[N] = { "zero", "one", "two", "three", "four", "five", "six" } ;
  35.  
  36. std::srand( std::time(nullptr) ) ; // if it has not already been done
  37.  
  38. std::random_shuffle( std::begin(dest), std::end(dest) ) ;
  39.  
  40. for( const std::string& str : dest ) std::cout << str << ' ' ;
  41. std::cout << '\n' ;
  42. }
  43. }
  44.  
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
three five two four one six zero 
four zero six three two five one