Summary:
Joseph problem is a famous problem: N personal circle, the number of starting from the first report, the first of M will be killed, the last remaining one, the rest will be killed. For example, N = 6, M = 5, the order being killed is: 5,4,6,2,3,1.
analysis:
(1) for each person since the dead and alive only two states, each can be labeled with boolean state array, can represent dead true, it indicates to false live.
(2) at the start of each person is alive, so the array initial value assigned to all false.
(3) simulated killing process until all people have been killed so far.
1. loops through the list form
n represents the number of individuals, m M represents the number of people:
public int josephRing1 ( int n-, int m) { the LinkedList <Integer> = List new new the LinkedList <> (); for ( int I = 0; I <n-; I ++ ) { List.add (I); } int BT = 0 ; the while (list.size ()>. 1 ) { //// deleted as human m-1 (starting from 0) // analytical see the previous BT = (m BT + -. 1)% list.size (); List .remove (BT); } return list.size () == List.get. 1 (0): -1? ; }
2. Use recurrence formula
n represents the number of individuals, m M represents the number of people:
public int josephRing2 ( int n-, int m) { IF (m <n-||. 1 <. 1 ) return -1 ; int Last = 0 ; // i represents There are currently several people for ( int i = 2; i <= n-; I ++ ) Last = (m + Last)% I; return Last; }
3. Using a recursive call
public int josephRing3(int n, int m) { if (n == 1) return n; return (josephRing3(n - 1, m) + m) % n + 1; }
4. The simplest implementation, a line of code to achieve
public int josephRing(int n, int m) { return n == 1 ? n : (josephRing(n - 1, m) + m) % n + 1; }