How can I check in Visual Basic if string has dupl

2019-08-12 03:56发布

I'm making Bulls And Cows game and I want to randomly generate a number with four different digits.

Randomize()
Do
    Random = Int(9000 * Rnd()) + 1000
    'If (hasDupes = True)
    randomTwo = Random
    For i = 0 To randomTwo.Length - 1
        For j = 0 To randomTwo.Length - 1
            If randomTwo(i) = randomTwo(j) Then
                dupes = False
                Exit For
            End If
        Next
    Next
Loop Until dupes = True

^ That's what I have so far but it ain't working. Is there any function how I can find if there are duplicate characters or where is my mistake ?

2条回答
来,给爷笑一个
2楼-- · 2019-08-12 04:04

Here my implementation

Dim sResult As String  
Dim iCnt As Integer  
Dim iTmp As Integer  

iCnt = 0
Do While iCnt < 4
    iTmp = Int(10 * Rnd())
    If InStr(sResult, CStr(iTmp)) = 0 and not (iCnt = 0 and iTmp = 0) Then
        sResult = sResult & CStr(iTmp)
        iCnt = iCnt + 1
    End If
Loop

Debug.Print sResult

EDIT: Additional check first number must be > 0 after reading RLH comment

查看更多
甜甜的少女心
3楼-- · 2019-08-12 04:28

This will return four unique numbers.

Sub unique4()
Dim n(1 To 4) As Integer
Dim i As Integer
Dim t As Integer
Dim hr as Boolean

n(1) = 9 * Rnd()
i = 2
Do
    hr = False
    n(i) = 9 * Rnd()
    For t = 1 To i - 1
        If n(t) = n(i) Then
            hr = True
            Exit For
        End If
    Next t
    If Not hr Then
        i = i + 1
    End If
Loop While i < 5

Debug.Print n(1) & n(2) & n(3) & n(4)

End Sub
查看更多
登录 后发表回答