Menu
Coddy logo textTech

Recap - Parking Meter

Part of the Object Oriented Programming section of Coddy's R journey. Lesson 21 of 57.

challenge icon

Challenge

Medium

Complete the factory make_meter(rate) in Meter.R. rate is the number of minutes one cent buys; lock it with lockBinding() inside the factory so it can never change. The meter keeps the minutes left and the cents paid as private variables and returns four functions:

  • insert(cents) accepts only 10, 20, 50 or 100 and otherwise stops with coin not accepted; each coin adds cents * rate minutes and counts towards the amount paid.
  • wait(minutes) lets time pass: the minutes left go down, but never below 0. A negative wait stops with time cannot go back.
  • status() returns 12 min left, or expired when no time is left.
  • paid() returns the cents paid.

Use call. = FALSE. The supplied code reads the rate, then lines coin 20 or wait 5, and prints the status or error: and the message after each. Finally it prints the amount paid and tries to change rate inside the factory's environment.

Your code goes in Meter.R. main.R holds the supplied input/output code and cannot be edited.

Try it yourself

source("Meter.R")

# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
meter <- make_meter(as.numeric(input[1]))
for (line in input[-1]) {
  p <- strsplit(line, " ")[[1]]
  msg <- tryCatch({
    if (p[1] == "coin") meter$insert(as.numeric(p[2]))
    if (p[1] == "wait") meter$wait(as.numeric(p[2]))
    meter$status()
  }, error = function(e) paste("error:", conditionMessage(e)))
  cat(line, ": ", msg, "\n", sep = "")
}
cat("paid: ", meter$paid(), " cents\n", sep = "")
r <- tryCatch({ environment(meter$insert)$rate <- 0; "rate changed" }, error = function(e) "rate is locked")
cat(r, "\n", sep = "")

All lessons in Object Oriented Programming

Practice on your own: Online R compiler