josephuswitharray.java

来自「约瑟夫问题的模拟」· Java 代码 · 共 52 行

JAVA
52
字号
/**
 *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 + =
减小字号Ctrl + -
显示快捷键?