整形变量用作为数组查重
5位运动员参加了10米台跳水比赛,有人让他们预测比赛结果
A选手说:B第二,我第三;
B选手说:我第二,E第四;
C选手说:我第一,D第二;
D选手说:C最后,我第三;
E选手说:我第四,A第一;
比赛结束后,每位选手都说对了一半,请编程确定比赛的名次。
由于名次的不确定性所以ABDCE每个选手每个人的名次都遍历一遍,之后的if语句也没啥说的主要就是查重函数.定义了一个ret变量,应为在player这个数组里面存的是12345这五个数字,也就是说会把1一次向左移动1 2 3 4 5次如果没有重复,即ret将会为11111,转化为16进制为3e,如果重复了里面只的值必定不为e3;由此即可判断有误重复,即展现了整形变量用为数组的方法.而传统的方法就是用数组遍历做,只能说很传统,很慢.
#include<stdlib.h>
int xiaoyan(int*player, int n) {
int ret = 0;
for (int i = 0; i < n; i++)
{
ret |= 1 << player[i]; // 核心操作
}return ret == 0x3e;
}
int main() {
int player[5] = { 0 };
for (player[0] = 1; player[0] <= 5; player[0]++) {
for (player[1] = 1; player[1] <= 5; player[1]++) { //这段代码看似复杂
for (player[2] = 1; player[2] <= 5; player[2]++) { // 只是把每个人的名次都遍历一遍
for (player[3] = 1; player[3] <= 5; player[3]++) {
for (player[4] = 1; player[4] <= 5; player[4]++) {
if ((player[1] == 2) + (player[0] == 3) == 1 && (player[1] == 2) + (player[4] == 4) == 1 &&
(player[2] == 1) + (player[3] == 2) == 1 && (player[2] == 5) + (player[3] == 3) == 1 &&
(player[4] == 4) + (player[0] == 1) == 1 && xiaoyan(player, 5)) {
printf("运动员a名词为%d\n"
"运动员b名词为%d\n"
"运动员c名词为%d\n"
"运动员d名词为%d\n"
"运动员e名词为%d\n",
player[0], player[1],
player[2], player[3], player[4]);
system("pause");
}
}
}
}
}
}
}
具体运行的值就不在演示了,可以复制下代码自己测试.