Iは任意因子(どのように多くの工程)と必須方向をそれぞれ有する移動命令の認識などの問題を見ることになります。因子を省略すると、実際には1
の値を意味します。
したがって、これらは、正規表現内のパターンのように表すことができる。これが行われると
String regex = "(?<factor>\\d*)"
+ "(?<dir>[LURDX])";
、我々だけ座標で対応する 変更(dx
、dy
に方向をマッピングする必要があります)、正規表現マッチのwhileループで移動命令を処理するときに変更を適用します(係数の値を掛けた値)。X
は常に lastX
とlastY
として最後の位置を覚えているが扱える特殊なケースであること
注意。
次は私の実装です:このプログラムの
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Walk {
enum Move {
L (-1, 0)
, U (0, 1)
, R (1, 0)
, D (0, -1)
, X (0, 0)
;
private int dx;
private int dy;
private Move(int dx, int dy) {
this.dx = dx;
this.dy = dy;
}
public int getDx() {
return dx;
}
public int getDy() {
return dy;
}
}
public static void main(String[] args) {
String input = "3L5UR2DDX2LR";
String regex = "(?<factor>\\d*)"
+ "(?<dir>[LURDX])";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
int x = 0;
int y = 0;
int lastX = 0;
int lastY = 0;
while (m.find()) {
String factorString = m.group("factor");
int factor;
if (factorString.length()==0) {
factor=1;
} else {
factor=Integer.parseInt(factorString);
}
String dirString = m.group("dir");
Move move = Move.valueOf(dirString);
System.out.format("(%d,%d) last was (%d, %d) %d %s -> "
, x, y
, lastX, lastY
, factor, move.name());
if (move==Move.X) {
x = lastX;
y = lastY;
} else {
lastX = x;
lastY = y;
x += factor * move.getDx();
y += factor * move.getDy();
}
System.out.format("(%d,%d)%n", x, y);
}
System.out.format("finally arrive at (%d,%d)%n", x, y);
}
}
出力はこれです:
(0,0) last was (0, 0) 3 L -> (-3,0)
(-3,0) last was (0, 0) 5 U -> (-3,5)
(-3,5) last was (-3, 0) 1 R -> (-2,5)
(-2,5) last was (-3, 5) 2 D -> (-2,3)
(-2,3) last was (-2, 5) 1 D -> (-2,2)
(-2,2) last was (-2, 3) 1 X -> (-2,3)
(-2,3) last was (-2, 3) 2 L -> (-4,3)
(-4,3) last was (-2, 3) 1 R -> (-3,3)
finally arrive at (-3,3)