Polymorphic Areas
PHP
Medium
7 views
Problem Description
Types: C r for circle, S a for square. Print area for each shape with 2 decimals.
Input Format
First n. Next n lines type value.
Output Format
n lines areas.
Official Solution
<?php
abstract class Shape{ abstract function area(); }
class Circle extends Shape{
private $r;
function __construct($r){ $this->r=$r; }
function area(){ return 3.141592653589793*$this->r*$this->r; }
}
class Square extends Shape{
private $a;
function __construct($a){ $this->a=$a; }
function area(){ return $this->a*$this->a; }
}
$inputLines=preg_split('/\\R/', rtrim(stream_get_contents(STDIN)));
if(!$inputLines || trim($inputLines[0])==='') exit;
$n=intval($inputLines[0]);
$output=[];
for($i=1;$i<=$n;$i++){
$tokens=preg_split('/\\s+/', trim($inputLines[$i] ?? ''));
$t=$tokens[0] ?? '';
$v=floatval($tokens[1] ?? 0);
if($t==='C') $sh=new Circle($v);
else $sh=new Square($v);
$output[] = number_format($sh->area(),2,'.','');
}
echo implode(PHP_EOL,$output);
?>
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!