Avatar of piotr-jelinski

piotr-jelinski's solution

to Triangle in the PHP Track

Published at Sep 30 2019 · 0 comments
Instructions
Test suite
Solution

Determine if a triangle is equilateral, isosceles, or scalene.

An equilateral triangle has all three sides the same length.

An isosceles triangle has at least two sides the same length. (It is sometimes specified as having exactly two sides the same length, but for the purposes of this exercise we'll say at least two.)

A scalene triangle has all sides of different lengths.

Note

For a shape to be a triangle at all, all sides have to be of length > 0, and the sum of the lengths of any two sides must be greater than or equal to the length of the third side. See Triangle Inequality.

Dig Deeper

The case where the sum of the lengths of two sides equals that of the third is known as a degenerate triangle - it has zero area and looks like a single line. Feel free to add your own code/tests to check for degenerate triangles.

Running the tests

  1. Go to the root of your PHP exercise directory, which is <EXERCISM_WORKSPACE>/php. To find the Exercism workspace run

     % exercism debug | grep Workspace
    
  2. Get PHPUnit if you don't have it already.

     % wget --no-check-certificate https://phar.phpunit.de/phpunit.phar
     % chmod +x phpunit.phar
    
  3. Execute the tests:

     % ./phpunit.phar triangle/triangle_test.php
    

Source

The Ruby Koans triangle project, parts 1 & 2 http://rubykoans.com

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

triangle_test.php

<?php

class TriangleTest extends PHPUnit\Framework\TestCase
{
    public static function setUpBeforeClass() : void
    {
        require_once 'triangle.php';
    }

    public function testEquilateralTrianglesHaveEqualSides() : void
    {
        $this->assertEquals(
            'equilateral',
            (new Triangle(2, 2, 2))->kind()
        );
    }

    public function testLargerEquilateralTrianglesHaveEqualSides() : void
    {
        $this->assertEquals(
            'equilateral',
            (new Triangle(10, 10, 10))->kind()
        );
    }

    public function testIsoscelesTriangleWhenLastTwoSidesAreEqual() : void
    {
        $this->assertEquals(
            'isosceles',
            (new Triangle(3, 4, 4))->kind()
        );
    }

    public function testIsoscelesTriangleWhenFirstAndLastSidesAreEqual() : void
    {
        $this->assertEquals(
            'isosceles',
            (new Triangle(4, 3, 4))->kind()
        );
    }

    public function testIsoscelesTriangleWhenFirstTwoSidesAreEqual() : void
    {
        $this->assertEquals(
            'isosceles',
            (new Triangle(4, 4, 3))->kind()
        );
    }

    public function testIsoscelesTrianglesWithUnequalSideLargerThanEqualSides() : void
    {
        $this->assertEquals(
            'isosceles',
            (new Triangle(4, 4, 7))->kind()
        );
    }

    public function testScaleneTrianglesHaveNoEqualSides() : void
    {
        $this->assertEquals(
            'scalene',
            (new Triangle(3, 4, 5))->kind()
        );
    }

    public function test2aEqualsBPlusCLooksLikeEquilateralButIsNot() : void
    {
        $this->assertEquals(
            'scalene',
            (new Triangle(5, 4, 6))->kind()
        );
    }

    public function testScaleneTrianglesHaveNoEqualSidesAtLargerScale() : void
    {
        $this->assertEquals(
            'scalene',
            (new Triangle(10, 11, 12))->kind()
        );
    }

    public function testScaleneTrianglesHaveNoEqualSidesInDescendingOrder() : void
    {
        $this->assertEquals(
            'scalene',
            (new Triangle(5, 4, 2))->kind()
        );
    }

    public function testVerySmallTrianglesAreLegal() : void
    {
        $this->assertEquals(
            'scalene',
            (new Triangle(0.4, 0.6, 0.3))->kind()
        );
    }

    public function testTrianglesWithNoSizeAreIllegal() : void
    {
        $this->expectException(Exception::class);

        (new Triangle(0, 0, 0))->kind();
    }

    public function testTrianglesViolatingTriangleInequalityAreIllegal() : void
    {
        $this->expectException(Exception::class);

        (new Triangle(1, 1, 3))->kind();
    }

    public function testTrianglesViolatingTriangleInequalityAreIllegal2() : void
    {
        $this->expectException(Exception::class);

        (new Triangle(7, 3, 2))->kind();
    }

    public function testTrianglesViolatingTriangleInequalityAreIllegal3() : void
    {
        $this->expectException(Exception::class);

        (new Triangle(1, 3, 1))->kind();
    }
}

triangle.php

<?php

declare(strict_types=1);

require_once 'TriangleValidator.php';

class Triangle
{
    public const TRIANGLE_EQUILATERAL = 'equilateral';
    public const TRIANGLE_ISOSCELES = 'isosceles';
    public const TRIANGLE_SCALENE = 'scalene';

    /**
     * @var float[]
     */
    private $sides;

    /**
     * @param float[] ...$sides
     * @throws Exception
     */
    public function __construct(float ...$sides)
    {
        sort($sides);
        (new TriangleValidator())->validate($sides);
        $this->sides = $sides;
    }

    /**
     * @return bool
     */
    public function isEquilateral(): bool
    {
        [$a, , $c] = $this->sides;

        return $a === $c;
    }

    /**
     * @return bool
     */
    public function isIsosceles(): bool
    {
        [$a, $b, $c] = $this->sides;

        return $a === $b || $b === $c;
    }

    /**
     * @return string
     */
    public function kind(): string
    {
        return $this->isEquilateral() ?
            self::TRIANGLE_EQUILATERAL :
            ($this->isIsosceles() ?
                self::TRIANGLE_ISOSCELES :
                self::TRIANGLE_SCALENE);
    }
}

TriangleValidator.php

<?php

declare(strict_types=1);

class TriangleValidator
{
    public const EXCEPTION_SIDE_COUNT = 'Triangle requires exactly 3 sides';
    public const EXCEPTION_SIDE_LENGTH = 'All sides of a triangle must be positive numbers';
    public const EXCEPTION_TRIANGLE_INEQUALITY = 'Triangle inequality violation';

    /**
     * @param array $sides
     * @throws Exception
     */
    public function validate(array $sides): void
    {
        if (!$this->checkSideCount($sides)) {
            throw new Exception(self::EXCEPTION_SIDE_COUNT);
        }

        if (!$this->checkSideLength($sides)) {
            throw new Exception(self::EXCEPTION_SIDE_LENGTH);
        }

        if (!$this->checkTriangleInequality($sides)) {
            throw new Exception(self::EXCEPTION_TRIANGLE_INEQUALITY);
        }
    }

    /**
     * @param array $sides
     * @return bool
     */
    private function checkSideCount(array $sides): bool
    {
        return count($sides) === 3;
    }

    /**
     * @param array $sides
     * @return bool
     */
    private function checkSideLength(array $sides): bool
    {
        [$a] = $sides;

        return $a > 0;
    }

    /**
     * @param array $sides
     * @return bool
     */
    private function checkTriangleInequality(array $sides): bool
    {
        [$a, $b, $c] = $sides;

        return $a + $b > $c;
    }
}

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?