TopCoder problem "TurtleGraphics" used in TCCC06 Finals (Division I Level Two)

Problem Statement


Your new graphical programming language Honu contains the primitives 'L' (turn left), 'R' (turn right), 'U' (turn up), 'D' (turn down), and 'F' (move forward), to describe the actions of a trail-leaving turtle in the three-dimensional sea. Only the 'F' command actually moves the turtle, and it always moves it one unit forward. All other commands simply change the orientation of the turtle. The turn commands all are with respect to the turtle's current orientation. That is, 'R' means the turtle turns towards its current right side; 'U' means the turtle turns towards where its shell is facing.

In addition, commands can be repeated if they are immediately followed by a single digit from 1 to 9. So "F3" moves forward 3 units. There will not be adjacent digits in the command string. Digits may only follow the characters 'U', 'D', 'R', 'L', 'F', or ')'. The repeat count only applies to the immediately previous command, so "FF3" only advances four units.

Commands can also be grouped by parentheses. So "(FRFL)5" traces a zig-zag line, repeating "FRFL" five times.

Parentheses can be nested, so "((F2)2)2" moves forward 8 units.

Given a sequence of these commands, your method must return the Euclidean distance from where the turtle began to where it ended up.



Method signature:double distance(String command)
(be sure your method is public)


-Your return value must have an absolute or relative error less than 1e-9.


-command will contain between 0 and 50 characters, inclusive.
-command will consist only of the characters 'R', 'L', 'U', 'D', and 'F', '(', ')', and the digits '1'-'9'.
-command will be properly formatted according to the description above.


Returns: 1.4142135623730951
Going forward, turning right, and then going forward again leaves the turtle at a distance of the square root of two.
Returns: 0.0
The turtle traces a vertical square and ends up where he started.
Returns: 1.7320508075688772
Returns: 2.0

Problem url:

Problem stats url:




PabloGilberto , Olexiy , Jan_Kuipers , Andrew_Lazarev

Problem categories:

Brute Force, Geometry