J, 14 bytes
#:(,#+|.)^:n 0
Try it online!
A snippet assuming variable n
as specified in the challenge.
A Gray code of order n
can be constructed from order n-1
by the following steps:
- Take two copies of the previous one.
- Reverse the second.
- Prepend 0 bit to the first and 1 to the second.
As a list of integer values, prepending the 1 bit corresponds to adding 2^(n-1)
, which is precisely the length of the previous Gray code, and prepending 0 is a no-op. Therefore, one such iteration can be summarized to "append length plus reverse to self", which is what (,#+|.)
does.
#:(,#+|.)^:n 0
( )^:n 0 Starting from a single 0, repeat n times:
|. Reverse
#+ Add length to each item
, Append to self
(0 -> 0 1 -> 0 1 3 2 -> 0 1 3 2 6 7 5 4 -> ...)
#: Convert each number to binary
J, 17 bytes
[:#:(,#+|.)@[&0&0
Try it online!
Same solution as a function. @[&0&0
part is a bit tricky:
f@[&0&0
f A monadic(1-arg) function
@[ Convert to a dyadic(2-arg) function that uses the left arg,
ignoring the right
&0 Attach a dummy argument on the right side to get a "bind" function
&0 Treat a "bind" function as dyadic, where left arg becomes
repetition count and right arg is the starting value,
and set 0 as the starting value