आसान 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 के लिए अनुकूलित की गई है। ऊपर दिए गए स्टेटमेंट और सीमाओं का पालन करें।

दूसरों से सीखें

समुदाय समाधान

अभी तक कोई प्रकाशित समाधान नहीं। पहला साझा करने के लिए इस चुनौती को हल करें।