Sunday, October 16, 2011

RAPTOR SKILL - Modulus Operator - Part 2

It is suggested that you read Modulus Operator - Part 1 first.

You may not be aware of it, but you already know how to use the modulus operator. If you have ever made change (as cashiers do all the time), you are using the modulus operator. As an example, let's assume that you need to give a customer $0.93 in change. This would be your thinking, step by step:

1. Determine the number of quarters by dividing 93 by 25:
  • 93 / 25 = 3 quarters, with remainder 18 cents.
  • Hey, that 18 is the modulus! (93 mod 25 = 18).
2. Determine the number of dimes by dividing the remainder (18 from above) by 10.
  • 18 / 10 = 1 dime, with new remainder or modulus 8. (18 mod 10 = 8).
3. Determine the number of nickels by dividing the new remainder (8 from above) by 5.
  • 8 / 5 = 1 nickel, with remainder or modulus 3. (8 mod 5 = 3). This is the number of pennies.
So the correct change for $0.93 is 3 quarters, 1 dime, 1 nickel, and 3 pennies.

Challenge One: Can you write a RAPTOR program that would convert a pile of pennies (less than 100) into the equivalent amount in silver coins? The logic you need is above, but you will need to use RAPTOR's floor function to "round down" each division. In the example above, 93 / 25 works out to 3.72 and that won't do for the number of quarters. floor(93/25) gives the integer 3, which is what we want here. A floor function is common in most programming languages.

Challenge Two: What if the change to be returned is more than $1 (or $5 or $10 etc). Can you modify the Challenge One program to accomodate this?