Tuesday, May 12, 2015

Swimmers

Problem:

TopCoder Problem Statement - Swimmers
Single Round Match 169 Round 1 - Division II, Level One

Overview:

Calculate the time it takes a swimmer to complete a round trip given their speed, the distance, and the current.

Java Source:
     1 public class Swimmers {
     2  
     3  public int[] getSwimTimes(int[] distances, int[] speeds, int current) {
     4 
     5         // Holds the values we're calculating and returning
     6         int[] times = new int[distances.length];
     7 
     8         // Iterate through each swimmer and calculate their time.
     9         for (int i = 0; i < distances.length; i++)  {
    10             times[i] = getTime(distances[i], speeds[i], current);
    11         }
    12 
    13         return times;
    14  }
    15 
    16     /*
    17      * Returns the time it takes the swimmer to complete the round trip
    18      * given the one-way distance, their speed, and the current.
    19      * If distance == 0, the trip takes 0 time.
    20      * If the speed is not > current, the upstream portion will be
    21      * impossible and -1 is returned.
    22      */
    23     private int getTime(int distance, int speed, int current)  {
    24 
    25         if (distance == 0) return 0;
    26 
    27         if (speed <= current) return -1;
    28 
    29         /*
    30          * Need to use floats here for the intermediate calculations
    31          * so that we don't introduce rounding errors.
    32          */
    33          
    34          // The downstream time.
    35         float time = (float) distance / (float)(speed + current);
    36 
    37         // The upstream time.
    38         time += (float) distance / (float)(speed - current);
    39 
    40         return (int) time;
    41 
    42     }
    43 }

Notes:

Just two things to be careful of here. First, be sure to check for a distance of zero, and a current equal to or greater than the swimmer's speed. Second be careful not to use ints when performing the division for the downstream and upstream times. This can lead to rounding errors. You want to keep everything as a float until the very end where you'll truncate it and return the int.

No comments:

Post a Comment