Friday, June 3, 2011

Joseph Problem...

Joseph likes taking part in programming contests. His favorite problem is, of course, Joseph's problem. It is stated as follows.


Problem : There are n persons numbered from 0 to n - 1 standing in a circle. The person number k, counting from the person number 0, is executed. After that the person number k of the remaining persons is executed, counting from the person after the last executed one. The process continues until only one person is left. This person is a survivor. The problem is, given n and k detect the survivor's number in the original circle.
  Solution: You can easily write a recursive write:
 Example:(20, 3) = 4+17-1 =20 Find J (20, 3), assume that you have to know the J (19, 3) = 17, then remove the number 3 20 people who left with 19 people, and this 19 starting from the number 4, 17 the last person is left, so J (20, 3) = 4 +17-1 = 20
 
public class JoshephProblem {
    public static void main(String[] args) {
        System.out.println(">>> " + J(5, 3));
    }

    public static int J(int n, int m) {
        if (n == 2) {
            if (m % 2 == 1)
                return 2;
            else
                return 1;
        } else {
            int temp = (J(n - 1, m) + m) % n;
            if (temp == 0)
                return n;
            else
                return temp;
        }
    }
}

No comments:

Post a Comment