不能算初学Java,Josephus问题简化版

   Java里面已经有众多的集合类可以用了,亏我初学时还像C那样,自己去写了两个类实现链表,ORZ。。。记录一下,以便跟上一篇对比一下,这算是进步历程吗?似乎太慢了,看来得少打点机。汗。。。

package com.thomas;
import java.util.ArrayList;
import java.util.Scanner;
public class Josephus2 {
    public static void main(String[] args) {
        //if the run command arguments are less than two
        //give out a warning and quit
        if(args.length < 2)
        {
            System.out.println("Too few arguments. Need two!\n"
                    + "The first one is where to start counting.\n"
                    + "The second one is the gap between two counting");
            return;
        }
        ArrayList list = new ArrayList();
        System.out.print("decide the length: ");
        Scanner scan = new Scanner(System.in);
        //initial the elements from standard input
        int length = scan.nextInt();
        for(int i = 0; i < length; ++i)
        {
            System.out.print("The number " + i + " element is:");
            list.add(scan.nextInt());
        }
        //print the original result
        System.out.println("original result:");
        for(int i = 0; i < list.size(); ++i)
            System.out.print(list.get(i) + "\t");
        System.out.println();
        //get the command arguments
        int start = Integer.parseInt(args[0]);
        int gap = Integer.parseInt(args[1]);
        int [] result = new int [list.size()];
        Josephus2.solution(result, list, start, gap);
        //print the final result
        System.out.println("final result: ");
        for(int i = 0; i < result.length; ++i)
            System.out.print(result[i] + "\t");
        System.out.println();
        scan.close();
    }
    /**
     *
     * @param result: the array used to restore the final result
     * @param list:    The link list used to restore the original elements
     * @param start: where to start the counting
     * @param gap:    the number of people that are skipped between two counting
     */
    public static void solution(int [] result, ArrayList list, int start, int gap)
    {
        int location = 0;
        int num = list.size();
        for(int i = 0; i < num; ++i)
        {
            location = (start + gap - 1) % list.size();
            result[i] = (int) list.get(location);
            list.remove(location);
            start = location;
        }
    }
}

你可能感兴趣的:(java,ArrayList,Josephu)