Parking Garage
Part of the Object Oriented Programming section of Coddy's R journey. Lesson 55 of 57.
Challenge
HardBuild 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.RandVan.Rthe 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.Rcomplete the Reference ClassGarage. Its fieldfreeholds the free spots per rank andparkedis 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 repliesparked AB12 in medium,full for AB12orAB12 is already parked.leave(plate, hours)frees the spot and repliesAB12 paid 9(the rate times the hours, at least 1 hour) orno vehicle AB12.status()repliesfree: 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
1S3 Basics
Working With FilesLists With a ClassConstructor FunctionsPrint and Format MethodsValidators and HelpersRecap - Temperatures4Encapsulation in R
Closures as ObjectsEnvironments as ObjectsAccessor FunctionsGuarding StateRecap - Parking Meter2S3 Generics and Methods
Generics and UseMethodDefault MethodsMethods for Base GenericsNextMethod BasicsRecap - Shape Areas8Reference Classes
Defining Reference ClassesMethods and Field UpdatesCopy SemanticsInheritance and callSuperRecap - Task Queue11Project: Library Management
Books and MembersBorrowing BooksPractice on your own: Online R compiler