gpt4 book ai didi

ios - 在 Swift 中打乱一个字符串

转载 作者:可可西里 更新时间:2023-10-31 23:57:14 25 4
gpt4 key购买 nike

我正在尝试使用 Swift 为 iPhone 创建一个字谜游戏。我对编程和 Swift 比较陌生,但之前曾用 Python 创建过这个游戏。

这是我的伪代码:

//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

到目前为止,这是我的代码:

导入 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)]

我的问题是我不知道如何从所选单词中删除所选字符。如果可以的话,我会简单地创建一个循环,在其中重复上述过程,直到原始单词为空

最佳答案

Swift 5 或更高版本

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"

关于ios - 在 Swift 中打乱一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27761557/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com