图a为初始状态,操作圈中的灯,则该灯与对面的两盏灯都会切换“开/关”状态,如图b所示。假设这些灯的编号为0到6号,“开/关”状态随机产生,并输出到列表框List1中,接着需要从中选出数盏灯进行操作,使得最后所有灯都打开(已证明方案-一定存在且唯一), 并在列表框List2中输出灯的编号。
程序采用枚举策略,一一尝试对每盏灯状态进行“切换”操作,“1”表示对当前灯进行切换,“0”表示不操作。
程序运行界面如图c所示。
Dim a(0 To 6)As Integer,b(0 To 6) As Integer
Private Sub Command1_Click()
Dim i As Integer, x As Integer, pos As Integer
Dim flag As Boolean
List2.Clear
For i = 0 To
x = i:pos = 0:flag = True
For j = 0 To 6
b(j)= a(j)
Next j
Do While x > 0
If x Mod 2 = 1 Then
b(pos)= 1 - b(pos)
b((pos + 3) Mod 7) = 1 – b((pos + 3) Mod 7)
End If
pos = pos + 1
x = x \ 2
Loop
For j = 0 To 6
IfThen flag = False:Exit For
Next j
If flag Then
pos = 0
Do While i > 0
If i Mod 2 = 1 Then List2.AddItem “第” + CStr(pos)+ “号”
i = i \ 2
pos = pos + 1
Loop
Exit For
End If
Next i
End Sub
Private Sub Form_Load() ‘随机生成初始数据
Dim i As Integer
Randomize
List1.Clear
For i = 0 To 6
a(i)= Int(Rnd * 2)
If a(i)= 1 Then
List1.AddItem “第” + CStr(i) + “号:”+ “开”
Else
List1.AddItem “第” + CStr(i) + “号:” + “关”
End If
Next i
End Sub