I thought it'd be fun to try and make a mastermind game using microsoft excel.
So you choose a number, put it in A1, then set up a function like this:
=findmatchwrongpos(TEXT($A$1),TEXT(C1)
and your function would look something like this where we mark a "match" with an asterisk so it won't be counted again.
Function findmatchwrongpos(a, b As String) As Integer
For i = 1 To Len(a)
If Mid(a, i, 1) = Mid(b, i, 1) Then
correctposcount = correctposcount + 1
Mid(a, i, 1) = "*"
Mid(b, i, 1) = "*"
End If
Next i
For i = 1 To Len(a)
c = Mid(a, i, 1)
If c <> "*" Then
For j = 1 To Len(b)
If Mid(b, j, 1) = c Then
Mid(b, j, 1) = "*"
Mid(a, i, 1) = "*"
wrongposcount = wrongposcount + 1
Exit For
End If
Next j
End If
Next i
findmatchwrongpos = wrongposcount
End Function
And for debugging purposes, why not have a function that returns a variant type so you can see what's going on:
=findmatchitem(TEXT($A$1),TEXT(C1),1)
passing an item number so you can get different return items:
Function findmatchitem(a, b As String, item As Integer) As Variant
For i = 1 To Len(a)
If Mid(a, i, 1) = Mid(b, i, 1) Then
correctposcount = correctposcount + 1
Mid(a, i, 1) = "*"
Mid(b, i, 1) = "*"
End If
Next i
correcta = a
correctb = b
For i = 1 To Len(a)
c = Mid(a, i, 1)
If c <> "*" Then
For j = 1 To Len(b)
If Mid(b, j, 1) = c Then
Mid(b, j, 1) = "*"
Mid(a, i, 1) = "*"
wrongposcount = wrongposcount + 1
Exit For
End If
Next j
End If
Next i
If item = 1 Then
findmatchitem = correctposcount
ElseIf item = 2 Then
findmatchitem = wrongposcount
ElseIf item = 3 Then
findmatchitem = "CORRECT CHECK: " + correcta + "," + correctb
ElseIf item = 4 Then
findmatchitem = "WRONG CHECK: " + a + "," + b
End If
End Function
Maybe after this, I'll dig out a copy of Interplay's Learn to Program Basic and write mastermind in it.
No comments:
Post a Comment