쉬움 0명 해결 정답률 0%

Shape Factory

Create shapes from text descriptions with a factory and return the area of each one.

배우게 될 내용

  • Create objects from a text description
  • Hide construction behind one function
  • Let each shape compute its own area

문제

번역본 보기

The factory method pattern hides how objects are created: you ask the factory for a shape by name and get back an object that knows how to compute its own area.

Each description is a shape name followed by its numbers, separated by spaces:

  • circle r: area π·r²
  • square s: area s²
  • rectangle w h: area w·h
  • triangle b h: area b·h / 2

Implement shape_factory_areas(shapes).

Input

shapes: The descriptions. Numbers may have decimals.

Output

Return the area of each shape, in order. Answers within 1e-6 are accepted.

제약 조건

1 ≤ number of shapes ≤ 1,000

0 < every number ≤ 1,000

예시

예시 1
입력:
shapes = ["square 3", "rectangle 2 5", "triangle 4 3"]

예상 출력:
expected = [9.0, 10.0, 6.0]
입력:
std::vector<std::string> shapes = {"square 3", "rectangle 2 5", "triangle 4 3"};

예상 출력:
std::vector<double> expected = {9.0, 10.0, 6.0};
입력:
string[] shapes = new string[] {"square 3", "rectangle 2 5", "triangle 4 3"};

예상 출력:
double[] expected = new double[] {9.0, 10.0, 6.0};

설명

3² = 9, 2·5 = 10 and 4·3/2 = 6.

예시 2
입력:
shapes = ["circle 1"]

예상 출력:
expected = [3.141592653589793]
입력:
std::vector<std::string> shapes = {"circle 1"};

예상 출력:
std::vector<double> expected = {3.141592653589793};
입력:
string[] shapes = new string[] {"circle 1"};

예상 출력:
double[] expected = new double[] {3.141592653589793};

설명

π·1² = π ≈ 3.141593.

접근 방법

먼저 스스로 풀어 본 뒤 힌트를 하나씩 열어 보세요.

힌트 1

Read the first word to know which shape to build.

힌트 2

Map each shape name to its area formula.

힌트 3

Use π from your language's math library and keep full precision.

예상 복잡도

O(number of shapes) time, O(number of shapes) extra space

참고 자료

이 문제는 CodeUtility에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.

다른 사람의 풀이 보기

커뮤니티 솔루션

아직 공개된 풀이가 없습니다. 문제를 풀고 첫 풀이를 공유하세요.