Find the winner by incrementing co-ordinates till Euclidean distance <= D
Last Updated :
20 Feb, 2024
A and B play a game and A starts first. Consider a Token placed at (0,0) in a 2D plane, a player can perform the below moves on the token:
- increase x coordinate of the token to x+K
- increase y coordinate of the token to y+K
After each move the euclidean distance of the token from origin should be smaller than equal to D. i.e. x2 + y2 <= D2 . The player who is unable to make a move looses.
Examples:
Input: D=2, K=1
Output: B
Explanation: From the initial position (0,0), player A has the option to move to either (0,1) or (1,0) From there, player B can move to any of the following coordinates: (0,2), (2,0) or (1,1). Now A cannot make any move. Therefore, B wins.
Input: D=5, K=2
Output: A
Explanation: From the initial position (0,0), player A has the option to move to either (0,2) or (2,0). From there, player B can move to any of the following coordinates: (0,4), (2,2) or (4,0). Player A can only move to the coordinates: (4,2) or (2,4). Now B can not make any move. Therefore, A wins.
Approach: To solve the problem, follow the idea below:
The idea is to find the numbers of steps taken by both the players mathematically. Both players, A and B, move a distance of K. Since player A starts the game, the optimal strategy for player B is to maintain the trajectory on the line (y=x). This means that if player A moves K distance along the x-axis, player B will move K distance along the y-axis, and vice versa. This movement forms the hypotenuse of a triangle, with value √ 2 K.
The total distance to be covered is D, so the total number of hypotenuses formed will be D/√ 2 K. Since each hypotenuse is contributed by both players, the total number of steps becomes 2*D/√ 2 K = √ (2*(D2/K2)).
If the total number of steps is odd, player A wins. If it's even, player B wins.
Step-by-step algorithm:
- Calculate the square of the maximum distance D that can be moved from the origin, divide it by the square of the step size K, and multiply the result by 2.
- Take the square root of the result which is the maximum number of steps that can be taken by both players combined.
- If the maximum number of steps is odd, player A wins. If it is even, player B wins.
Below is the implementation of the above algorithm:
C++
// C++ Code
#include <bits/stdc++.h>
using namespace std;
// Function to determine the winner of the game
string game(long long D, long long K)
{
// Calculate the square of the maximum distance D,
// divide it by the square of the step size K,
// and multiply the result by 2.
long long x = 2 * ((D * D) / (K * K));
// Take the square root of the result
// If the maximum number of steps is odd,
// player A wins else player B wins.
return (int(sqrt(x)) & 1 ? "A" : "B");
}
// Driver code
int main()
{
// Test Case 1
long long D = 2, K = 1;
cout << game(D, K) << endl;
// Test Case 2
D = 5, K = 2;
cout << game(D, K) << endl;
return 0;
}
Java
// Java code
import java.util.*;
public class GFG {
// Function to determine the winner of the game
public static String game(long D, long K)
{
// Calculate the square of the maximum distance D,
// divide it by the square of the step size K,
// and multiply the result by 2.
long x = 2 * ((D * D) / (K * K));
// Take the square root of the result
// If the maximum number of steps is odd,
// player A wins else player B wins.
return ((int)Math.sqrt(x) & 1) == 1 ? "A" : "B";
}
// Driver code
public static void main(String[] args)
{
// Test Case 1
long D = 2, K = 1;
System.out.println(game(D, K));
// Test Case 2
D = 5;
K = 2;
System.out.println(game(D, K));
}
}
Python3
# Python code
import math
# Function to determine the winner of the game
def game(D, K):
# Calculate the square of the maximum distance D,
# divide it by the square of the step size K,
# and multiply the result by 2.
x = 2 * ((D * D) / (K * K))
# Take the square root of the result
# If the maximum number of steps is odd,
# player A wins else player B wins.
return 'A' if int(math.sqrt(x)) & 1 else 'B'
# Driver code
if __name__ == "__main__":
# Test Case 1
D = 2
K = 1
print(game(D, K))
# Test Case 2
D = 5
K = 2
print(game(D, K))
C#
using System;
class Program
{
// Function to determine the winner of the game
static string Game(long D, long K)
{
// Calculate the square of the maximum distance D,
// divide it by the square of the step size K,
// and multiply the result by 2.
long x = 2 * ((D * D) / (K * K));
// Take the square root of the result
// If the integer part of the square root is odd,
// player A wins; else, player B wins.
return ((long)Math.Sqrt(x) % 2 == 1) ? "A" : "B";
}
// Driver code
static void Main()
{
// Test Case 1
long D1 = 2, K1 = 1;
Console.WriteLine(Game(D1, K1));
// Test Case 2
long D2 = 5, K2 = 2;
Console.WriteLine(Game(D2, K2));
}
}
// This code is contributed by akshitaguprzj3
JavaScript
// Function to determine the winner of the game
function game(D, K) {
// Calculate the square of the maximum distance D,
// divide it by the square of the step size K,
// and multiply the result by 2.
const x = 2 * Math.floor((D * D) / (K * K));
// Take the square root of the result
// If the maximum number of steps is odd,
// player A wins else player B wins.
return Math.sqrt(x) % 2 === 1 ? "A" : "B";
}
// Test Case 1
let D = 2, K = 1;
console.log(game(D, K));
// Test Case 2
D = 5, K = 2;
console.log(game(D, K));
Time Complexity: O(1)
Auxiliary Space: O(1)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read