这也算是个小游戏,一圈人围在一起,然后给一个香蕉,开始从0数到k。期间每+1就传递到下一个手中,到k那个人就出局。
基于自定义栈类实现。
package sort; public class Queue_Array implements Queue{ public static final int CAPACITY = 5; protected int capacity; protected Object[] q; protected int f = 0; protected int r = 0; public Queue_Array(int capacity) { this.capacity = capacity; this.q = new Object[capacity]; } public Queue_Array() { this(CAPACITY); } @Override public int getSize() { return (capacity - (f - r)) % capacity; } @Override public boolean isEmpty() { return r == f; } @Override public Object front() throws Exception { if (isEmpty()) { throw new Exception(); } return q[f]; } @Override public void enqueue(Object o) { // 此处是避免和r == f时候的空冲突 if (getSize() == capacity - 1) { return; } q[r] = o; r = (r + 1) % capacity; } @Override public Object dequeue() throws Exception { Object o; if (isEmpty()) { throw new Exception(); } o = q[f]; q[f] = null; f = (f + 1) % capacity; return o; } @Override public void traversal() { for (Object elem : q) { System.out.println(elem); } } public static Object Josephus(Queue q, int k) throws Exception { if (q.isEmpty()) { return null; } while (q.getSize() > 1) { q.traversal(); for (int i = 0; i < k; i++) { q.enqueue(q.dequeue()); } Object e = q.dequeue(); // System.out.println("quit --- " + e); } return q.dequeue(); } public static Queue buildQueue(Object[] a) { Queue q = new Queue_Array(); for (Object item : a) { q.enqueue(item); } return q; } public static void main(String[] args) throws Exception { String[] kid = { "hufan", "libai", "dufu", "zhangzhidong", "wangbo" }; System.out.println("final boy is ---" + Josephus(buildQueue(kid), 2)); } }
自己画了个烂图。
突然想到昨天没做题,今天快乐double。