From bb868d8dd6fc85c0ff6b3e1ca41575dee153de63 Mon Sep 17 00:00:00 2001 From: fiatcode Date: Tue, 24 Feb 2026 10:50:39 +0700 Subject: [PATCH] REFACTOR: introduce Direction enum and extract wrapping logic --- lib/mars_rover.dart | 71 +++++++++++++++++++++++++++------------------ 1 file changed, 43 insertions(+), 28 deletions(-) diff --git a/lib/mars_rover.dart b/lib/mars_rover.dart index b06c6e1..a7d5068 100644 --- a/lib/mars_rover.dart +++ b/lib/mars_rover.dart @@ -1,57 +1,72 @@ +enum Direction { + north('N'), + east('E'), + south('S'), + west('W'); + + final String code; + const Direction(this.code); + + static Direction fromCode(String code) { + return Direction.values.firstWhere((d) => d.code == code); + } + + Direction turnLeft() { + return Direction.values[(index + 3) % 4]; + } + + Direction turnRight() { + return Direction.values[(index + 1) % 4]; + } +} + class Rover { int x; int y; - String direction; + Direction _direction; final int plateauWidth; final int plateauHeight; Rover({ required this.x, required this.y, - required this.direction, + required String direction, this.plateauWidth = 100, this.plateauHeight = 100, - }); + }) : _direction = Direction.fromCode(direction); + + String get direction => _direction.code; void turnLeft() { - const leftTurns = { - 'N': 'W', - 'W': 'S', - 'S': 'E', - 'E': 'N', - }; - direction = leftTurns[direction]!; + _direction = _direction.turnLeft(); } void turnRight() { - const rightTurns = { - 'N': 'E', - 'E': 'S', - 'S': 'W', - 'W': 'N', - }; - direction = rightTurns[direction]!; + _direction = _direction.turnRight(); } void moveForward() { - switch (direction) { - case 'N': - y = (y + 1) % (plateauHeight + 1); + switch (_direction) { + case Direction.north: + y = _wrapCoordinate(y + 1, plateauHeight); break; - case 'E': - x = (x + 1) % (plateauWidth + 1); + case Direction.east: + x = _wrapCoordinate(x + 1, plateauWidth); break; - case 'S': - y = (y - 1) % (plateauHeight + 1); - if (y < 0) y += plateauHeight + 1; + case Direction.south: + y = _wrapCoordinate(y - 1, plateauHeight); break; - case 'W': - x = (x - 1) % (plateauWidth + 1); - if (x < 0) x += plateauWidth + 1; + case Direction.west: + x = _wrapCoordinate(x - 1, plateauWidth); break; } } + int _wrapCoordinate(int value, int max) { + final wrapped = value % (max + 1); + return wrapped < 0 ? wrapped + max + 1 : wrapped; + } + void execute(String commands) { for (var i = 0; i < commands.length; i++) { final command = commands[i];