ðŸŽ‰ Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io ðŸŽ‰

# DrizzlingVoid's solution

## to Trinary in the Julia Track

Published at Feb 04 2021 · 0 comments
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.

## Source

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

## Version compatibility

This exercise has been tested on Julia versions >=1.0.

## Submitting Incomplete Solutions

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

### runtests.jl

``````using Test

include("trinary.jl")

@testset "trinary 1 is decimal 1" begin
@test trinary_to_decimal("1") == 1
end

@testset "trinary 2 is decimal 2" begin
@test trinary_to_decimal("2") == 2
end

@testset "trinary 10 is decimal 3" begin
@test trinary_to_decimal("10") == 3
end

@testset "trinary 11 is decimal 4" begin
@test trinary_to_decimal("11") == 4
end

@testset "trinary 100 is decimal 9" begin
@test trinary_to_decimal("100") == 9
end

@testset "trinary 112 is decimal 14" begin
@test trinary_to_decimal("112") == 14
end

@testset "trinary 222 is decimal 26" begin
@test trinary_to_decimal("222") == 26
end

@testset "trinary 1122000120 is decimal 32091" begin
@test trinary_to_decimal("1122000120") == 32091
end

@testset "invalid trinary digits returns 0" begin
@test trinary_to_decimal("1234") == 0
end

@testset "invalid word as input returns 0" begin
@test trinary_to_decimal("carrot") == 0
end

@testset "invalid numbers with letters as input returns 0" begin
@test trinary_to_decimal("0a1b2c") == 0
end``````
``````function trinary_to_decimal(str::String)::Int
occursin(r"[^0-2]", str) && return 0
return sum(parse(Int, v)*3^(length(str)-i) for (i, v) in enumerate(str))
end``````

### 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?