โจทย์
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).
อินพุต
shapes: The descriptions. Numbers may have decimals.
เอาต์พุต
Return the area of each shape, in order. Answers within 1e-6 are accepted.
เงื่อนไข
1 ≤ จำนวนรูปทรง ≤ 1,000
0 < ทุกตัวเลข ≤ 1,000
ตัวอย่าง
อินพุต:
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 และ 4·3/2 = 6
อินพุต:
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
อ่านคำแรกเพื่อรู้ว่าต้องสร้างรูปทรงอะไร
คำใบ้ 2
จับคู่ชื่อรูปทรงแต่ละชื่อกับสูตรพื้นที่
คำใบ้ 3
ใช้ π จากไลบรารีคณิตศาสตร์ของภาษาและรักษาความแม่นยำไว้
ความซับซ้อนที่คาดหวัง
เวลา O(จำนวนรูปทรง), หน่วยความจำเพิ่ม O(จำนวนรูปทรง)
แหล่งอ้างอิง
โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน