Parse shapes into a discriminated union and compute their areas.
What to build
A program that prints the area of each shape and the total.
Requirements
- Use a discriminated union
Shapewithkindbeingcircle,rectortriangle. - For each line print
KIND AREAwith the area to two decimal places (circle πr², rect w × h, triangle b × h / 2). - For a line whose first word is not one of the three kinds, print
skipped LINE. - Finally print
total AREA(two decimal places) over the valid shapes.
Input
Line 1: n. Then n lines: circle r, rect w h or triangle b h.
Output
n lines, then the total.
Constraints
1 ≤ n ≤ 50; all sizes are positive numbers.
Example
Input:
3
circle 1
rect 2 3
triangle 4 5
Output:
circle 3.14
rect 6.00
triangle 10.00
total 19.14
Why it works
Each member of the union carries exactly the sizes it needs, and checking kind gives access to them, so a circle can never be measured with a width by mistake.
Examples
Example 1 · Input
3 circle 1 rect 2 3 triangle 4 5
Expected output
circle 3.14 rect 6.00 triangle 10.00 total 19.14
Example 2 · Input
2 square 2 circle 2
Expected output
skipped square 2 circle 12.57 total 12.57
Hints
Hint 1
type Shape = { kind: "circle"; r: number } | { kind: "rect"; w: number; h: number } | { kind: "triangle"; b: number; h: number }.
Hint 2
Parse each line into a Shape or null; then compute the area by checking kind.
Solution
Show one correct solution (try it yourself first)
const read = (): string => prompt() ?? "";
type Shape =
| { kind: "circle"; r: number }
| { kind: "rect"; w: number; h: number }
| { kind: "triangle"; b: number; h: number };
function parse(line: string): Shape | null {
const [kind, x, y] = line.split(" ");
if (kind === "circle") return { kind, r: Number(x) };
if (kind === "rect") return { kind, w: Number(x), h: Number(y) };
if (kind === "triangle") return { kind, b: Number(x), h: Number(y) };
return null;
}
function area(s: Shape): number {
if (s.kind === "circle") return Math.PI * s.r * s.r;
if (s.kind === "rect") return s.w * s.h;
return (s.b * s.h) / 2;
}
const n = Number(read());
let total = 0;
for (let i = 0; i < n; i++) {
const line = read();
const shape = parse(line);
if (shape === null) {
console.log("skipped " + line);
continue;
}
const a = area(shape);
total += a;
console.log(shape.kind + " " + a.toFixed(2));
}
console.log("total " + total.toFixed(2));