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.
All of Computer Science http://www.wolframalpha.com/input/?i=binary&a=*C.binary-_*MathWorld-
This exercise has been tested on Julia versions >=1.0.
It's possible to submit an incomplete solution so you can see how others have completed the exercise.
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)
is_valid(x) = 0x30 <= codepoint(x) <= 0x32
all([is_valid(digit) for digit in str]) || return 0
raise((index, digit)) = codepoint(digit - 0x30) * 3^(index-1)
mapreduce(raise, +, enumerate(reverse(str)); init=0)
end
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.
Level up your programming skills with 3,450 exercises across 52 languages, and insightful discussion with our volunteer team of welcoming mentors. Exercism is 100% free forever.
Sign up Learn More
Community comments