How can I generate n-bit base-m Gray code in Mathematica, where only 1 bit changes at a time and all possibilities are covered? I have been hitting my head against a metaphorical wall for a few hours now, feeling frustrated at my forgotten Electrical Engineering knowledge.
For FullGrayCode[4,2] I would expect something like this that I found by hand:
{
{0, 0, 0, 0},
{1, 0, 0, 0},
{1, 1, 0, 0},
{0, 1, 0, 0},
{0, 1, 1, 0},
{1, 1, 1, 0},
{1, 0, 1, 0},
{0, 0, 1, 0},
{0, 0, 1, 1},
{1, 0, 1, 1},
{1, 1, 1, 1},
{0, 1, 1, 1},
{0, 1, 0, 1},
{1, 1, 0, 1},
{1, 0, 0, 1},
{0, 0, 0, 1}
}
For FullGrayCode[3,2] a novel case I might expect something like this
{
{0,0},
{0,1},
{0,2},
{1,2},
{1,1},
{1,0},
{2,0},
{2,1},
{2,2}
}
For FullGrayCode[3,3] I could expect:
{
{0,0,0},
{0,0,1},
{0,0,2},
{0,1,2},
{0,1,1},
{0,1,0},
{0,2,0},
{0,2,1},
{0,2,2},
{1,2,2},
{1,2,1},
{1,2,0},
{1,1,0},
{1,1,1},
{1,1,2},
{1,0,2},
{1,0,1},
{1,0,0},
{2,0,0},
{2,0,1},
{2,0,2},
{2,1,2},
{2,1,1},
{2,1,0},
{2,2,0},
{2,2,1},
{2,2,2}
}
I originally wrote this:
FullGrayCode[n_Integer?Positive, m_Integer?Positive]:=Module[
{sequence, baseMIncrement, grayCode},
baseMIncrement[num_List]:=Module[
{carry, pos, numCopy},
carry = 1;
pos = Length[num];
numCopy = num;
While[pos > 0 && carry > 0,
numCopy[[pos]] = Mod[numCopy[[pos]] + carry, m];
carry = If[numCopy[[pos]] == 0, 1, 0];
pos--;
];
numCopy
];
grayCode[num_List] := Module[
{gray},
gray = num;
gray[[1]] = Mod[gray[[1]] + 1, m];
If[gray[[1]] != 0,
gray[[2]] = Mod[gray[[2]] + 1, m]
];
gray
];
sequence = {ConstantArray[0, n]};
For[i = 1, i < m^n, i++,
sequence = Append[sequence, grayCode[baseMIncrement[sequence[[-1]]]]];
];
sequence
]
but the difference between the first and second (and so on) have all of the bits changing except for one of them, it should be one of the bits change.
Additional hand done case in Excel for FullGrayCode[3,4] (non-efficient and rotated 2-3):
{
{0,0,0},
{0,0,1},
{0,0,3},
{0,0,2},
{0,1,2},
{0,1,3},
{0,1,1},
{0,1,0},
{0,3,0},
{0,3,1},
{0,3,3},
{0,3,2},
{0,2,2},
{0,2,3},
{0,2,1},
{0,2,0},
{1,2,0},
{1,2,1},
{1,2,3},
{1,2,2},
{1,3,2},
{1,3,3},
{1,3,1},
{1,3,0},
{1,1,0},
{1,1,1},
{1,1,3},
{1,1,2},
{1,0,2},
{1,0,3},
{1,0,1},
{1,0,0},
{3,0,0},
{3,0,1},
{3,0,3},
{3,0,2},
{3,1,2},
{3,1,3},
{3,1,1},
{3,1,0},
{3,3,0},
{3,3,1},
{3,3,3},
{3,3,2},
{3,2,2},
{3,2,3},
{3,2,1},
{3,2,0},
{2,2,0},
{2,2,1},
{2,2,3},
{2,2,2},
{2,3,2},
{2,3,3},
{2,3,1},
{2,3,0},
{2,1,0},
{2,1,1},
{2,1,3},
{2,1,2},
{2,0,2},
{2,0,3},
{2,0,1},
{2,0,0}
}
GrayCode
resource function (resources.wolframcloud.com/FunctionRepository/resources/…). See in the examples on that page how to combine its output withPadLeft
to obtain something that looks very much like your output. $\endgroup$