20 lucky persons

Fortunately persons

demand analysis

There are 100 individual prisoners, each person's number is 1,2, ... 100 King ready to pardon a person, pardon the rule: people first get rid of the odd location. The remainder of the new reservation queue, continue to kill people in an odd position. Until finally rest up a person, this person is the lucky ones, please summed up his number.

Analysis step

a, 100 define an array of individual memory number.
B, define an endless loop, removing people odd position.
c, the non-human odd numbered positions from the new stores to the new array to go.
d, new array repeat the process until the rest of a person that is lucky so far.

public class LuckyNumDemo {
    public static void main(String[] args) {
        // 1、定义一个数组存储100个人的编号。
        int[] peoples = new int[100];
        // 2、存入100个人的编号进去。
        for(int i = 0 ; i < peoples.length ; i++ ) {
            peoples[i] = i+1;
        }
        System.out.println("数组内容:"+ Arrays.toString(peoples)); // --Java提供的而技术,了解会用就好!
        // 3、定义一个死循环,去掉奇数位置的人。
        while(true){
            // 4、定义一个新数组存储本轮幸存者,本轮幸存者人数一定是数组长度/2
            int[] lastPeoples = new int[peoples.length / 2];
            // 5、遍历出原数组的偶数位置的人存入到新数组即可。
            int index = 0 ; // 记录索引
            for(int i = 1 ; i < peoples.length ; i+=2 ) {
                // peoples[i]
                lastPeoples[index++]  = peoples[i];
            }
            // 6、本轮幸存者
            System.out.println("本轮幸存者:"+Arrays.toString(lastPeoples));
            // 7、判断幸存者是否只有一位了,就结束循环
            if(lastPeoples.length == 1) break;
            // 8、把新的数组地址替换老数组地址从新进行一样的筛选
            peoples = lastPeoples;
        }

    }
}
Published 34 original articles · won praise 16 · views 284

Guess you like

Origin blog.csdn.net/qq_41005604/article/details/105201364