Skip to content

Commit 06703c1

Browse files
committed
Josephus problem (Ex. 1.3.37).
1 parent af0cd72 commit 06703c1

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
2+
/*************************************************************************
3+
*
4+
* Josephus problem
5+
*
6+
* % java Ex_1_3_37 7 2
7+
* 1 3 5 0 4 2 6
8+
*
9+
*************************************************************************/
10+
11+
public class Ex_1_3_37
12+
{
13+
public static void main(String[] args)
14+
{
15+
int n = Integer.parseInt(args[0]),
16+
m = Integer.parseInt(args[1]);
17+
18+
Queue<Integer> q = new Queue<Integer>();
19+
for (int i = 0; i < n; i++)
20+
q.enqueue(new Integer(i));
21+
22+
int k = 0;
23+
while (!q.isEmpty())
24+
{
25+
int x = q.dequeue();
26+
27+
if (++k % m == 0)
28+
StdOut.print(x + " ");
29+
else
30+
q.enqueue(x);
31+
}
32+
StdOut.println();
33+
}
34+
}

0 commit comments

Comments
 (0)