Dennis van Mazijk Dennis van Mazijk - 5 months ago 26
Swift Question

Swift: Generate a set of (X) random 6 character substrings

I am trying to generate 5 random substrings of six characters each from the alphabet. For example: ABCDEF, RSTUVW, UVWXYZ, etc. These substrings can be duplicates, so generating ABCDEF twice is a not a problem.

When I have these 5 substrings, I want to generate five arrays containing three characters. One of these characters should be the last letter of the substring and the other two letters should be two random unique letters from the entire alphabet.


Get five random substrings:

For [ABCDEF] the system could generate [F, H, S] and for [RSTUVW] it could generate [K, Q, W]. As you can see, the three-character arrays always contain the last letter of its substring and two other randomised unique letters.

The above is part of a game for kids to practice the order of the alphabet. In order to generate possible answers I actually need small sets of characters to assign to buttons.

What do you think is the best way to approach this?


Thanks to @vacawama here's a possible solution.

1. Create the alphabet

let alphabet = Array("ABCDEFGHIJKLMNOPQRSTUVWXYZ".characters)

2. Create the 6 "sequences"

let sequences = (0..<5).map { _ -> String in
    let startIndex = Int(arc4random_uniform(UInt32(alphabet.count - 5)))
    let endIndex = startIndex + 5
    return String(alphabet[startIndex...endIndex])


3. Get the last char for each sequence

let lastChars = sequences.flatMap { $0.characters.last }

["U", "I", "O", "H", "P"]

4. Build 5 elms

Here's the code snippet

let elms = { char0 -> String in
    var tempAlphabet = alphabet
    let index1 = Int(arc4random_uniform(UInt32(tempAlphabet.count)))
    let char1 = tempAlphabet.removeAtIndex(index1)
    let index2 = Int(arc4random_uniform(UInt32(tempAlphabet.count)))
    let char2 = tempAlphabet[index2]
    return String(Array(Set<Character>([char0, char1, char2])))

["DUN", "ZIQ", "ROP", "HSW", "PGS"]