鱼C论坛

 找回密码
 立即注册
查看: 2280|回复: 1

开灯问题题解出错

[复制链接]
发表于 2018-4-22 22:55:42 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
package practice;

import java.util.ArrayList;

class Box {
        boolean open;

        protected Box(boolean open) {
                this.open = open;
        }

        public boolean getStat() {
                return this.open;
        }

        public void shift() {
                this.open = !this.open;
        }
}

public class Main {

        public static void main(String[] args) {
                ArrayList<Box> al = new ArrayList<>(100);
               
                for (int i = 0; i < 100; i++) {
                        al.add(new Box(true));
                }

                for(int round=1;round<=100;round++) {
                        int j = 0;
                        while(j<100) {
                                al.get(j).shift();
                                j += round;
                        }
                }
               
                for(int i=0;i<al.size();i++) {
                        if(al.get(i).getStat()) {
                                System.out.print((i+1)+" ");
                        }
                }
               
        }

}

========================================

1 3 4 6 7 8 9 11 12 13 14 15 16 18 19 20 21 22 23 24 25 27 28 29 30 31 32 33 34 35 36 38 39 40 41 42 43 44 45 46 47 48 49 51 52 53 54 55 56 57 58 59 60 61 62 63 64 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100

==========================================
看到论坛有人用Python写了『开箱子』(即开灯问题)问题的解答,于是用Java写了一遍。结果总是不对。

正确结果:1 4 9 16 25 36 49 64 81
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2018-5-2 08:51:45 | 显示全部楼层
<code>
for (int i = 0; i < 100; i++) {
        al.add(new Box(false));  // ***************
}

for(int round=1;round<=100;round++) {
        int j = 0;
        while(j<100) {
                al.get(j).shift();
                j += round;
        }
}

for(int i=0;i<al.size();i++) {
        if(al.get(i).getStat()) {
                System.out.print(i+" ");  //  *************
        }
}
</code>
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-20 06:55

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表