座標移動

題目描述

開發一個座標計算工具, A表示向左移動,D表示向右移動,W表示向上移動,S表示向下移動。
從(0,0)點開始移動,從輸入字符串裏面讀取一些座標,並將最終輸入結果輸出到輸出文件裏面。
輸入:

合法座標爲A(或者D或者W或者S) + 數字(兩位之內)
座標之間以;分隔。
非法座標點須要進行丟棄。如AA10;  A1A;  $%$;  YAD; 等。
下面是一個簡單的例子 如:
A10;S20;W10;D30;X;A1A;B10A11;;A10;

處理過程:
起點(0,0)
+   A10   =  (-10,0)
+   S20   =  (-10,-20)
+   W10  =  (-10,-10)
+   D30  =  (20,-10)
+   x   =  無效
+   A1A   =  無效
+   B10A11   =  無效
+  一個空 不影響
+   A10  =  (10,-10)

結果 (10, -10)

輸入描述

一行字符串

輸出描述

最終座標,以,分隔

輸入例子

A10;S20;W10;D30;X;A1A;B10A11;;A10;

輸出例子

10,-10

算法實現

import java.util.Scanner;

/**
 *
 * All Rights Reserved !!!
 */
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
//        Scanner scanner = new Scanner(Main.class.getClassLoader().getResourceAsStream("data.txt"));
        while (scanner.hasNext()) {
            String input = scanner.nextLine();
            System.out.println(move(input));
        }

        scanner.close();
    }

    private static String move(String input) {
        String[] steps = input.split(";");
        int[] result = new int[2];

        for (String step : steps) {
            move(step, result);
        }


        return result[0] + "," + result[1];
    }

    private static void move(String input, int[] result) {

        if (input.matches("(A|D|W|S)[0-9]{1,2}")) {
            // 方向
            char direction = input.charAt(0);
            // 步數
            int step = Integer.parseInt(input.substring(1));
            switch (direction) {
                case 'A':
                    result[0] -= step;
                    break;
                case 'D':
                    result[0] += step;
                    break;
                case 'W':
                    result[1] += step;
                    break;
                case 'S':
                    result[1] -= step;
                    break;
            }
        }
    }
}
相關文章
相關標籤/搜索