# 4d47's solution

## to Trinary in the PHP Track

Published at Jul 13 2018 · 1 comment
Instructions
Test suite
Solution

Convert a trinary number, represented as a string (e.g. '102012'), to its decimal equivalent using first principles.

The program should consider strings specifying an invalid trinary as the value 0.

Trinary numbers contain three symbols: 0, 1, and 2.

The last place in a trinary number is the 1's place. The second to last is the 3's place, the third to last is the 9's place, etc.

``````# "102012"
1       0       2       0       1       2    # the number
1*3^5 + 0*3^4 + 2*3^3 + 0*3^2 + 1*3^1 + 2*3^0    # the value
243 +     0 +    54 +     0 +     3 +     2 =  302
``````

If your language provides a method in the standard library to perform the conversion, pretend it doesn't exist and implement it yourself.

## 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 trinary/trinary_test.php
``````

## Source

All of Computer Science http://www.wolframalpha.com/input/?i=binary&a=*C.binary-_*MathWorld-

## Submitting Incomplete Solutions

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

### trinary_test.php

``````<?php

require "trinary.php";

class TrinaryTest extends PHPUnit\Framework\TestCase
{
public function test1IsDecimal1()
{
\$this->assertEquals(1, toDecimal('1'));
}

public function test2IsDecimal2()
{
\$this->assertEquals(2, toDecimal('2'));
}

public function test10IsDecimal3()
{
\$this->assertEquals(3, toDecimal('10'));
}

public function test11IsDecimal4()
{
\$this->assertEquals(4, toDecimal('11'));
}

public function test100IsDecimal9()
{
\$this->assertEquals(9, toDecimal('100'));
}

public function test112IsDecimal14()
{
\$this->assertEquals(14, toDecimal('112'));
}

public function test222IsDecimal26()
{
\$this->assertEquals(26, toDecimal('222'));
}

public function test1122000120IsDecimal32091()
{
\$this->assertEquals(32091, toDecimal('1122000120'));
}

public function testInvalidTrinaryIsDecimal0()
{
\$this->assertSame(0, toDecimal('13201'));
}
}``````
``````<?php

function toDecimal(\$str)
{
//return base_convert(\$str, 3, 10);
if (!preg_match('/^[012]+\$/', \$str))
return 0;
\$sum = 0;
for (\$i = strlen(\$str) - 1, \$pos = 0; \$i >= 0; \$i--, \$pos++) {
\$sum += \$str[\$i] * 3 ** \$pos;
}
return \$sum;
}``````