- Forward


Arithmetic on a Circle
A Programming Pattern


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Motivation
Back SMYC Forward
  • Frequently:
    • Values can be increased without bound (e.g., if someone keeps giving you dollar bills)
  • In Some Cases:
    • Values don't keep increasing, they "repeat" (e.g., the hour of the day)
Review
Back SMYC Forward

Addition on the Line

NumberLine_Addition

Subtraction on the Line

NumberLine_Subtraction
Thinking About the Problem
Back SMYC Forward

Addition on the Circle

NumberCircle_Addition

Subtraction on the Circle

NumberCircle_Subtraction
The Pattern
Back SMYC Forward
  • Notation:
    • current denotes the current value
    • change denotes the change (either positive or negative)
    • cardinality denotes the number of elements in the set of values
  • The Process:
    • Use a 0-based set of consecutive integer values
    • Use integer arithmetic
    • If needed, calculate the number of times 0 is passed using:
      javaexamples/programmingpatterns/ArithmeticOnTheCircle.java (Fragment: pattern1)
       
    • Calculate the new value as:
      javaexamples/programmingpatterns/ArithmeticOnTheCircle.java (Fragment: pattern2)
       
The Example of Military Time
Back SMYC Forward
  • The Values:
    • 0 to 23
  • Start at 17:00:
    • In 12 hours it will be 29 % 24 or 5:00
    • In 93 hours it will be 110 % 24 or 14:00
Other Time/Date Examples
Back SMYC Forward
  • Minutes:
    • Go from 0 to 59
  • Days of the Week:
    • Go from 0 to 6
  • Months of the Year:
    • Go from 0 to 11 (not 1 to 12)
Other Examples: Weights and Distances
Back SMYC Forward
  • Weights:
    • Ounces go from 0 to 15 (then use pounds)
    • Pounds go from 0 to 1999 (then use tons)
  • Distances:
    • Inches go from 0 to 11 (then use feet)
    • Feet go from 0 to 2 (then use yards)
    • Yards go from 0 to 1759 (then use miles)
Other Examples: Even/Odd Numbers
Back SMYC Forward
  • Definition:
    • A number is said to be even if it can be divided by 2 with no remainder
  • An Observation:
    • If we think of all numbers as being either even or odd we can think about this as counting on a circle
  • Using %:
    • Does x % 2 equal 0?
Other Examples: Cycling through a Set
Back SMYC Forward
  • Examples:
    • Turn-taking by different players
    • Cycling through a set of colors
    • Repeating a set of instructions
  • An Observation:
    • An element in a set can be identified by its index (starting at 0)
Humor
Back SMYC Forward
/imgs
(Courtesy of xkcd)
There's Always More to Learn
Back -