[Interview Question] [C Language] 5 athletes participated in the diving competition, and someone asked them to predict the result of the competition

topic:

Player A said: B is second and I am third;
Player B said: I am second and E is fourth;
Player C said: I am first, D is second;
Player D said: C is last, I am third;
Player E said : I am fourth, A first;
after the game, every player happened to be half right, please use programming to achieve their ranking

analysis:

Through the above, I know that each of the five players is exactly half right, but we don't know which half it is. We know that in our computer, the right is 1 and the wrong is 0. As long as the two predictions of each of our players add up to exactly 1, then the condition will be established . Next, we will write the program.

#include <stdio.h>
#include <stdlib.h>
int main()
{
    
    
	int a = 0;
	int b = 0;
	int c = 0;
	int d = 0;
	int e = 0;
	//每个选手取得的名次都是未知的,所以这种情况下,每个选手都进行一次循环,循环的范围就是可能取得名次的范围
	for (a = 1; a <= 5; a++)
	{
    
    
		for (b = 1; b <= 5; b++)
		{
    
    
			for (c = 1; c <= 5; c++)
			{
    
    
				for (d = 1; d <= 5; d++)
				{
    
    
					for (e = 1; e <= 5; e++)
					{
    
    
					//当同时满足每个人说对一半时,条件成立,跳出循环,输出结果
						if (((b == 2) + (a == 3) == 1) && 
                             ((b == 2) + (e == 4) == 1) &&
                               ((c == 1) + (d == 2) == 1) && 
                                 ((c == 5) + (d == 3) == 1) &&
                                   ((e == 4) + (a == 1) == 1))
						{
    
    
						//如果就按以上步骤去输出结果的话你会发现,输出了多种结果,如图1所示(在下面),这是因为每个名次只能有一位选手取得,这一点我们没有考虑到,如果让每位选手取得的成绩相乘(1*2*3*4*5)恰好等于120,这时候结果就唯一了						
							if (a*b*c*d*e==120)
							printf("a=%d b=%d c=%d d=%d e=%d\n", a, b, c, d, e);
						}
					}
				}
			}
		}
	}
	system("pause");
	return 0;
}

figure 1

Insert picture description here

The final result we get is

Insert picture description here
Going back to the initial prediction, a careful friend may find that C predicts that he will be the first, but it turns out to be the last one. What a big predictor!
Finally, I wish everyone a happy life and work and study first!

<<<<<<The bloggers can't see clearly. Are you sure you can leave without leaving a like? >>>>>>

Guess you like

Origin blog.csdn.net/weixin_54748281/article/details/114248900