Create random asterisks for specific word

YasserKhalil
PlatinumLounger
Posts: 4911
Joined: 31 Aug 2016, 09:02

Create random asterisks for specific word

Post by YasserKhalil »

Hello everyone
I am trying to create a puzzle (which is simply is a word with some missing letters) and the students have to complete the missing letters.
Suppose I have the word "Hello World" .. and starting in column G, I need to put each letter in the column so "H" letter would be in column G and "e" letter would be in column H and the letter "l" would be in column I and so on for the rest of letters
Untitled.png
Then I need to create asterisk in some cells randomly "*" instead of the letters that the students have to enter. The number of asterisks would be in percent according to the length of the word. I mean I need to specify the number of asterisks by 25 % of the total length of the word
Example "Hello World" would be 11 so 25 % 11 equals to about 2.7 (raised to 3)
so randomly put three asterisks in the cells (in a random way) like that and I don't need to include the space which is the empty cell for putting the asterisk.
2.png
You do not have the required permissions to view the files attached to this post.

User avatar
HansV
Administrator
Posts: 78237
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Create random asterisks for specific word

Post by HansV »

Code: Select all

Sub Test()
    Asterisks "Hello World"
End Sub

Sub Asterisks(ByVal s As String)
    Dim n As Long
    Dim m As Long
    Dim p() As Long
    Dim i As Long
    Dim j As Long
    Dim k As Long
    Dim l As Long
    Dim t As Long
    n = Len(s)
    m = Round(0.25 * n, 0)
    ' Create array of positions excluding spaces
    For i = 1 To n
        If Mid(s, i, 1) <> " " Then
            j = j + 1
            ReDim Preserve p(1 To j)
            p(j) = i
        End If
    Next i
    ' Shuffle 5 times
    For i = 1 To 5
        For k = 1 To j
            l = Application.RandBetween(1, j)
            t = p(k)
            p(k) = p(l)
            p(l) = t
        Next k
    Next i
    ' Place asterisks
    For i = 1 To m
        Mid(s, p(i), 1) = "*"
    Next i
    ' Fill cells
    For i = 1 To n
        Cells(1, 6 + i).Value = Mid(s, i, 1)
    Next i
End Sub
Best wishes,
Hans

YasserKhalil
PlatinumLounger
Posts: 4911
Joined: 31 Aug 2016, 09:02

Re: Create random asterisks for specific word

Post by YasserKhalil »

Amazing my tutor. That's exactly what I needed.
Thank you very much for awesome help all the time.