Mercurial > Algorithms__Sedgewick
comparison algs4-c++/src/Josephus.cpp @ 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 | |
children |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:7f2a9104e947 |
---|---|
1 #include <algorithm> | |
2 #include <cstdlib> | |
3 #include <iostream> | |
4 #include <sstream> | |
5 | |
6 #include "Queue.hpp" | |
7 | |
8 void usage( char * name ) { | |
9 std::cerr << name << " skip size" << std::endl; | |
10 exit( EXIT_FAILURE ); | |
11 } | |
12 | |
13 | |
14 int read_int( char *s ) { | |
15 std::stringstream ss; | |
16 | |
17 ss.str( s ); | |
18 int tmp; | |
19 ss >> tmp; | |
20 if ( ss.fail() ) { | |
21 return -1; | |
22 } | |
23 return tmp; | |
24 } | |
25 | |
26 int main( int argc, char **argv ) { | |
27 | |
28 if ( argc != 3 ) { | |
29 usage( argv[0] ); | |
30 } | |
31 | |
32 int skip = read_int( argv[1] );; | |
33 int size = read_int( argv[2] ); | |
34 if ( skip == -1 || size == -1 ) { | |
35 usage( argv[0] ); | |
36 } | |
37 | |
38 | |
39 Queue<int> q; | |
40 | |
41 for ( int i = 0; i < size; ++i ) { | |
42 q.enqueue( i ); | |
43 } | |
44 | |
45 int i = 0; | |
46 while ( q.size() ) { | |
47 int tmp = q.dequeue(); | |
48 if ( (i+1) % skip ) | |
49 q.enqueue( tmp ); | |
50 else | |
51 std::cout << tmp << std::endl; | |
52 ++i; | |
53 } | |
54 | |
55 } |