Military Tanks

Здравейте на всички, видях че няма тема за тази задача от Mock Exam 4 - Military Tanks и реших да споделя моето решение, което е доста елементарно, първо пробвах да реша задачата с пресмятане на frequency на всеки от елементите, но не успях да изляза с решение по този начин, после изцяло смених подхода. Надявам се да е полезно :slightly_smiling_face:

import java.util.Arrays;
import java.util.Scanner;
import java.util.ArrayList;

public class MilitaryTanks {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.next();
char[] arr = input.toCharArray();

    StringBuilder right = new StringBuilder();
    int r= 0;
    StringBuilder left = new StringBuilder();
    int l = 0;
    StringBuilder up = new StringBuilder();
    int u = 0;
    StringBuilder down = new StringBuilder();
    int d = 0;

    for (int i = 0; i < input.length(); i++) {
        arr[i] = input.charAt(i);
        if (arr[i] == 'R') {
            right.append(arr[i]);
            r = right.length();
        } else if (arr[i] == 'L') {
            left.append(arr[i]);
            l = left.length();
        } else if (arr[i] == 'U') {
            up.append(arr[i]);
            u= up.length();
        }else if(arr[i] == 'D'){
            down.append(arr[i]);
            d=down.length();

        }
    }

    int positionX = r-l;
    int positionY = u-d;
    System.out.println("(" +positionX+ ", " + positionY + ")");
}

}

1 Like

Scanner sc = new Scanner(System.in);
String input = sc.next();

    int x = 0;
    int y = 0;

    for (int i = 0; i < input.length(); i++) {
        
       switch (input.charAt(i)) {
            case 'R' :
                x++;
                break;
            case 'U' :
                y++;
                break;
            case 'L' :
                x--;
                break;
            case 'D' :
                y--;
                break;
        }
    }
    System.out.println("(" + x + ", " + y + ")");
2 Likes

Thank you so much !
There is in Python code
string_builder = input()
string_builder_right =
R = 0
string_builder_left =
L = 0
string_builder_up =
U = 0
string_builder_down =
D = 0
for el in string_builder:
if el == ‘R’:
string_builder_right.append(el)
R = len(string_builder_right)
elif el == ‘L’:
string_builder_left.append(el)
L = len(string_builder_left)
elif el == ‘U’:
string_builder_up.append(el)
U = len(string_builder_up)
elif el == ‘D’:
string_builder_down.append(el)
D = len(string_builder_down)

positionX = R - L
positionY = U - D
print(f’({positionX}, {positionY})')