Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shuffling a string in Swift

Tags:

ios

swift

I'm trying to create a word jumbler game for the iPhone using Swift. I'm relatively new to programming and Swift, but have created this game in Python previously.

Here is my pseudo-code:

//select RANDOM WORD from array

//determine the number of characters in the RANDOMLY SELECTED WORD

//randomly select a NUMBER within the boundries of the number of characters (i.e. if the word is "apple," select a number between 0 and 4)

//select the CHARACTER that corresponds to the randomly selected NUMBER

//add the CHARACTER to a new string (JUMBLE)

//remove the CHARCATER from the RANDOMLY SELECTED WORD

//Repeat until the RANDOM WORD is empty

Here is my code so far:

import UIKit

//this is my array/word bank
var words = ["Apple", "Orange", "Pear"]

//this selects a random word in the array
var selectedWord = words[Int(arc4random_uniform(UInt32(words.count)))]

//this counts the number of characters in the string
var length = (countElements(selectedWord))

//this randomly selects a position within the string
var position = Int(arc4random_uniform(UInt32(length)))

//this creates a new string consiting of the letter found in the position from the previous line of code
var subString = selectedWord[advance(selectedWord.startIndex, position)]

My issues is that I cannot figure out how to remove the selected character from the selected word. If I could, I'd simply create a loop where I repeat the process above until the original word is empty

like image 664
Gabe Levin Avatar asked Oct 21 '25 03:10

Gabe Levin


1 Answers

Swift 5 or later

extension RangeReplaceableCollection  { 
    /// Returns a new collection containing this collection shuffled
    var shuffled: Self {
        var elements = self
        return elements.shuffleInPlace()
    }
    /// Shuffles this collection in place
    @discardableResult
    mutating func shuffleInPlace() -> Self  {
        indices.forEach {
            let subSequence = self[$0...$0]
            let index = indices.randomElement()!
            replaceSubrange($0...$0, with: self[index...index])
            replaceSubrange(index...index, with: subSequence)
        }
        return self
    }
    func choose(_ n: Int) -> SubSequence { return shuffled.prefix(n) }
}

let words = ["python", "jumble", "easy", "difficult", "answer", "xylophone"]

let randomWordShuffled = words.randomElement()?.shuffled ?? "" // "jmeblu"
like image 177
Leo Dabus Avatar answered Oct 23 '25 17:10

Leo Dabus