Wednesday, January 21, 2015

Inchworm

Problem:

TopCoder Problem Statement - Inchworm
Single Round Match 163 Round 1 - Division II, Level One

Overview:

Count the number of leaves an inchworm will stop at and eat before making it's way to the end of a branch.

Java Source:
01: public class Inchworm {
02: 
03:     public int lunchtime(int branch, int rest, int leaf) {
04: 
05:         int meals = 0;
06: 
07:         for (int p = 0; p <= branch; p += rest) {
08:             if ((p % leaf) == 0) meals++;
09:         }
10: 
11:         return meals;
12:     }
13: }
Notes:

This is a simple problem that can be solved in less time that it takes to read the description.

We'll use the variable p to keep track of the inchworm's current position. This starts at zero, and get incremented by rest until the inchworm goes beyond the end of the branch.

At each position, we'll check to see if there's a leaf there, and if so, increment the number of meals eaten. We can tell if there is a leaf at the current position by using the % operator. If position is evenly divided by leaf, then we've stopped on a leaf.

Once p is greater than branch we can return the value in meals.

No comments:

Post a Comment