Find The Winner By Incrementing Co Ordinates Till Euclidean Distance D In C++ - C++ Programming Tutorial
C++ Course / Miscellaneous / Find The Winner By Incrementing Co Ordinates Till Euclidean Distance D In C++

Find The Winner By Incrementing Co Ordinates Till Euclidean Distance D In C++

BLUF: Mastering Find The Winner By Incrementing Co Ordinates Till Euclidean Distance D In C++ is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Find The Winner By Incrementing Co Ordinates Till Euclidean Distance D In C++

C++ is renowned for its efficiency. Learn how Find The Winner By Incrementing Co Ordinates Till Euclidean Distance D In C++ enables low-level control and high-performance computing in the tutorial below.

Introduction:

In this C++ method, the goal is to identify a collection of successful coordinates by incrementing their values in a systematic manner until the Euclidean distance from the origin reaches or surpasses a specified maximum distance labeled as 'D'. The process commences with initial coordinates positioned at the origin (0,0) within a 2D plane and utilizes a methodical incrementation technique. The Euclidean distance, computed through the employment of the distance formula, acts as the benchmark for identifying the successful coordinates. This technique guarantees a methodical exploration of the coordinate space, incrementing the x and y values in a structured manner until the defined distance threshold is achieved. The straightforward and transparent nature of this method establishes it as an efficient approach for systematically and predictably discovering a successful point within the designated Euclidean distance.

Program:

Example

#include <iostream>
#include <cmath>
using namespace std;
// Function to calculate Euclidean distance between two points
double calculateDistance(int x1, int y1, int x2, int y2) {
    return sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2));
}
int main() {
    int x_winner, y_winner;  // Coordinates of the winning point
    double D;  // Maximum allowed distance
    // Input the maximum allowed distance
    cout << "Enter the maximum distance (D): ";
    cin >> D;
    // Loop to iterate through possible coordinates
    for (int x = 0; ; x++) {
        for (int y = 0; ; y++) {
            // Calculate Euclidean distance for the current coordinates
            double distance = calculateDistance(0, 0, x, y);
            // Check if the distance is less than or equal to D
            if (distance <= D) {
                // If yes, set the winner coordinates and break out of the loops
                x_winner = x;
                y_winner = y;
                break;
            }
        }
        // Break out of the outer loop if a winner is found
        if (calculateDistance(0, 0, x_winner, y_winner) <= D) {
            break;
        }
    }
    // Output the winner coordinates
    cout << "The winner coordinates are: (" << x_winner << ", " << y_winner << ")" << endl;
    return 0;
}

Output:

Output

Enter the maximum distance (D): 5
The winner coordinates are: (0, 0)

Explanation:

  • Introduction:

The script is designed to identify a successful pair of coordinates by iteratively increasing the x and y values until the Euclidean distance from the starting point (0,0) to those coordinates is equal to or lower than a set maximum distance, D.

  • Algorithm for Computing Euclidean Distance:

The c alculateDistance function determines the Euclidean distance between two points by applying the well-known formula: square root of the sum of the squares of the differences in coordinates, (x2 - x1)^2 + (y2 - y1)^2.

Main Logic:

  • User Input:

The process begins with requesting the user to enter the maximum permissible distance (D).

  • Iterating within one loop inside another:

The script employs nested loops to traverse potential coordinate values.

  • Calculating Distances:

For every pair of coordinates (x, y), the calculateDistance function is applied to determine the Euclidean distance from the origin (0,0).

  • Verification of Winning Condition:

If the computed distance is equal to or less than the designated maximum distance (D), those coordinates are deemed as the victor, prompting the loops to terminate.

Finally, the software displays the successful coordinates.

  • Handling Infinite Loops:

The employment of infinite loops is intentional. The outer loop persists until a successful set of coordinates is identified. Meanwhile, the inner loop iterates endlessly until a winning criteria is satisfied for a specific x value. This guarantees a methodical exploration for the victorious coordinates.

Complexity analysis:

Time Complexity:

The time complexity of the code becomes more complex because of the existence of infinite loops. The nested loops iteratively increase the x and y coordinates until a specific winning condition is satisfied, and this iteration could potentially go on indefinitely until an appropriate pair of coordinates is identified. As a result, the time complexity is most accurately characterized as infinite or unbounded.

Space Complexity:

The code's space complexity is kept to a minimum and remains constant. It avoids utilizing data structures or algorithms that would result in substantial memory consumption. The main memory usage is attributed to variables like x, y, D, distance, and the winner's xwinner and ywinner coordinates. These variables consistently occupy a fixed amount of memory irrespective of the input values. Consequently, the space complexity is classified as constant or O(1).

Approach 1: Using Linear Search with Step Increment

The method utilizes a structured linear search technique to locate coordinates within a specified maximum Euclidean distance (D).

It commences from the starting point at (0, 0) and progressively increases both the x and y coordinates by a constant step size during each iteration.

Program:

Example

#include <iostream>
#include <cmath>
using namespace std;
int main() {
    int stepSize = 1;  // Step size for coordinate increment
    double D;  // Maximum allowed distance
    // Input the maximum allowed distance
    cout << "Enter the maximum distance (D): ";
    cin >> D;
    int x = 0, y = 0;
    // Linear search with step increment
    while (true) {
        double distance = sqrt(pow(x, 2) + pow(y, 2));
        // Check if the distance is less than or equal to D
        if (distance <= D) {
            cout << "The winner coordinates are: (" << x << ", " << y << ")" << endl;
            break;
        }
        // Increment coordinates by stepSize
        x += stepSize;
        y += stepSize;
    }
    return 0;
}

Output:

Output

Enter the maximum distance (D): 5
The winner coordinates are: (0, 0)

Explanation:

  • Initialization:

The stepSize variable is defined as 1, specifying the increment value for the coordinates in every iteration.

D represents the maximum permissible distance that the software will utilize to determine the coordinates that lead to victory.

  • User Input:

The user is asked to provide the maximum allowable distance (D).

  • Initializing Coordinates:

At the beginning, x and y are set to zero, indicating the initial position (origin) on a two-dimensional coordinate plane.

  • Sequential Search:

The software initiates an endless loop (while (true)) to execute a sequential search for the successful coordinates.

  • During every cycle of the loop:

The distance from the origin (0,0) to the current point (x, y) is computed by applying the distance formula.

If the computed distance is equal to or less than the designated maximum distance (D), the existing coordinates are deemed the victor.

The successful coordinates are subsequently shown, and the loop is terminated.

  • Incrementation:

If the distance requirement is not satisfied, the coordinates (x and y) will be increased by the stepSize during every iteration.

This process of incrementing guarantees that the software methodically navigates various C++ guides within the two-dimensional space.

The end result showcases the successful coordinates, indicating the point that meets the criteria of being within the designated maximum distance from the origin.

Complexity analysis:

Time Complexity:

The time complexity of the code depends on the count of iterations within the while (true) loop.

As the loop incrementally increases both x and y by a constant stepSize until it discovers the winning coordinates, the time complexity is linear with respect to the total iterations performed.

If we represent the number of iterations as N, the computational complexity is O(N).

Space Complexity:

The code's space complexity remains constant (O(1)) as it consumes a consistent amount of memory irrespective of the input size.

The variables stepSize, D, x, y, and distance maintain a consistent memory footprint during the entire program runtime.

The storage space needed for these variables remains constant regardless of the input size.

Approach 2: Using Quadratic Search with Diagonal Movement

This method implements a structured quadratic search approach to locate coordinates within a specified maximum Euclidean distance (D).

It initiates from the starting point (0, 0) and progressively advances following a quadratic trajectory, encompassing a larger area in a diagonal manner.

Program:

Example

#include <iostream>
#include <cmath>
using namespace std;
int main() {
    int D;  // Maximum allowed distance
    // Input the maximum allowed distance
    cout << "Enter the maximum distance (D): ";
    cin >> D;
    int x = 0, y = 0;
    // Quadratic search with diagonal movement
    while (true) {
        double distance = sqrt(pow(x, 2) + pow(y, 2));
        // Check if the distance is less than or equal to D
        if (distance <= D) {
            cout << "The winner coordinates are: (" << x << ", " << y << ")" << endl;
            break;
        }
        // Increment coordinates quadratically
        x += (x >= y) ? x : y;
        y += (x >= y) ? x : y;
    }
    return 0;
}

Output:

Output

Enter the maximum distance (D): 5
The winner coordinates are: (0, 0)

Explanation:

  • User Input:

The user is asked to provide the maximum permissible distance (D).

  • Initializing Coordinates:

At the beginning, x and y are set to zero to symbolize the initial position (origin) within a two-dimensional coordinate system.

  • Algorithm for Exploring Paths Diagonally and Searching Quadratically:

The software initiates an endless loop (while (true)) to execute a quadratic search with diagonal motion for the coordinates that lead to victory.

  • During each cycle of the loop:

The distance from the origin (0,0) to the current point with coordinates (x, y) is determined by applying the Euclidean distance formula.

If the computed distance is equal to or less than the designated maximum distance (D), the current coordinates are deemed the victor.

The successful coordinates are then showcased, and the loop terminates.

  • Incrementation - Quadratic Motion:

If the distance requirement is not satisfied, the values of coordinates (x and y) increase exponentially.

The greater value between x and y is incremented by itself in every iteration.

This quadratic progression method enables the software to efficiently explore a wider region within the 2D space.

The end result showcases the successful coordinates, indicating the point that meets the criteria of being within the designated maximum distance from the origin.

Complexity analysis:

Time Complexity:

The time complexity of the code is determined by the quantity of iterations within the while (true) loop.

The loop follows a quadratic search pattern, with the iteration count dependent on the expansion of the x and y coordinates.

The time complexity can be described as quadratic, represented as O(N^2), with N representing the total number of iterations required to determine the successful coordinates.

Space Complexity:

The space efficiency is constant, represented as O(1), as the program's memory usage stays the same regardless of the input parameters.

The variables D, x, y, and distance maintain a consistent memory footprint during the entire program runtime.

The memory needed for these variables remains constant regardless of the input size.

Approach 3: Random Search with Convergence

The method employs a stochastic search technique to locate points within a specified maximum Euclidean distance (D).

It commences with arbitrary initial coordinates falling within a designated range and then progressively modifies the coordinates in a random manner.

Program:

Example

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cmath>
using namespace std;
int main() {
    int D;  // Maximum allowed distance
    // Input the maximum allowed distance
    cout << "Enter the maximum distance (D): ";
    cin >> D;
    srand(time(0));  // Seed for random number generation
    int x = rand() % (2 * D) - D;  // Random initial x within [-D, D]
    int y = rand() % (2 * D) - D;  // Random initial y within [-D, D]
    while (true) {
        double distance = sqrt(pow(x, 2) + pow(y, 2));
        // Check if the distance is less than or equal to D
        if (distance <= D) {
            cout << "The winner coordinates are: (" << x << ", " << y << ")" << endl;
            break;
        }
        // Randomly adjust coordinates
        x += rand() % (2 * D) - D;
        y += rand() % (2 * D) - D;
    }
    return 0;
}

Output:

Output

Enter the maximum distance (D): 6
The winner coordinates are: (-3, 5)

Explanation:

  • User Input:

The maximum permitted distance (D) is specified by the user.

  • Initialization with Random Values:

Random starting coordinates (x and y) within the interval [-D, D] are selected using the rand function.

The srand(time(0)) function initializes the random number generator using the current time.

  • Iteration of Random Search:

During every loop iteration, the software computes the Euclidean distance from the starting point to the existing coordinates.

If the computed distance is equal to or less than D, the current coordinates are deemed victorious, and the software stops execution.

Otherwise, it randomly modifies the coordinates to explore various regions of the 2D plane.

  • Random Adjustment:

Modifications are randomly applied to both the x and y values during each iteration.

The modifications fall within the interval [-D, D], adding variability to the exploration process.

  • Convergence:

The unpredictable modifications introduce diversity in the coordinates.

Over multiple cycles, the unpredictability gradually moves closer to points that meet the requirement of Euclidean distance.

Once the successful coordinates are located, the application displays them.

Complexity Analysis:

Time Complexity:

Determining the time complexity of this method can be difficult because of its unpredictable behavior.

Typically, the time complexity tends to be relatively elevated as it relies on the quantity of iterations required to locate coordinates within the designated Euclidean distance.

The typical time complexity can be estimated as O(N), with N representing the average amount of iterations needed.

Space Complexity:

The space complexity remains constant, represented as O(1), as the program's memory usage remains unchanged irrespective of the input values.

The variables D, x, y, distance, and the random number generation variables maintain a consistent memory footprint during the program's entire runtime.

The amount of memory needed by these variables remains constant regardless of the input size.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience