Last active
September 17, 2015 07:43
-
-
Save ytkhs/8a4e87d2d088ba163133 to your computer and use it in GitHub Desktop.
PHPのジェネレータを使ってグレイコードを出力する
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| $i^($i>>1); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 0 : 0000 | |
| 1 : 0001 | |
| 2 : 0011 | |
| 3 : 0010 | |
| 4 : 0110 | |
| 5 : 0111 | |
| 6 : 0101 | |
| 7 : 0100 | |
| 8 : 1100 | |
| 9 : 1101 | |
| 10 : 1111 | |
| 11 : 1110 | |
| 12 : 1010 | |
| 13 : 1011 | |
| 14 : 1001 | |
| 15 : 1000 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| function graycodes($range) { | |
| foreach($range as $i) { | |
| // キーも一緒に返すことができます。 | |
| yield $i => decbin($i ^ ($i >> 1)); | |
| // 次回はここからスタートします。 | |
| } | |
| } | |
| // 0から15番目までのグレイコードを出力します。 | |
| foreach(graycodes(range(0, 15)) as $k => $v) { | |
| echo sprintf("%2d : %04d\n",$k, $v); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment