[Algorithm question] Huawei computer test (Niu Ke) - HJ17 coordinate movement (Java)

Problem Description

Title
Develop a coordinate calculation tool, A means to move to the left, D means to move to the right, W means to move up, and S means to move down. Start moving from (0,0), read some coordinates from the input string, and output the final input result to the output file.
Input:
Legal coordinates are A (or D or W or S) + numbers (within two digits)
and the coordinates are separated by ;.
Illegal coordinate points need to be discarded. Such as AA10; A1A; %; YAD; etc.
The following is a simple example such as:
A10;S20;W10;D30;X;A1A;B10A11;;A10;
Processing process:
starting point (0,0)
A10 = (-10,0)
S20 = (-10,-20 )
W10 = (-10,-10)
D30 = (20,-10)
x = invalid
A1A = invalid
B10A11 = invalid
A null does not affect
A10 = (10,-10)
result (10, -10)
data range: every The length of the string input by the group satisfies 1≤ n ≤10000, the coordinates are guaranteed to satisfy −2 31 ≤ x,y ≤ 2 31 −1, and the number part only contains positive numbers.
Input description:
one line of string
Output description:
final coordinates, separated by commas

Test example
Input: A10;S20;W10;D30;X;A1A;B10A11;;A10;
Output: 10,-10
Input: ABC;AKL;DA1;
Output: 0,0

Solution

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    
    
    public static void main(String[] args) {
    
    
        Scanner input=new Scanner(System.in);
        String regex="[ADWS]\\d{1,2}";
        String target=input.next();
        String[] strs=target.split(";");
        int[] position=new int[2];
        for(int i=0;i<strs.length;i++){
    
    
            String temp=strs[i];
            if(temp.matches(regex)){
    
    
                char direction=temp.charAt(0);
                int distance= Integer.parseInt(temp.substring(1));
                switch(direction){
    
    
                    case 'A':position[0]-=distance;break;
                    case 'S':position[1]-=distance;break;
                    case 'D':position[0]+=distance;break;
                    case 'W':position[1]+=distance;break;
                }
            }
        }
        System.out.println(position[0]+","+position[1]);
    }
}

problem solving ideas

  • Receive the string entered by the user, and then split the string into a string array with ; as the delimiter;
  • Traverse the array, and use regular expressions (starting with ASDW, ending with 1 to 2 numbers, and the total length is 2 to 3) to judge whether the format of the subscript element is correct;
  • If the format is correct, extract the first character of the string as the direction, extract the remaining characters and convert them into int type as the distance;
  • Calculate the specific coordinate movement through the switch statement, and finally output the result.

Guess you like

Origin blog.csdn.net/m0_73845616/article/details/131912353