用Java代码解决约瑟夫问题
时间: 2023-03-07 19:34:25 浏览: 83
很高兴能为您服务!Java代码解决约瑟夫问题的一种方法是使用循环结构。可以使用for循环或while循环,比如下面的代码:// 定义数组 int arr[] = {1, 2, 3, 4, 5};
// 定义计数 int count = 2; // 定义索引 int index = -1;
// 使用while循环 while(arr.length > 0) {
index = (index + count) % arr.length;
System.out.println(arr[index]);
// 将数组索引处的元素移出数组
arr = removeTheElement(arr, index);
} // 定义方法来移出数组元素 static int[] removeTheElement(int[] arr, int index) {
// 创建一个新数组,长度为原数组长度-1
int[] anotherArray = new int[arr.length-1];
// 复制原数组中除了要移出的元素外的所有元素
for (int i = 0, k = 0; i < arr.length; i++) {
// 如果i不是要移出的元素的索引,复制到新数组
if (i == index) {
continue;
}
anotherArray[k++] = arr[i];
}
// 返回新数组
return anotherArray;
}