Java 解决约瑟夫问题的示例代码

以下是使用 Java 解决约瑟夫问题的示例代码:

import java.util.ArrayList;
import java.util.List;

public class JosephusProblem {
    
    
    public static void main(String[] args) {
    
    
        int numPeople = 7; // 总人数
        int countInterval = 3; // 数到几的人出列

        List<Integer> people = new ArrayList<>();
        for (int i = 1; i <= numPeople; i++) {
    
    
            people.add(i);
        }

        int currentIndex = 0;
        while (people.size() > 1) {
    
    
            currentIndex = (currentIndex + countInterval - 1) % people.size();
            people.remove(currentIndex);
        }

        System.out.println("最后剩下的人是:" + people.get(0));
    }
}

这段代码解决了经典的约瑟夫问题。首先,我们创建一个列表 people 用于表示总人数,并通过循环将数字 1 到 numPeople 添加进去。然后,我们使用一个循环来模拟数数的过程。

在每次循环中,通过计算 (currentIndex + countInterval - 1) % people.size() 来确定下一个要出列的人的索引位置。然后,我们将该人从列表中移除。循环将继续,直到只剩下一人为止。

最后,我们打印出剩下的唯一一人的编号,即为约瑟夫问题的解答。你可以根据需要自行调整代码中的总人数和数到几的人出列。

猜你喜欢

转载自blog.csdn.net/wzxue1984/article/details/132984137