- Forward


Starts and Completions
A Programming Pattern


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Motivation
Back SMYC Forward
  • Frequently:
    • We need to figure out the integer number of "tasks" that have been started and/or finished using a related measure of "work"
  • Origin of the Name:
    • In baseball it is common to track a pitchers starts and complete games
  • Other Examples:
    • Laps of a course started having run/driven a known distance
    • Pizzas purchased having eaten a known number of slices
    • Shipping containers needed for a known number of refrigerators
    • Years of college started having completed a known number of semesters
The Naive Approach to Completions
Back SMYC Forward
  • The Approach:
    • Divide (e.g., 7 miles run over a 3 mile track means 7/3 = 2 1/3 laps)
  • The Obvious Shortcoming:
    • The result isn't an integer
The Obvious Fix for Completions
Back SMYC Forward
  • The Approach:
    • Use integer division
  • Examples:
    • 0 miles run over a 3 mile track means 0/3 = 0 laps were completed
    • 1 mile run over a 3 mile track means 1/3 = 0 laps were completed
    • 7 miles run over a 3 mile track means 7/3 = 2 laps were completed
    • 9 miles run over a 3 mile track means 9/3 = 3 laps were completed
The Pattern for Completions
Back SMYC Forward
javaexamples/programmingpatterns/StartsAndCompletions.java (Fragment: completions)
 
The Naive Approach to Starts
Back SMYC Forward
  • The Approach:
    • Divide (e.g., 7 miles run over a 3 mile track means 7/3 = 2 1/3 laps)
  • The Obvious Shortcoming:
    • The result (still) isn't an integer
The Obvious Fix for Starts
Back SMYC Forward
  • The Approach:
    • Use integer division (e.g., 7 miles run over a 3 mile track means 7/3 = 2 laps were started)
  • The Shortcoming:
    • This isn't the right answer (e.g., 3 laps were started, not 2)
The 10,000 Monkeys Fix for Starts
Back SMYC Forward
  • The Approach:
    • Use integer division and add 1 (e.g., 7 miles run over a 3 mile track means 7/3 + 1 = 2 + 1 = 3 laps were started)
  • The Shortcoming:
    • This doesn't always result in the correct answer (e.g., for 6 miles, 6/3 + 1 = 2 + 1 = 3 but the correct answer is 2)
The Pattern for Starts
Back SMYC Forward
The Remainder Indicator
javaexamples/programmingpatterns/StartsAndCompletions.java (Fragment: indicator)
 
Starts
javaexamples/programmingpatterns/StartsAndCompletions.java (Fragment: starts)
 
Examples
Back SMYC Forward
  • The Charity Event:
    • A participant who runs 26 miles on a 3-mile track completed 26 / 3 or 8 laps, but started 9 (since 26 % 3 is non-zero)
  • A Baseball Game:
    • A pitcher who worked 9 of 9 innings completed 9 / 9 or 1 game, and also started 1 game (since 9 % 9 is zero)
There's Always More to Learn
Back -