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
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With