Đề bài
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·htriangle 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.
Ràng buộc
1 ≤ number of shapes ≤ 1,000
0 < every number ≤ 1,000
Ví dụ
Đầu vào:
shapes = ["square 3", "rectangle 2 5", "triangle 4 3"]
Kết quả mong đợi:
expected = [9.0, 10.0, 6.0]
Đầu vào:
std::vector<std::string> shapes = {"square 3", "rectangle 2 5", "triangle 4 3"};
Kết quả mong đợi:
std::vector<double> expected = {9.0, 10.0, 6.0};
Đầu vào:
string[] shapes = new string[] {"square 3", "rectangle 2 5", "triangle 4 3"};
Kết quả mong đợi:
double[] expected = new double[] {9.0, 10.0, 6.0};
Giải thích
3² = 9, 2·5 = 10 and 4·3/2 = 6.
Đầu vào:
shapes = ["circle 1"]
Kết quả mong đợi:
expected = [3.141592653589793]
Đầu vào:
std::vector<std::string> shapes = {"circle 1"};
Kết quả mong đợi:
std::vector<double> expected = {3.141592653589793};
Đầu vào:
string[] shapes = new string[] {"circle 1"};
Kết quả mong đợi:
double[] expected = new double[] {3.141592653589793};
Giải thích
π·1² = π ≈ 3.141593.
Hướng tiếp cận
Hãy tự thử trước, sau đó mở từng gợi ý một.
Gợi ý 1
Read the first word to know which shape to build.
Gợi ý 2
Map each shape name to its area formula.
Gợi ý 3
Use π from your language's math library and keep full precision.
Độ phức tạp mong đợi
O(number of shapes) time, O(number of shapes) extra space
Tham khảo
Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.