簡単 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 つずつ開いてみましょう。

ヒント 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用に調整されています。上記の説明と制約に従ってください。

他の人の解答から学ぶ

コミュニティの解答

まだ公開された解答がありません。この課題を解いて最初の解答を共有しましょう。