TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
十个小孩围成一圈分糖果,老师分给第一个小孩10块,第二小孩2块,第三个小孩8块,第四个小孩22块,第五个小孩16
块,第六个小孩4块,第七个小孩10块,第八个小孩6块,第九个小孩14块,第十个小孩20块。然后所有的小孩同时将自已手中的
糖分一半给右边的小孩,糖块数为奇数的人可向老师要一块,问经过这样几次调整后大家手中的糖的块数都一样多?每人各有多
少块糖?
- public class Test75{
- public static void main(String args[]){
- new Test75().shareSweet75();
- }
- /**
- * 75.10个小孩分糖果
- */
- 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();
- }
- }
- 结果:
复制代码 C:at>java Test75
Times:0 10 2 8 22 16 4 10 6 14 20
Times:1 15 6 5 15 19 10 7 8 10 17
Times:2 17 11 6 11 18 15 9 8 9 14
Times:3 16 15 9 9 15 17 13 9 9 12
Times:4 14 16 13 10 13 17 16 12 10 11
Times:5 13 15 15 12 12 16 17 14 11 11
Times:6 13 15 16 14 12 14 17 16 13 12
Times:7 13 15 16 15 13 13 16 17 15 13
Times:8 14 15 16 16 15 14 15 17 17 15
Times:9 15 15 16 16 16 15 15 17 18 17
Times:10 17 16 16 16 16 16 16 17 18 18
Times:11 18 17 16 16 16 16 16 17 18 18
Times:12 18 18 17 16 16 16 16 17 18 18
Times:13 18 18 18 17 16 16 16 17 18 18
Times:14 18 18 18 18 17 16 16 17 18 18
Times:15 18 18 18 18 18 17 16 17 18 18
Times:16 18 18 18 18 18 18 17 17 18 18
Times:17 18 18 18 18 18 18 18 18 18 18
源码下载:http://file.javaxxz.com/2014/11/23/000605109.zip |
|