Fácil 0 resueltos 0% de aceptación

Shape Factory

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

Lo que aprenderás

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

Problema

Ver traducción

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.

Restricciones

1 ≤ number of shapes ≤ 1,000

0 < every number ≤ 1,000

Ejemplos

Ejemplo 1
Entrada:
shapes = ["square 3", "rectangle 2 5", "triangle 4 3"]

Salida esperada:
expected = [9.0, 10.0, 6.0]
Entrada:
std::vector<std::string> shapes = {"square 3", "rectangle 2 5", "triangle 4 3"};

Salida esperada:
std::vector<double> expected = {9.0, 10.0, 6.0};
Entrada:
string[] shapes = new string[] {"square 3", "rectangle 2 5", "triangle 4 3"};

Salida esperada:
double[] expected = new double[] {9.0, 10.0, 6.0};

Explicación

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

Ejemplo 2
Entrada:
shapes = ["circle 1"]

Salida esperada:
expected = [3.141592653589793]
Entrada:
std::vector<std::string> shapes = {"circle 1"};

Salida esperada:
std::vector<double> expected = {3.141592653589793};
Entrada:
string[] shapes = new string[] {"circle 1"};

Salida esperada:
double[] expected = new double[] {3.141592653589793};

Explicación

π·1² = π ≈ 3.141593.

Cómo abordarlo

Inténtalo primero por tu cuenta y luego abre las pistas una a una.

Pista 1

Read the first word to know which shape to build.

Pista 2

Map each shape name to its area formula.

Pista 3

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

Complejidad esperada

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

Referencias

Este reto está adaptado para CodeUtility. Sigue el enunciado y las restricciones indicadas arriba.

Aprende de otros

Soluciones de la comunidad

Aún no hay soluciones publicadas. Resuelve este reto para compartir la primera.