alfps

Demo of std::vector with Collatz sequence

Jan 8th, 2021 (edited)
219
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.26 KB | None | 0 0
  1. #include <iterator>
  2. #include <vector>
  3. using   std::size,      // From <iterator>
  4.         std::vector;    // From <vector>
  5.  
  6. template< class Collection >
  7. auto int_size( const Collection& c )
  8.     -> int
  9. { return static_cast<int>( size( c ) ); }
  10.  
  11. auto is_even( const int v )
  12.     -> bool
  13. { return v % 2 == 0; }
  14.  
  15. auto next_collatz( const int v )
  16.     -> int
  17. { return is_even( v )? v/2 : 3*v + 1; }
  18.  
  19. auto collatz( const int n )
  20.     -> vector<int>
  21. {
  22.     vector<int> result;
  23.     for( int x = n; x != 1; x = next_collatz( x ) ) {
  24.         result.push_back( x );
  25.     }
  26.     result.push_back( 1 );
  27.     return result;
  28. }
  29.  
  30. #include <iostream>
  31. using std::cout, std::endl;     // From <iostream>
  32.  
  33. auto main() -> int
  34. {
  35.     const int n = 42;
  36.     const vector<int> numbers = collatz( n );
  37.  
  38.     cout << "Collatz sequence starting with " << n << ", one per line:" << endl;
  39.     cout << endl;
  40.     for( const int v: numbers ) {
  41.         cout << "> " << v << endl;
  42.     }
  43.    
  44.     cout << endl;
  45.     cout << "The same numbers but with all on one line:" << endl;
  46.     cout << endl;
  47.     cout << "> ";
  48.     for( int i = 0; i < int_size( numbers ); ++i ) {
  49.         if( i > 0 ) {
  50.             cout << ", ";
  51.         }
  52.         cout << numbers[i];
  53.     }
  54.     cout << "." << endl;
  55. }
  56.  
Add Comment
Please, Sign In to add comment