fork download
  1. #include <utility>
  2. #include <iostream>
  3. #include <cstdlib>
  4.  
  5. template< typename Ret, typename Last >
  6. Ret random_picker_impl( size_t i, Last&& last )
  7. {
  8. return std::forward<Last>(last);
  9. }
  10.  
  11. template< typename Ret, typename First, typename Second, typename ... Rest >
  12. Ret random_picker_impl( size_t i, First&& first, Second&& second, Rest&&... rest )
  13. {
  14. if( i == 0 )
  15. {
  16. return std::forward<First>(first);
  17. }
  18. else
  19. {
  20. return random_picker_impl<Ret>( i-1, std::forward<Second>(second), std::forward<Rest>(rest)... );
  21. }
  22. }
  23.  
  24. template< typename First, typename ... Rest >
  25. First random_picker( First&& first, Rest&&... rest )
  26. {
  27. size_t index = (sizeof...(rest) + 1) * (std::rand() / double(RAND_MAX));
  28. return random_picker_impl<First>( index, std::forward<First>(first), std::forward<Rest>(rest)... );
  29. }
  30.  
  31. int main()
  32. {
  33. for( int i=0; i<20; ++i )
  34. {
  35. auto i = random_picker( 1, 2, 3 );
  36. std::cout << "chose: " << i << '\n';
  37. }
  38. }
  39.  
Success #stdin #stdout 0s 2828KB
stdin
Standard input is empty
stdout
chose: 3
chose: 2
chose: 3
chose: 3
chose: 3
chose: 1
chose: 2
chose: 3
chose: 1
chose: 2
chose: 2
chose: 2
chose: 2
chose: 2
chose: 3
chose: 3
chose: 2
chose: 3
chose: 1
chose: 2