Menu
Coddy logo textTech

Parking Garage

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

challenge icon

Challenge

Hard

Build a parking garage. Vehicle.R declares the virtual S4 class Vehicle (slot plate), the generics size_rank(v) and rate(v) and the names SIZES: small, medium, large for the ranks 1, 2 and 3.

  • In Motorbike.R, Car.R and Van.R the classes are declared; add their methods: a motorbike has rank 1 and pays 1 per hour, a car rank 2 and 3 per hour, a van rank 3 and 5 per hour.
  • In Garage.R complete the Reference Class Garage. Its field free holds the free spots per rank and parked is a list by plate. park(v) takes a free spot of the vehicle's own rank or, if none is free, the next larger rank, and replies parked AB12 in medium, full for AB12 or AB12 is already parked. leave(plate, hours) frees the spot and replies AB12 paid 9 (the rate times the hours, at least 1 hour) or no vehicle AB12. status() replies free: small 1, medium 0, large 2; parked: 1.

The supplied code reads the free spots as small,medium,large, then commands park car AB12 (bike, car or van), leave AB12 3 or status, and prints each reply.

Your code goes in Vehicle.R, Motorbike.R, Car.R, Van.R and Garage.R. main.R holds the supplied input/output code and cannot be edited.

Try it yourself

source("Vehicle.R")
source("Motorbike.R")
source("Car.R")
source("Van.R")
source("Garage.R")

# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
garage <- Garage$new(free = as.numeric(strsplit(input[1], ",")[[1]]))
for (line in input[-1]) {
  p <- strsplit(line, " ")[[1]]
  reply <- switch(p[1],
    park = garage$park(switch(p[2],
      bike = new("Motorbike", plate = p[3]),
      car = new("Car", plate = p[3]),
      van = new("Van", plate = p[3]))),
    leave = garage$leave(p[2], as.numeric(p[3])),
    status = garage$status())
  cat(reply, "\n", sep = "")
}

All lessons in Object Oriented Programming

Practice on your own: Online R compiler