Sunday, August 30, 2015

ClockWalk

Problem:

TopCoder Problem Statement - ClockWalk
Single Round Match 175 Round 1 - Division II, Level One

Overview:

Determine the ending time after a series of jumps forward and back.

Java Source:
     1 public class ClockWalk {
     2
     3  public int finalPosition(String flips) {
     4   int result = 0;
     5
     6   for (int i = 0; i < flips.length(); i++)  {
     7    if (flips.charAt(i) == 'h')  result += i + 1;
     8    else result -= i + 1;
     9   }
    10
    11   result %= 12;
    12
    13   return (result <= 0) ? (result + 12) : result;
    14  }
    15
    16 }
Notes:

For each character in flips we want to either move forward or backward around a clock face. The number of steps is 1 plus the index of the current character. 1 for position 0, 2 for position 1, etc.

If the character is 'h', we use += to advance forward. Otherwise -= to move backward.

After all the moves have been made, we mod the result by 12, and if the result is less than or equal to 0, we add 12.

No comments:

Post a Comment