Mercurial > Algorithms__Sedgewick
changeset 17:10e1ce04c4f1
The Josephus program, ex 1.3.37
author | Eris Caffee <discordia@eldalin.com> |
---|---|
date | Fri, 19 Jun 2015 18:18:47 -0500 |
parents | eb159ea69f33 |
children | a149b424b4e2 60fb85712482 |
files | algs4-c++/src/Josephus.cpp |
diffstat | 1 files changed, 55 insertions(+), 0 deletions(-) [+] |
line diff
1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/algs4-c++/src/Josephus.cpp Fri Jun 19 18:18:47 2015 -0500 1.3 @@ -0,0 +1,55 @@ 1.4 +#include <algorithm> 1.5 +#include <cstdlib> 1.6 +#include <iostream> 1.7 +#include <sstream> 1.8 + 1.9 +#include "Queue.hpp" 1.10 + 1.11 +void usage( char * name ) { 1.12 + std::cerr << name << " skip size" << std::endl; 1.13 + exit( EXIT_FAILURE ); 1.14 + } 1.15 + 1.16 + 1.17 +int read_int( char *s ) { 1.18 + std::stringstream ss; 1.19 + 1.20 + ss.str( s ); 1.21 + int tmp; 1.22 + ss >> tmp; 1.23 + if ( ss.fail() ) { 1.24 + return -1; 1.25 + } 1.26 + return tmp; 1.27 + } 1.28 + 1.29 +int main( int argc, char **argv ) { 1.30 + 1.31 + if ( argc != 3 ) { 1.32 + usage( argv[0] ); 1.33 + } 1.34 + 1.35 + int skip = read_int( argv[1] );; 1.36 + int size = read_int( argv[2] ); 1.37 + if ( skip == -1 || size == -1 ) { 1.38 + usage( argv[0] ); 1.39 + } 1.40 + 1.41 + 1.42 + Queue<int> q; 1.43 + 1.44 + for ( int i = 0; i < size; ++i ) { 1.45 + q.enqueue( i ); 1.46 + } 1.47 + 1.48 + int i = 0; 1.49 + while ( q.size() ) { 1.50 + int tmp = q.dequeue(); 1.51 + if ( (i+1) % skip ) 1.52 + q.enqueue( tmp ); 1.53 + else 1.54 + std::cout << tmp << std::endl; 1.55 + ++i; 1.56 + } 1.57 + 1.58 + }