Source code for titan_pylib.algorithm.gray_code
1from typing import Iterator
2
3
[docs]
4def gray_code(n) -> Iterator[int]:
5 """長さ n の bit 列に対し、0,1,...,(1<<n) を列挙する。
6 i 番目の返り値は、前と変化する位置を返す。
7 """
8 pre = 0
9 for i in range(1, 1 << n):
10 now = i ^ (i >> 1)
11 yield (pre ^ now).bit_length() - 1
12 pre = now