Polymorphic Areas

Polymorphic Areas

Medium PHP PHP OOP Basics 33 views
Explanation Complexity

Problem Statement

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.

Example

3
C 1
S 2
C 3
3.14
4.00
28.27

Constraints

n

Input / Output Format

Input Format
First n. Next n lines type value.
Output Format
n lines areas.
Constraints
n

Examples

Input:
3 C 1 S 2 C 3
Output:
3.14 4.00 28.27

Example Solution (Public)

PHP
<?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);
?>

Official Solution Code

<?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);
?>
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.