Posición del robot después de determinados movimientos.

Dado un robot que solo puede moverse en cuatro direcciones, ARRIBA (U), ABAJO (D), IZQUIERDA (L), DERECHA (R). Dada una string que consta de instrucciones para moverse. Muestra las coordenadas de un robot después de ejecutar las instrucciones. La posición inicial del robot está en el origen (0, 0).

Ejemplos: 

Input : move = "UDDLRL" 
Output : (-1, -1)

Explanation:
    Move U : (0, 0)--(0, 1)
    Move D : (0, 1)--(0, 0)
    Move D : (0, 0)--(0, -1)
    Move L : (0, -1)--(-1, -1)
    Move R : (-1, -1)--(0, -1)
    Move L : (0, -1)--(-1, -1)
    Therefore final position after the complete
    movement is: (-1, -1)

Input : move = "UDDLLRUUUDUURUDDUULLDRRRR"
Output : (2, 3)

Fuente: Experiencia de la entrevista de Goldman Sachs | conjunto 36 .

Aproximación: cuente el número de movimientos hacia arriba (U), movimientos hacia abajo (D), movimientos hacia la izquierda (L) y movimientos hacia la derecha (R) como cuenta hacia arriba, cuenta hacia abajo, cuenta hacia la izquierda y cuenta hacia la derecha, respectivamente. La coordenada x final será 
(countRight – countLeft) y la coordenada y será (countUp – countDown).

A continuación se muestra la implementación de la idea anterior:

C++

// C++ implementation to find  final position of
// robot after the complete movement
#include <bits/stdc++.h>
using namespace std;
 
// Function to find  final position of
// robot after the complete movement
void finalPosition(string move)
{
    int l = move.size();
    int countUp = 0, countDown = 0;
    int countLeft = 0, countRight = 0;
 
    // Traverse the instruction string 'move'
    for (int i = 0; i < l; i++)
    {
        // For each movement increment its
        // respective counter
        if (move[i] == 'U')
            countUp++;
        else if (move[i] == 'D')
            countDown++;
        else if (move[i] == 'L')
            countLeft++;
        else if (move[i] == 'R')
            countRight++;
    }
 
    // Required final position of robot
    cout << "Final Position: ("
         << (countRight - countLeft)
         << ", " << (countUp - countDown)
         << ")" << endl;
}
 
// Driver code
int main()
{
    string move = "UDDLLRUUUDUURUDDUULLDRRRR";
    finalPosition(move);
    return 0;
}

Java

// Java implementation to find final position
// of robot after the complete movement
 
import java.io.*;
 
class GFG {
 
    // function to find final position of
    // robot after the complete movement
    static void finalPosition(String move)
    {
 
        int l = move.length();
        int countUp = 0, countDown = 0;
        int countLeft = 0, countRight = 0;
 
        // traverse the instruction string
        // 'move'
        for (int i = 0; i < l; i++)
        {
            // for each movement increment
            // its respective counter
            if (move.charAt(i) == 'U')
                countUp++;
 
            else if (move.charAt(i) == 'D')
                countDown++;
 
            else if (move.charAt(i) == 'L')
                countLeft++;
 
            else if (move.charAt(i) == 'R')
                countRight++;
        }
 
        // required final position of robot
        System.out.println("Final Position: ("
                           + (countRight - countLeft) + ", "
                           + (countUp - countDown) + ")");
    }
 
    // Driver code
    public static void main(String[] args)
    {
        String move = "UDDLLRUUUDUURUDDUULLDRRRR";
        finalPosition(move);
    }
}
 
// This code is contributed by vt_m

Python3

# Python3 implementation to find final position
# of robot after the complete movement
 
# function to find final position of
# robot after the complete movement
 
 
def finalPosition(move):
 
    l = len(move)
    countUp, countDown = 0, 0
    countLeft, countRight = 0, 0
 
    # traverse the instruction string
    # 'move'
    for i in range(l):
 
        # for each movement increment
        # its respective counter
        if (move[i] == 'U'):
            countUp += 1
 
        elif(move[i] == 'D'):
            countDown += 1
 
        elif(move[i] == 'L'):
            countLeft += 1
 
        elif(move[i] == 'R'):
            countRight += 1
 
    # required final position of robot
    print("Final Position: (", (countRight - countLeft),
          ", ", (countUp - countDown), ")")
 
 
# Driver code
if __name__ == '__main__':
    move = "UDDLLRUUUDUURUDDUULLDRRRR"
    finalPosition(move)
 
# This code is contributed by 29AjayKumar

C#

// C# implementation to find final position
// of robot after the complete movement
using System;
 
class GFG {
 
    // function to find final position of
    // robot after the complete movement
    static void finalPosition(String move)
    {
        int l = move.Length;
        int countUp = 0, countDown = 0;
        int countLeft = 0, countRight = 0;
 
        // traverse the instruction string
        // 'move'
        for (int i = 0; i < l; i++)
        {
           // for each movement increment
            // its respective counter
            if (move[i] == 'U')
                countUp++;
 
            else if (move[i] == 'D')
                countDown++;
 
            else if (move[i] == 'L')
                countLeft++;
 
            else if (move[i] == 'R')
                countRight++;
        }
 
        // required final position of robot
        Console.WriteLine("Final Position: ("
                          + (countRight - countLeft) + ", "
                          + (countUp - countDown) + ")");
    }
 
    // Driver code
    public static void Main()
    {
        String move = "UDDLLRUUUDUURUDDUULLDRRRR";
        finalPosition(move);
    }
}
 
// This code is contributed by Sam007

PHP

<?php
// PHP implementation to find
// final position of robot after
// the complete movement
 
// function to find final position of
// robot after the complete movement
function finalPosition($move)
{
    $l = strlen($move);
    $countUp = 0;
    $countDown = 0;
    $countLeft = 0;
    $countRight = 0;
 
    // traverse the instruction
    // string 'move'
    for ($i = 0; $i < $l; $i++) {
 
        // for each movement increment its
        // respective counter
        if ($move[$i] == 'U')
            $countUp++;
        else if ($move[$i] == 'D')
            $countDown++;
        else if ($move[$i] == 'L')
            $countLeft++;
        else if ($move[$i] == 'R')
            $countRight++;
    }
 
    // required final position of robot
    echo "Final Position: ("
        . ($countRight - $countLeft)
        . ", " , ($countUp - $countDown)
        . ")" ."\n";
}
 
    // Driver Code
    $move = "UDDLLRUUUDUURUDDUULLDRRRR";
    finalPosition($move);
     
// This code is contributed by Sam007
?>

Javascript

<script>
    // Javascript implementation to find final position
    // of robot after the complete movement
     
    // function to find final position of
    // robot after the complete movement
    function finalPosition(move)
    {
        let l = move.length;
        let countUp = 0, countDown = 0;
        let countLeft = 0, countRight = 0;
  
        // traverse the instruction string
        // 'move'
        for (let i = 0; i < l; i++)
        {
           // for each movement increment
            // its respective counter
            if (move[i] == 'U')
                countUp++;
  
            else if (move[i] == 'D')
                countDown++;
  
            else if (move[i] == 'L')
                countLeft++;
  
            else if (move[i] == 'R')
                countRight++;
        }
  
        // required final position of robot
        document.write("Final Position: ("
                          + (countRight - countLeft) + ", "
                          + (countUp - countDown) + ")");
    }
     
    let move = "UDDLLRUUUDUURUDDUULLDRRRR";
      finalPosition(move);
     
</script>
Producción

Final Position: (2, 3)

Publicación traducida automáticamente

Artículo escrito por ayushjauhari14 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *