From 92e7ac3d19c4c6aa73ff238d764b6a48e4a92183 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Wed, 4 Sep 2024 21:43:13 +0200 Subject: [PATCH] =?UTF-8?q?java:=20add=20=C2=AB874.=20Walking=20Robot=20Si?= =?UTF-8?q?mulation=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- java/walking-robot-simulation.java | 57 ++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 java/walking-robot-simulation.java diff --git a/java/walking-robot-simulation.java b/java/walking-robot-simulation.java new file mode 100644 index 0000000..7b0c3de --- /dev/null +++ b/java/walking-robot-simulation.java @@ -0,0 +1,57 @@ +import java.util.HashSet; + +class Solution { + private static final int TURN_LEFT = -2; + private static final int TURN_RIGHT = -1; + + private record Vec(int x, int y) { + public Vec turnLeft() { + return new Vec(-y, x); + } + + public Vec turnRight() { + return new Vec(y, -x); + } + + public Vec add(Vec other) { + return new Vec(x + other.x, y + other.y); + } + + public int distance() { + return Math.abs(x * x + y * y); + } + } + + public int robotSim(int[] commands, int[][] obstacles) { + int maxDistance = 0; + + // Process obstacles + var uniqueObstacles = new HashSet(); + for (int[] obstacle : obstacles) { + uniqueObstacles.add(new Vec(obstacle[0], obstacle[1])); + } + + var pos = new Vec(0, 0); + var direction = new Vec(0, 1); + + for (int command : commands) { + if (command == TURN_LEFT) { + direction = direction.turnLeft(); + } else if (command == TURN_RIGHT) { + direction = direction.turnRight(); + } + + for (var steps = 0; steps < command; ++steps) { + var next = pos.add(direction); + if (uniqueObstacles.contains(next)) { + break; + } + + pos = next; + maxDistance = Math.max(maxDistance, pos.distance()); + } + } + + return maxDistance; + } +}