Thursday, June 26, 2014

ExerciseMachine

Problem:

TopCoder Problem Statement - ExerciseMachine

Overview:

Count the number of times a second aligns with a whole number percentage of the total workout time.

Java Source:
01: /*
02: TopCoder
03: Single Round Match: 145
04: Division: 2
05: Level: 2
06: Points: 500
07: Description: http://community.topcoder.com/stat?c=problem_statement&pm=1675
08:  */
09: 
10: public class ExerciseMachine {
11: 
12:     public static final int SECS_PER_MINUTE = 60;
13:     public static final int SECS_PER_HOUR = SECS_PER_MINUTE * 60;
14: 
15:     public int getPercentages(String time) {
16: 
17:         // Split the time on the ':' character, and get it's components.
18:         String[] timeArr = time.split(":");
19:         int hours = Integer.parseInt(timeArr[0]);
20:         int minutes = Integer.parseInt(timeArr[1]);
21:         int secs = Integer.parseInt(timeArr[2]);
22: 
23:         // Calculate the total number of seconds in the workout.
24:         int totalSeconds = (hours * SECS_PER_HOUR) +
25:                 (minutes * SECS_PER_MINUTE) + secs;
26: 
27:         int counter = 0;
28: 
29:         // For each second, determine if the counter will be displayed.
30:         for (int i = 1; i < totalSeconds; i++) {
31:             if (((i * 100) % totalSeconds) == 0) {
32:                 counter++;
33:             }
34:         }
35: 
36:         return counter;
37:     }
38: }
Notes:

Lines 18-21 break apart the "time" String into it components. Line 15 then performs simple multiplication and addition to determine the total number of seconds in the workout.

With that, lines 30-34 count through each second and determine if falls on a whole number percentage of the total workout time.

No comments:

Post a Comment