Number of steps required to reach point (x,y) from (0,0) using zig-zag way
Given a coordinate (x, y). The task is to calculate the number of steps required to reach point (x, y) from (0, 0) using zig-zag way and you cannot travel in straight line for more than 1 unit. Also, start moving along Y axis.
For example we can reach the Point denoted by red color in the respective ways as shown in the below diagram:
Examples:
Input: x = 4, y = 4
Output: 8
In the diagram above the line is passing
using 8 steps.
Input: x = 4, y = 3
Output: 9
Input: x = 2, y = 1
Output: 5
Approach: By sketching a small diagram we can see the two cases:
- Case 1: If x is less than y then answer will always be x + y + 2*((y-x)/2).
- Case 2: If x is greater than equal to y then answer will always be x + y + 2*(((x-y)+1)/2).
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countSteps( int x, int y)
{
if (x < y) {
return x + y + 2 * ((y - x) / 2);
}
else {
return x + y + 2 * (((x - y) + 1) / 2);
}
}
int main()
{
int x = 4, y = 3;
cout << countSteps(x, y);
return 0;
}
|
Java
class GfG
{
static int countSteps( int x, int y)
{
if (x < y)
{
return x + y + 2 * ((y - x) / 2 );
}
else
{
return x + y + 2 * (((x - y) + 1 ) / 2 );
}
}
public static void main(String[] args)
{
int x = 4 , y = 3 ;
System.out.println(countSteps(x, y));
}
}
|
Python3
def countSteps(x, y):
if x < y:
return x + y + 2 * ((y - x) / / 2 )
else :
return x + y + 2 * (((x - y) + 1 ) / / 2 )
if __name__ = = "__main__" :
x, y = 4 , 3
print (countSteps(x, y))
|
C#
using System;
class GfG
{
static int countSteps( int x, int y)
{
if (x < y)
{
return x + y + 2 * ((y - x) / 2);
}
else
{
return x + y + 2 * (((x - y) + 1) / 2);
}
}
public static void Main()
{
int x = 4, y = 3;
Console.WriteLine(countSteps(x, y));
}
}
|
PHP
<?php
function countSteps( $x , $y )
{
if ( $x < $y )
{
return $x + $y + 2 *
(( $y - $x ) / 2);
}
else
{
return $x + $y + 2 *
((( $x - $y ) + 1) / 2);
}
}
$x = 4; $y = 3;
echo (countSteps( $x , $y ));
?>
|
Javascript
<script>
function countSteps(x, y)
{
if (x < y) {
return x + y + 2 * parseInt((y - x) / 2);
}
else {
return x + y + 2 * parseInt(((x - y) + 1) / 2);
}
}
var x = 4, y = 3;
document.write(countSteps(x, y));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Last Updated :
22 Jun, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...