It is easier to denote the #. of the generalised Gray codes, so the examples
below become
,.(#/ #.gGC/)&.>2 4;3 3
+----------------------------------------------------------------------+
|0 1 2 3 7 6 5 4 8 9 10 11 15 14 13 12 |
+----------------------------------------------------------------------+
|0 1 2 5 4 3 6 7 8 17 16 15 12 13 14 11 10 9 18 19 20 23 22 21 24 25 26|
+----------------------------------------------------------------------+
In an even more general approach which base is used is determined per
dimension:
(](]; ,.@:#.)gGC1) 4 3 2
+-----+--+
|0 0 0| 0|
|0 0 1| 1|
|0 1 1| 3|
|0 1 0| 2|
|0 2 0| 4|
|0 2 1| 5|
|1 2 1|11|
|1 2 0|10|
|1 1 0| 8|
|1 1 1| 9|
|1 0 1| 7|
|1 0 0| 6|
|2 0 0|12|
|2 0 1|13|
|2 1 1|15|
|2 1 0|14|
|2 2 0|16|
|2 2 1|17|
|3 2 1|23|
|3 2 0|22|
|3 1 0|20|
|3 1 1|21|
|3 0 1|19|
|3 0 0|18|
+-----+--+
with
lr 'gGC1'
[: > [: ,/@([ ,"1"1 _1 [EMAIL PROTECTED] $ (,: |.)@])&.>/ <@,[EMAIL PROTECTED]"0
An alternative which immediately produces the generalised Gray code numbers:
gGC2=: [: +/\ 0: (, }:) [: ([ ((* {:) ,~ }:@]) (,@$ ((,: -)@}: ,. {:)))/ ,&1
gGC2 4 3 2
0 1 3 2 4 5 11 10 8 9 7 6 12 13 15 14 16 17 23 22 20 21 19 18
((#.gGC1) -: gGC2) 4 3 2
1
Comparing performance
10 ts '8 gGC 5'
0.13025744 50335872
10 ts 'gGC1 T'[T=:8#5
0.13039646 50334016
10 ts 'gGC2 T'
0.019955891 6817024
R.E. Boss
-----Oorspronkelijk bericht-----
Van: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] Namens R.E. Boss
Verzonden: dinsdag 5 december 2006 18:03
Aan: 'Programming forum'
Onderwerp: RE: [Jprogramming] Gray codes
Generalised or n-ary Gray codes use more numbers, see
http://en.wikipedia.org/wiki/Gray_code#n-ary_Gray_code
gGC=: 4 : 0 NB. (generalised) x-dim y-ary Graycode
z=:i.y
z ,/@:([,."_1 [EMAIL PROTECTED] $(,:|.)@])^:(<:x) [,.z
)
2 3 <@gGC"0 [4 3
+---+-----+
|0 0|0 0 0|
|0 1|0 0 1|
|0 2|0 0 2|
|0 3|0 1 2|
|1 3|0 1 1|
|1 2|0 1 0|
|1 1|0 2 0|
|1 0|0 2 1|
|2 0|0 2 2|
|2 1|1 2 2|
|2 2|1 2 1|
|2 3|1 2 0|
|3 3|1 1 0|
|3 2|1 1 1|
|3 1|1 1 2|
|3 0|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|
+---+-----+
R.E. Boss
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm