开灯问题题解出错
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 <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>
页:
[1]