ジョセフス問題は反復解法


歴史
ジョセフスの問題は、理論的なゲームフラビウスヨセフスの名前を付けた後、彼は洞窟で40人の兵士と一緒に閉じ込められた歴史家だった.代わりにローマの兵士に降伏の彼らは多くの描画によって自殺にコミットを選択します.ヨセフス州は、神の恵みや運によって、彼らは生きて残って、ローマの兵士に降伏する唯一の2つだった.
問題
実行されるのを待っている列に立っている人々の' n '数があります、そして、1だけが生きているままです.問題は2つの値を持ち、一つは人々の数であり、他の方法は実行される.


Input : N = 5, K = 2
Output : 3
Firstly, the Person at position 2 is out, 
then position 0 goes out, then position 4
Finally, the Person at position 1 is out. 
So the Person at position 3 survives.

Input : 7 4
Output : 2

解決策
Time Complexity: theta(2^n)
Space Complexity: theta(1)

import java.util.Scanner;
import java.util.Arrays;

public class Jos {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int k = sc.nextInt();
        int temp = n;
        int count = 0;
        boolean[] arr = new boolean[n];
        Arrays.fill(arr, true);
        for (int i = 0; i < temp; i++) {
            if (n != 1) {
                if (arr[i])
                    count++;
                if (count == k) {
                    arr[i] = false;
                    count = 0;
                    n -= 1;
                }
                if (i == temp - 1) {
                    i = -1;
                }

            } else {
                break;
            }
        }
        for (int j = 0; j < arr.length; j++) {
            if (arr[j])
                System.out.println(j);
        }
    }
}