Updated Gray code algorithm