I'm currently trying to solve a problem as follows:
Implement an object hierarchy which contains at least classes for a rectangle, a triangle and a circle. Implement a function float SumArea() that will iterate over an n-sized container of these shapes and sum their area. Also implement functions void AddTriangle(float b, float h), void AddSquare(float size), void AddCircle(float radius).
- Note 1: You need only write a single function for each class (plus the constructor).
- Note 2: The total sum of areas is required, regardless if the shapes overlap.
- Note 3: Try to make the iteration code as optimal as possible.
So far I've managed to write classes for the shapes as well as a method for each to calculate their area (the question is a bit confusing as it says rectangle but then has a function called addsquare in the answer class). I've also added the areas together in sum area but am a bit lost as to how I can calculate the area even if the shapes overlap in the container?
Here is what I have so far:
class Rectangle {
constructor(size) {
this.size = size;
}
area() {
return this.size * this.size;
}
}
class Triangle {
constructor(base, height) {
this.base = base;
this.height = height;
}
area() {
return this.base * this.height / 2;
}
}
class Circle {
constructor(radius) {
this.radius = radius;
}
area() {
return Math.PI * this.radius ** 2;
}
}
class Answer {
addTriangle(b, h) {
const triangle = new Triangle(b, h);
return triangle.area();
}
addSquare(size) {
const rectangle = new Rectangle(size);
return rectangle.area();
}
addCircle(radius) {
const circle = new Circle(radius);
return circle.area();
}
sumArea() {
return Answer.addTriangle Answer.addSquare Answer.addCircle;
}
}
Any help greatly appreciated.
CodePudding user response:
Your implementation isn't working with a container, as the assignment is telling you to do. It requires you to store a list of shapes that you iterate over when you call the sumArea
method
He's a snippet to help you in the right direction:
class Rectangle {
constructor(size) { this.size = size; }
area() { return this.size * this.size; }
}
class Triangle {
constructor(base, height) { this.base = base; this.height = height; }
area() { return this.base * this.height / 2; }
}
class Circle {
constructor(radius) { this.radius = radius; }
area() { return Math.PI * this.radius ** 2; }
}
class Answer {
container = [];
addTriangle(b, h) {
this.container.push(new Triangle(b, h));
}
// Implement `addSquare` and `addCircle`
sumArea() {
// Iterate over `this.container` here, to add together all shapes'
// areas in the container. Look into using `reduce` for that.
}
}
const answer = new Answer();
answer.addTriangle(3, 5);
answer.addTriangle(4, 1);
// answer.addSquare(2, 4);
// answer.addCircle(6);
console.log(answer.sumArea());