Shift right by half a trit
This is inspired by Shift right by half a bit, but it's a little different.
Motivation
I was wondering if there is a function f
that maps the non-negative integers to the non-negative integers, with the following properties:
- It is non-decreasing (if
a < b
, thenf(a) ≤ f(b)
) - For any non-negative integer
a
,f(f(a)) = floor(a/3)
It turns out there is exactly one f
that satisfies these properties. Your task is to implement it.
Task
Write a program or function that takes a non-negative integer n
, and applies these rules:
- If
n=0
, return0
. - Otherwise, write
n
in ternary. If it starts with a1
, change the leading1
to a2
, then remove the final digit and return the resulting number. - If
n
starts with a2
, change it to a1
and return the resulting number.
Note that you don't need to implement this exact procedure, but I included it to give an explicit description of f
.
Rules
Numbers can be represented in any reasonable format, but if you represent them as a string or list of digits, it must be in decimal or unary. I include this to specifically disallow ternary, since that skips a large part of the problem.
This is code-golf, so fewest bytes wins.
Test cases
0 -> 0
1 -> 0
2 -> 1
26 -> 17
27 -> 18
53 -> 26
54 -> 27
1337 -> 688