标签:分糖果
十个小孩围成一圈分糖果,老师分给第一个小孩10块,第二小孩2块,第三个小孩8块,第四个小孩22块,第五个小孩16块,第六个小孩4块,第七个小孩10块,第八个小孩6块,第九个小孩14块,第十个小孩20块。然后所有的小孩同时将自已手中的糖分一半给右边的小孩,糖块数为奇数的人可向老师要一块,问经过这样几次调整后大家手中的糖的块数都一样多?每人各有多少块糖?
public class test2 { public void shareSweet75() { int[] boy = { 10, 2, 8, 22, 16, 4, 10, 6, 14, 20 }; int[] copy = new int[boy.length]; int times = 0; System.out.print("Times:" + times + " "); show(boy); while (allTheSame(boy) == false) {// 不相等 System.arraycopy(boy, 0, copy, 0, 10); for (int i = 0; i <= 9; i++) { boy[i] = copy[(i - 1 + 10) % 10] / 2 + copy[i] / 2; } times++; System.out.print("Times:" + times + " "); show(boy); for (int i = 0; i <= 9; i++) { if (boy[i] % 2 == 1) boy[i]++; } if (times > 100) break; }// while System.out.print("Times:" + ++times + " "); show(boy); } /** * 判断是否全相等,只有一个数返回 */ public boolean allTheSame(int[] a) { if (a == null || a.length == 0) { return false; } if (a.length == 1) return true; for (int i = 1; i < a.length; i++) { if (a[0] != a[i]) { return false; } } return true; } /** * 显示数组的值 */ public void show(int[] a) { if (a == null) System.out.println("Array = null"); for (int i = 0; i < a.length; i++) { System.out.print(a[i] + " "); } System.out.println(); } public static void main(String[] args) { // TODO Auto-generated method stub new test2().shareSweet75(); } }
运行结果为
本文出自 “闲庭信步、” 博客,请务必保留此出处http://macxiao.blog.51cto.com/9606147/1586788
标签:分糖果
原文地址:http://macxiao.blog.51cto.com/9606147/1586788