java数组实现约瑟夫
来源:互联网 发布:网络推广人员工资高吗 编辑:程序博客网 时间:2024/04/30 20:32
/** * <约瑟夫问题><br> * <规则:从第二个开始报数,一共报三下,第三个报的人出去。如果从2开始,顺序为2、3、4 。那么4就要出去> * * @author snowday88 */public class ShouPa{ private int[] shouPa; // 要报的数 private int num; public ShouPa(int size, int num) { shouPa = new int[size]; for (int i = 0; i < size; i++) { shouPa[i] = i + 1; } this.num = num; } // 获得最后一个出列的 public int getTheLast() { // 打印数组 printArray(); // 得到数组的长度 int length = shouPa.length; // 定义index 从第二个数开始 int index = 1; // 记录出列的个数 int chuLie = 0; // 当数组只剩一个数的时候就停止循环 while ((chuLie + 1) != length) { // 报数三下 for (int i = 0; i < num; i++) { // 用来循环 int cursor = index + i; // 判断是否越界了,如果越界就当作循环。 if (cursor > (length - 1)) { cursor = (index + i) % (length - 1) - 1; } // 如果当前数组元素是0则跳到下一个 while (shouPa[cursor] == 0) { index++; cursor = index + i; if (index > length - 1) { index = (index % (length - 1)) - 1; } if (cursor > (length - 1)) { cursor = (cursor) % (length - 1) - 1; } } // 出列 if (i == 2) { // 出列的数置为0 shouPa[cursor] = 0; // index为出列的下一数的位置 index = index + num; if (index > length - 1) { index = (index % (length - 1)) - 1; } // 出列数加一 chuLie++; } } } // 得到最后一个数 for (int i = 0; i < shouPa.length; i++) { if (shouPa[i] > 0) { System.out.println(); System.out.print("最后出列的数是: "); return shouPa[i]; } } return 0; } // 打印数组 public void printArray() { for (int i : shouPa) { System.out.print(i + " "); } } public static void main(String[] args) { System.out.println(new ShouPa(7, 3).getTheLast()); }}