In: Computer Science
Use C language
Level 2
n (n is odd) people sitting around a round table playing a game. In this situation, everyone has a left neighbour and a right neighbour. At the beginning, each of them is holding a whiteboard with an integer number. Now, they are playing a game consisting of several rounds. In each round, everyone will first look at the numbers of his/her left neighbour and right neighbour, then calculate the average of the two numbers, replace the number on his/her whiteboard with the average finally. The game terminates when any one has to write a non-integer number on his/her whiteboard.
Given the number of people, the number of passed rounds and the integer numbers on their whiteboards at this moment, you are asked the integer numbers on their whiteboards at the very beginning. The number of rounds increases by 1 when changing the number on the whiteboard and new numbers are all integers.
Input the number of people n and the number of rounds t on the first line. On the next line are numbers on their whiteboards after t rounds.
Output the integer numbers on their whiteboards at the very beginning.
3 2
3 1 2
6 -2 2
If you like the solution please give it a thumbs up. And if you have any query please let me know in the comments.
Solution :-
C code :-
#include <stdio.h>
int main() {
int n = 3;
int arr[3] = {6,-2,2};
int level = 0; // initially level 0
while(1)
{
int allInteger = 1; // if all the values in array are integers
int temp[n]; // temp array to store average values
for(int i=0;i<n;i++)
{
int left = arr[((i-1)+n)%n]; // find value of left element
int right = arr[(i+1)%n]; // find value of right element
if((left+right)%2 == 1) // if sum of both is odd then avg will be non-integer
{
allInteger = 0;
break;
}
temp[i] = (left+right)/2;
}
// if non-integer terminate
if(allInteger == 0)
{
break;
}
// if all are integers then copy average value to original array
for(int i=0;i<n;i++)
arr[i] = temp[i];
// increment level
level = level+1;
}
printf("level = %d \n", level);
for(int i=0;i<n;i++)
printf("%d ", arr[i]);
}
Sample Output :-
level = 2 3 1 2