TernaryGrayCodes
Length- words over in base-3 reflected Gray code order, where consecutive words differ by in exactly one digit.
OEIS
A000244SageMathsage.combinat.gray_codes.product([3]*n)TernaryGrayCodes(n)the base-3 digit strings of length , Gray-code ordered.Typed signatures
| Type | Package | Applies |
|---|---|---|
(integer<0..>) -> indexed_collection<ternary_gray_code> | combinatorics | always |
Details
- A lazy indexed collection; the count is the closed form , but the ORDER is the point — it is the standard reflected-Gray-code recursion (each digit's block traversed forward or reversed in turn), not lexicographic.
- Each element is the digit string itself, as a list over .
- unranks directly into that Gray-code order, so consecutive indices always differ in exactly one digit, by exactly 1.
Definition
Epsil, as the implementation runs it.
count(_n)
3 ^ _nunrank(_n, _r)
Map(Function(
(_r - _r % 3 ^ (_n - j)) / 3 ^ (_n - j) % 3 if Fold(
Function(
c +
(_r -
_r %
3 ^
(_n -
k)) /
3 ^
(_n -
k) %
3,
c,
k,
),
0,
Range(1, j -
1, 1),
) % 2 == 0 else 2 -
(_r -
_r %
3 ^
(_n - j)) /
3 ^
(_n - j) %
3,
j,
), Range(1, _n, 1))rank(_n, _x)
Fold(Function(
acc + 3 ^ (_n - j) * (_x[j] if Fold(
Function(c + _x[k], c, k),
0,
Range(1, j - 1, 1),
) % 2 == 0 else 2 - _x[j]),
acc,
j,
), 0, Range(1, _n, 1))valid(_n, _x)
Length(_x) == _n && Fold(
Function(ok_j && 0 <= _x[j] && _x[j] <= 2, ok_j, j),
True,
Range(1, Length(_x), 1),
)