约瑟夫环 java 对象数组实现

import java.util.Scanner;

class Person{
    String name;
    int seqno;
    Person(String _name, int _seqno){
        name = _name;
        seqno = _seqno;
    }
}

public class JosephCircle {
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner scanner = new Scanner(System.in);
        System.out.println("------请输入总人数------");  
        int totalNum = scanner.nextInt();
        System.out.println("----请输入报数的大小----");  
        int outNum = scanner.nextInt();
        String[] name = new String[totalNum];
        
        System.out.println("----请输入"+totalNum+"个人的名字,以回车键结束----");
        for(int i = 0; i < totalNum+1; i++){
            String str = scanner.nextLine();
            if(i == 0)
                continue;
            name[i-1] = str;
        }
        scanner.close();
        JoseCiCircle(totalNum, outNum, name);  
    }

    private static void JoseCiCircle(int totalNum, int outNum, String[] name) {
        Person[] ps = new Person[totalNum];
        
        for(int i = 0; i < totalNum; i++){
            Person p = new Person(name[i], i+1);
            ps[i] = p;
        }
        int pre = 0;
        int currentNum = totalNum;
        while(currentNum > 0){
            pre = (pre + outNum - 1) % currentNum;
            
            System.out.println("----"+ps[pre].seqno + "号已出局----");
             ps = adjust(ps, pre, currentNum);
            currentNum--;
            }
        }

    private static Person[] adjust(Person[] ps, int pre, int currentNum) {
        // TODO Auto-generated method stub
        for(int i = pre; i < currentNum - 1; i++){
            ps[i] = ps[i+1];
        }
        return ps;
    }
}

 

这是用数组实现约瑟夫环,用到了对象数组Person[],Person类中自带了编号。

欢迎评论,互相交流!

转载请注明出处!谢谢

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。