Friday, March 9, 2012

Algorithm study: Josephus Problem

The survivor label = (((((0+m1%2)+m2)%3+m3)%4 +m4)%5+m5)%6....

Examples:

Player : [0..5]
If m=3,
{0,1,2,3,4,5}
=>{0,1,3,4,5} - 2
=>{0,1,3,4} - 5
=>{0,1,4} - 3
=>{0,1} - 4
=>{0} - 1
  Saved=(((((0+3)%2+3)%3+3)%4+3)%5+3)%6
  = 1->1->0->3->0


Player : [0..4]


If m=3,
{0,1,2,3,4}

==>{0,1,3,4} -2

==>{0,1,3} -4

==>{1,3} - 0

==>{3} - 1

  Saved=((((0+3)%2+3)%3+3)%4+3)%5
  = 1->1->0->3


Player : [0..3]


If m=3,
{0,1,2,3}

==>{0,1,3} -2

==>{0,3} - 1
==>{0} - 3

  Saved=(((0+3)%2+3)%3+3)%4
  = 1->1->0



Player : [0..2]
If m=3,
{0,1,2}

==>{0,1} -2

==>{1} - 0
  Saved=((0+3)%2+3)%3
  = 1->1




Player : [0..1]

If m=3,
{0,1}

==>{0,1} -0

==>{1}
  Saved=(0+3)%2
  = 1


Player : [0]
No need to play!
Saved= 0

But, Why?

====================
Proof.
If there is n people, last killed guy is X, (X+m)%n will be the next guy to be killed.
If there is n people, killed guy is Y, (Y-m)% (n) will be the prev guy to be killed.
and all label after >= (Y-m)%(n) will be +1, then the last guy labelled as (Y-m)%n;

Ok, we do the process backward.
If the saviour guy is 0. add dummy 1.
(0-m)%2 will be the prev guy to be kill => (0-3)%2 =-3%1=1.
If we enforce prev guy to be zero, all other guys need to advance to position (?+m)%2,   ?={0,1}
0->1
Then we add this new prev guy as '0'
1->0
The total displacement of the surviour = 0+m%2 = 1.
Result:{0,1}

Then in next round, added a dummy 2.
(0-m)%3 will be prev guy to be killed = -3%3=0
If we let this guy to be zero, all guys need to advance to position (?+m)%3,  ?={0,1,2}
1->1
2->2 (dummy)
Then we add this new guy as '0'.
0->0;

The total displacement of the surviour = ((0+m%2)+m)%3
Result:{0,1,2}



Then in next round, added a dummy 3.
(0-m)%4 will be prev guy to be killed = -3%4=1
If we let this guy to be zero, all guys need to advance to position (?+m)%4,  ?={0,1,2,3}
0->3
2->1
3->2 (dummy)
Then we add this new guy as '0'.
1->0;

The total displacement of the surviour = (((0+m%2)+m)%3+m)%4
Result:{0,1,2,3}





Then in next round, added a dummy 4.
(0-m)%5 will be prev guy to be killed = -3%5=2
If we let this guy to be zero, all guys need to advance to position (?+m)%5,  ?={0,1,2,3,4}
0->3
1->4
3->1
4->2 (dummy)
Then we add this new guy as '0'.
2->0;

The total displacement of the surviour = ((((0+m%2)+m)%3+m)%4+m)%5
Result:{0,1,2,3,4}



Then in next round, added a dummy 5.
(0-m)%6 will be prev guy to be killed = -3%6=3
If we let this guy to be zero, all guys need to advance to position (?+m)%6,  ?={0,1,2,3,4,5}
0->3
1->4
2->5
4->1
5->2(dummy)
Then we add this new guy as '0'.
3->0;

The total displacement of the surviour = (((((0+m%2)+m)%3+m)%4 +m)%5+m)%6
Result:{0,1,2,3,4,5}

* If m is changing in each round, the equation will be:

The total displacement of the surviour = (((((0+m1%2)+m2)%3+m3)%4 +m4)%5+m5)%6.....







No comments:

Post a Comment