A drawing app keeps rectangles, squares and triangles in one list. Write the shape types so that code holding that list can ask any shape for its name and its perimeter (the length all the way around it) without knowing which kind of shape it is. That is polymorphism: one call, shape.perimeter(), and each kind of shape runs its own version.
Every shape class inherits from the class Shape, the common type. Shape has two methods:
name()returns the kind of shape as text:"Shape"for a plainShape.perimeter()returns the length around the shape:0for a plainShape.
Each shape class overrides both:
Rectangle(width, height): itsnameis"Rectangle", itsperimeter2 × (width + height).Square(side): itsnameis"Square", itsperimeter4 × side.Triangle(a, b, c): itsnameis"Triangle", itsperimetera + b + c.
In TypeScript a class inherits with class Rectangle extends Shape, and a method with the same name as the parent's replaces it for that class. Each class declares its fields, and its constructor calls super() before it stores anything in this.
Then write two plain functions that get any shapes as a Shape[]:
totalPerimeter(shapes)returns the sum of the perimeters of all the shapes.largestShape(shapes)returns thenameof the shape with the largest perimeter. If several shapes share the largest perimeter, the one that comes first wins.
Both functions must work through the common type's methods only: never check which kind a shape is. Then a new kind of shape, added later, works with them unchanged.
The starter code already has every class, constructor and method header: write their bodies. For each test, the harness reads the shapes, builds them in the order given, calls totalPerimeter and largestShape, and prints the two results on one line, separated by a space.
Example 1:
Input:
new Rectangle(3, 4)
new Square(5)
new Triangle(3, 4, 5)
Output: 46 Square
Explanation: The perimeters are 2 × (3 + 4) = 14, 4 × 5 = 20 and 3 + 4 + 5 = 12. Their total is 46, and the square's 20 is the largest.
Example 2:
Input:
new Rectangle(2, 4)
new Square(3)
new Triangle(4, 4, 4)
Output: 36 Rectangle
Explanation: All three perimeters are 12: 2 × (2 + 4), 4 × 3 and 4 + 4 + 4. On a tie the shape that comes first in the list wins, so the answer is the rectangle.
Example 3:
Input:
new Square(1)
new Rectangle(1, 1)
new Triangle(2, 2, 3)
Output: 15 Triangle
Explanation: The perimeters are 4, 4 and 7, so the last shape, the triangle, is the largest. A 1 by 1 rectangle has the same sides as a square, but it is still a Rectangle: each object answers name() for its own class.
Constraints:
- Every test has between 1 and 100 shapes: the list is never empty.
- Every size (width, height, side, and each side of a triangle) is an integer from 1 to 104.
- A triangle's three sides always make a real triangle: each side is shorter than the other two together.
Note:
Each function looks at every shape once: O(n) time for n shapes, and no extra space.
Free plan: 30 tutor messages. PRO is unlimited.
