gpt4 book ai didi

arrays - 如何更好地使用repeat while循环进行索引和数组

转载 作者:行者123 更新时间:2023-11-30 12:28:54 25 4
gpt4 key购买 nike

我想从给定数组中随机选择一个 KanjiCard 结构体项目,将属性“kanji”添加到另一个临时数组中并执行检查,如果随机选择的 struct.kanji 存在于 yetShowedArray 中> 重复随机选择,直到找到 yetShowedArray 中不存在汉字的结构才能使用它

实际的重复/同时流程并不能保证它会发生。

//test for the not repeating run *************************************************************************************

//check if the two array have the same number of items
guard arrayToUse.count != yetShowedArray.count else {
print("finished all the kanji")
var matching = 0
for element in arrayToUse {
if yetShowedArray.contains(element.kanji!){
matching += 1
}
}
print("matching kanji are : \(matching)")
return
}

var random = Int(arc4random_uniform(UInt32(arrayToUse.count)))

//Instance
kanjiToShow = arrayToUse[random]
guard let kanjiToTrack = kanjiToShow.kanji else {
print("kanjiToTrack is nil!!!")
return
}


if yetShowedArray.contains(kanjiToTrack){
print("contained")

repeat {
random = Int(arc4random_uniform(UInt32(arrayToUse.count)))
kanjiToShow = arrayToUse[random]

} while yetShowedArray.contains(kanjiToTrack)
print("refreshed random")

}
else {
print("never used before")
}

yetShowedArray.append(kanjiToTrack)
print(yetShowedArray)

print("arrayToUse: \(arrayToUse.count) yetShowedArray: \(yetShowedArray.count)")

//test for the not repeating run *************************************************************************************

解决方案

在 Anton Novoselov 的回答后找到

我将 let kanjiToTrack 更改为 var,然后在重复循环内刷新它

//Instance
kanjiToShow = arrayToUse[random]
guard var kanjiToTrack = kanjiToShow.kanji else {
print("kanjiToTrack is nil!!!")
return
}


if yetShowedArray.contains(kanjiToTrack){
print("contained")

repeat {
random = Int(arc4random_uniform(UInt32(arrayToUse.count)))
kanjiToShow = arrayToUse[random]
kanjiToTrack = kanjiToShow.kanji!


} while yetShowedArray.contains(kanjiToTrack)

print("refreshed random")

}
else {
print("never used before")
}

第二种解决方案

let random = Int(arc4random_uniform(UInt32(arrayToUse.count)))

//Instance
kanjiToShow = arrayToUse[random]
guard kanjiToShow.kanji != nil else {
print("kanjiToTrack is nil!!!")
return
}

arrayToUse.remove(at: random)

最佳答案

尝试在重复循环内再次刷新 kanjiToTrack。正如您所说,它是结构-值类型,因此您似乎在 while 子句中检查相同的 kanjiToTrack 。试试这个:

       repeat {
random = Int(arc4random_uniform(UInt32(arrayToUse.count)))
kanjiToShow = arrayToUse[random]
guard let kanjiToTrack = kanjiToShow.kanji else {return}


} while yetShowedArray.contains(kanjiToTrack)

关于arrays - 如何更好地使用repeat while循环进行索引和数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43829112/

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