Skip to content

Instantly share code, notes, and snippets.

@ytkhs
Last active September 17, 2015 07:43
Show Gist options
  • Select an option

  • Save ytkhs/8a4e87d2d088ba163133 to your computer and use it in GitHub Desktop.

Select an option

Save ytkhs/8a4e87d2d088ba163133 to your computer and use it in GitHub Desktop.
PHPのジェネレータを使ってグレイコードを出力する
$i^($i>>1);
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
<?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