一个游戏的JAVA源码,大家一起讨论下!
package com.pip.util.test; import java.util.ArrayList; import java.util.List; class Test { static int ok = 1; /** * 有100个人围成一个圈(编号0-99),从第0号的人开始从1报数, 凡报到3的倍数的人离开圈子,然后再数下去, 直到最后只剩一个人为止, * 问此人原来的位置是多少号? */ private void test1() { int total = 100; int start = 1; List list = new ArrayList(); for (int i = 1; i <= 100; i++) { Person person = new Person(i, "Y"); list.add(person); } List tt = list; while (true) { tt = doGame(tt); System.out.println("count num:" + Test.ok); int tem = tt.size(); if (tem <= 2) break; } for (int i = 0; i < tt.size(); i++) { Person person = (Person) tt.get(i); int index = person.getIndex(); System.out.println(index + 1 + "是最后一个留下的人!"); } } private List doGame(List list) { List lists = new ArrayList(); int size = list.size(); int num = size; if (size == 2) { } for (int i = 0; i < size; i++) { Person person = (Person) list.get(i); if ("Y".equals(person.getStatus())) { int count = i + 1; if (Test.ok % 3 == 0) { person.setStatus("N"); num--; System.out.println("index:" + person.getIndex() + "\t 离开"); } else { lists.add(person); } } if (num == 1) { break; } Test.ok++; } return lists; } class Person { int index; String status; public Person() { } public Person(int index, String status) { this.index = index; this.status = status; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } } public static void main(String args[]) { System.out.println("start...."); Test test = new Test(); test.test1(); System.out.println("end!"); } public static void main1(String[] args) { int count = 100; // 剩余人数 int leavings = count; int[] all = new int[count]; // index人物编号,counter报数 int index = 0, counter = 0; while (true) { // 人物对应的值为-1表示出局 if (all[index] != -1) { all[index] = index + 1; counter++; } if (counter % 3 == 0) { if (--leavings == 1) { System.out.println(index); break; } all[index] = -1; } index++; if (index == count - 1) { index = 0; } } } }