Discover the winner of a video game of contributing i sweets in every i-th relocation
Provided 2 integers X and Y representing the variety of sweets designated to gamers A and B respectively, where both the gamers delight in a video game of contributing i sweets to the challenger in every i th relocation. Beginning with gamer A, the video game continues with alternate turns till a gamer is not able to contribute the needed quantity of sweets and loses the video game, the job is to discover the winner of the video game.
Examples:
Input: X = 2, Y = 3 Output: A Description: The video game ends up in the following way:
Given that A stops working to contribute 5 sweets in the 5 th action, B wins the video game.
Input: X = 2, Y = 1 Output: B Description: The video game ends up in the following way:
Given that B stops working to offer 4 sweets in the 4 th action, A wins the video game.
Method: The concept is to resolve the issue based upon the following observation:
Action
Variety of sweets Had by A
Variety of sweets Had by B
0
X
Y
1
X– 1
Y + 1
2
X– 1 + 2 = X + 1
Y + 1– 2 = Y– 1
3
X– 2
Y + 2
4
X + 2
Y– 2
The gamer whose sweets decrease to 0 initially, will not be having enough sweets to give up the next relocation.
Count of sweets of gamer A reduces by 1 in odd relocations.
Count of sweets of gamer B reduces by 1 in even relocations.
Follow the actions listed below to resolve the issue:
Initialize 2 variables, state chanceA and chanceB, representing the variety of relocations in which the variety of sweets had by a gamer lowers to 0.
Given that count of sweets of gamer A reduces by 1 in odd relocations, chanceA = 2 * (X– 1) + 1
Given that count of sweets of gamer B reduces by 1 in even relocations, chanceB = 2 * Y
If chanceA < < chanceB, then B will be the winning gamer.
Otherwise, A will be the winning gamer.
Print the winning gamer.
Below is the execution of the above technique:
C++
#include << bits/stdc++. h>>
utilizing namespace sexually transmitted disease;
int stepscount( int a, int b)
{
int chanceA = 2 * a - 1;
int chanceB = 2 * b;
if( chanceA < < chanceB) {
cout << < < " B";
}
else if( chanceB < < chanceA) {
cout << < < " B";
}
return 0;
}
int primary()
{
int A = 2;
int B = 3;
stepscount( A, B);
return 0;
}
Time Intricacy: O( 1 ) Auxiliary Area: O( 1 )
Attention reader! Do not stop finding out now. Acquire all the essential DSA principles with the DSA Self Paced Course at a student-friendly rate and end up being market all set.