Imports System
'===========================================================
' Title: Gray‑Code Sequence (One‑Bit‑Change Order)
'
' This program prints the 5‑bit Gray‑code sequence from 0 to 31.
' Gray code guarantees that each successive value differs by
' exactly one bit.
'
' Gray code formula:
' gray(n) = n Xor (n >> 1)
'
' The program prints the Gray‑code values themselves in the
' natural one‑bit‑change order: 0, 1, 3, 2, 6, 7, 5, 4, ...
'===========================================================
Module GrayCodeSequence1
' Convert an integer to a 5‑bit binary string
Function ToBits(value As Integer) As String
Dim result As String = ""
For i As Integer = 4 To 0 Step -1
If (value And (1 << i)) <> 0 Then
result &= "1"
Else
result &= "0"
End If
Next
Return result
End Function
' Print the Gray‑code sequence in one‑bit‑change order
Sub PrintGraySequence()
For n As Integer = 0 To 31
Dim g As Integer = n Xor (n >> 1) ' Gray‑code transformation
Console.WriteLine($"{g,2} -> {ToBits(g)}")
Next
End Sub
Sub Main()
PrintGraySequence()
End Sub
End Module
'run:
'
' 0 -> 00000
' 1 -> 00001
' 3 -> 00011
' 2 -> 00010
' 6 -> 00110
' 7 -> 00111
' 5 -> 00101
' 4 -> 00100
'12 -> 01100
'13 -> 01101
'15 -> 01111
'14 -> 01110
'10 -> 01010
'11 -> 01011
' 9 -> 01001
' 8 -> 01000
'24 -> 11000
'25 -> 11001
'27 -> 11011
'26 -> 11010
'30 -> 11110
'31 -> 11111
'29 -> 11101
'28 -> 11100
'20 -> 10100
'21 -> 10101
'23 -> 10111
'22 -> 10110
'18 -> 10010
'19 -> 10011
'17 -> 10001
'16 -> 10000
'