📄 josephuswitharray.java
字号:
/**
*Jeffrey Zhou
*061251245
*Software Institute
*NJU
*/
/**
*Write a program to simulate The Josephus Problem.(With array)
*/
package josephus;
import javax.swing.JOptionPane;
public class JosephusWithArray {
//The main class for test
public static void main (String[] args) {
//Get the number of people
String numOfPeopleString = JOptionPane.showInputDialog(null, "Please enter the number of people:",
"Input of Josephus Problem",JOptionPane.QUESTION_MESSAGE);
int numOfPeopleInt = Integer.parseInt(numOfPeopleString);
//Get the number of gap
String numOfGapString = JOptionPane.showInputDialog(null, "Please enter the gap to count:",
"Input of Josephus Problem",JOptionPane.QUESTION_MESSAGE);
int numOfGapInt = Integer.parseInt(numOfGapString);
//Invoke the josephus method and display the result
josephusMethod(numOfPeopleInt,numOfGapInt);
}
//The Josephus method
public static void josephusMethod (int numOfPeople, int numOfGap) {
int[] arrayOfPeople = new int[numOfPeople + 1];
//Loop for count to out
for(int i=1;i<=numOfPeople;i++)
//initialize the array
arrayOfPeople[i] = i;
int b = numOfPeople, c = 1;
for(int i=1;i<=numOfPeople;i++){
if((c + numOfGap-1)%b != 0)
c = (c + numOfGap-1)%b;
else
c = b;
System.out.print(arrayOfPeople[c] + " ");
for(int j=c;j<b;j++)
arrayOfPeople[j] = arrayOfPeople[j+1];
b--;
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -