Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs

Dashboard
Notifications
Mark all as read
Challenges

When The Ternary Is Balance

+3
−0

Inspired by this Rosetta Code article.

Introduction

Balanced Ternary is a method of representing integers using -1, 0 and 1 in base 3.

Decimal 11 = (1 * 32) + (1 * 31) + (−1 * 30) = [1,1,-1] or "++-"

Decimal 6 = (1 * 32) + (−1 * 31) + (0 * 30) = [1,-1,0] or "+-0"

Task

Given any integer, you must give its balanced ternary representation in any permitted format (array, string, etc.)

Your program must support all integers present within its maximum integer limit.

Test Cases

Reference implementation with first 200 values

5 +--
6 +-0
11 ++-
65 +-++-
-44 -++0+
-540 -+-+000

Scoring

This is code-golf. Shortest answer in each language wins.

Why does this post require moderator attention?
You might want to add some details to your flag.
Why should this post be closed?

2 comment threads

Can I return a number instead of a string for the zero case? (2 comments)
Are leading zeros in the output allowed? (2 comments)

3 answers

+3
−0

Haskell, 78 77 bytes

(g[0]!)
g a=mapM(\_->[-1..1])a++g(0:a)
(a:b)!c|foldl1((+).(*3))a==c=a|0<1=b!c

Try it online!

Why does this post require moderator attention?
You might want to add some details to your flag.

0 comment threads

+3
−0

JavaScript (Node.js), 47 40 50 49 bytes

-1 (possibly -3) bytes thanks to Shaggy!

f=(n,s='0')=>n?f(n/3+n%3/2|0,'')+"+-0+-"[n%3+2]:s

Try it online!

A basic recursive solution.

Why does this post require moderator attention?
You might want to add some details to your flag.

3 comment threads

47 bytes? (2 comments)
For the value 0, this returns the empty string instead of the string `0`. (3 comments)
(Possible) 40 bytes (1 comment)
+2
−0

Python 3, 78 bytes

def t(n,*l):d="0+-"[n%3];return d*(not l or n*n) if n*n<2 else t((n+1)//3,1)+d

Try it online!

Why does this post require moderator attention?
You might want to add some details to your flag.

0 comment threads

Sign up to answer this question »

This community is part of the Codidact network. We have other communities too — take a look!

You can also join us in chat!

Want to advertise this community? Use our templates!