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, then f(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, return 0.
- Otherwise, write
n in ternary. If it starts with a 1, change the leading 1 to a 2, then remove the final digit and return the resulting number.
- If
n starts with a 2, change it to a 1 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
3ḍover the first list to make a new second list before summing; the second constructs one filtered list then immediately takes its length. \$\endgroup\$