Menu
Coddy logo textTech

Recap - Shape Areas

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

challenge icon

Challenge

Medium

Build a small shape library over four files. The constructors are given.

  • Shape.R: the generics area(shape, ...), perimeter(shape, ...) and describe(shape, ...). The default area() and perimeter() methods stop with unknown shape: hexagon (use call. = FALSE). The default describe() returns circle: area 3.14, perimeter 6.28, built from the shape's first class and the two generics, with two decimal places.
  • Circle.R, Rectangle.R, Triangle.R: the area and perimeter methods of each shape. A triangle has the sides a, b, c; its area is sqrt(s * (s - a) * (s - b) * (s - c)) with s half the perimeter.

The supplied code reads lines circle 1, rectangle 2 3, triangle 3 4 5 or any other name, prints describe() or error: and the message, and finally the total area.

Your code goes in Shape.R, Circle.R, Rectangle.R and Triangle.R. main.R holds the supplied input/output code and cannot be edited.

Try it yourself

source("Shape.R")
source("Circle.R")
source("Rectangle.R")
source("Triangle.R")

# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
total <- 0
for (line in input) {
  p <- strsplit(line, " ")[[1]]
  n <- as.numeric(p[-1])
  s <- switch(p[1],
    circle = new_circle(n[1]),
    rectangle = new_rectangle(n[1], n[2]),
    triangle = new_triangle(n[1], n[2], n[3]),
    structure(list(), class = p[1]))
  out <- tryCatch({
    total <- total + area(s)
    describe(s)
  }, error = function(e) paste("error:", conditionMessage(e)))
  cat(out, "\n", sep = "")
}
cat(sprintf("total area: %.2f", total), "\n", sep = "")

All lessons in Object Oriented Programming

Practice on your own: Online R compiler