**Java编程:**从A、B、C、D、E、F六位同学中挑选一些人去参加某项竞赛活动。根据竞赛规则,参赛人员须满足下列要求:
- (1)A、B两人中至少去一个人;
- (2)A、D两人不能同时去;
- (3)A、E、F三人中要选两人去;
- (4)B、C两人都去或者都不去;
- (5)C、D两人中去一个人;
- (6)若D不去,则E也不去。
选中参赛的人是( )
方法一:
int a = 1, b = 1, c = 1, d = 1, e = 1, f = 1; //参加为1,不参加为0
for (a = 0; a <= 1; a++) { //用六次for循环操作,判断是否参加
for (b = 0; b <= 1; b++) {
for (c = 0; c <= 1; c++) {
for (d = 0; d <= 1; d++) {
for (e = 0; e <= 1; e++) {
for (f = 0; f <= 1; f++) {
if ((a + b) >= 1 && (a + d) <= 1 && (a + e + f) == 2 && ((b + c) == 2 || (b + c) == 0)
&& (c + d) == 1 && (d + e) == 0) {
if (a == 1) {
System.out.println("A");
}
if (b == 1) {
System.out.println("B");
}
if (c == 1) {
System.out.println("C");
}
if (d == 1) {
System.out.println("D");
}
if (e == 1) {
System.out.println("E");
}
if (f == 1) {
System.out.println("F");
}
}
}
}
}
}
}
}
方法二:
for (int i = 0; i < 64; i++) { //通过位移运算,用一次for循环
int a = (i & 1), b = (i >> 1 & 1), c = (i >> 2 & 1), d = (i >> 3 & 1), e = (i >> 4 & 1), f = (i >> 5 & 1);
if ((a + b) >= 1 && (a + d) <= 1 && (a + e + f) == 2 && ((b + c) == 2 || (b + c) == 0) && (c + d) == 1
&& (d + e) == 0) {
if (a == 1) {
System.out.println("A");
}
if (b == 1) {
System.out.println("B");
}
if (c == 1) {
System.out.println("C");
}
if (d == 1) {
System.out.println("D");
}
if (e == 1) {
System.out.println("E");
}
if (f == 1) {
System.out.println("F");
}
}
}