
\ Balanced ternary gray code

: >gray ( n -- x ) dup 1 rshift not 3sum ; \ For any cell size

: gray> ( x -- n ) \ For 12 trit gray code
  dup 1 rshift 3sum
  dup 2 rshift 3sum
  dup 4 rshift 3sum
  dup 8 rshift 3sum
;

: graycode ( -- )
  121 dup 1+ swap negate do
    cr
    i t.
    i >gray t.
    i >gray gray> dup i = swap t. if ."  =  " else ."  <> " then
    i .
  loop
  cr
;

false t. false >gray t. false >gray gray> t.
 zero t.  zero >gray t.  zero >gray gray> t.
 true t.  true >gray t.  true >gray gray> t.

graycode
