生成随机的字符串而不会重新排列和重复先前的字符串吗? [英] Generate random Strings without a shuffle and repetition of previous ones?

查看:90
本文介绍了生成随机的字符串而不会重新排列和重复先前的字符串吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我按下按钮时,我的代码已经生成了一个随机的数组字符串,但是有时会重复出现一个字符串.我该怎么做,以使仅在所有其他字符串都已调用但不使用随机播放的情况下才再次调用字符串"Mango",而我想一次调用一个String?

My code already generates a random String of an array when I press a button, but sometimes a String gets repeated. What do I have to do so that the String "Mango" only gets called again when all the other Strings where already called without using a shuffle, I want to call one String at a time?

示例:芒果",猕猴桃",香蕉",菠萝",瓜",芒果",猕猴桃",.....

Example: "Mango", "Kiwi", "Banana", "Pineapple", "Melon", "Mango", "Kiwi",.....

这是我的代码:

var array = ["Mango", "Banana", "Apple","Kiwi", "Melon", "Pineapple"]

let fruits = Int(arc4random_uniform(UInt32(array.count)))

print(array[fruits])

推荐答案

为避免重复,您需要跟踪以前看到过哪些水果.有多种方法可以使所有建议的解决方案以一种或另一种方式完成.

In order to avoid repetitions you need to keep track of which fruits have previously been seen. There are several ways to do that an all of the proposed solutions do it in one way or another.

对于您的特定用例,您将需要将此跟踪保留在按钮执行的代码之外(例如,在视图控制器中).

For your specific use case, you will need this tracking to be retained outside of the code executed by the button (in your view controller for example).

这是一个通用的结构,可以帮助解决这个问题:(如果这是一次性的,则可以在视图控制器中定义;如果要在其他地方重用该机制,则可以在视图控制器之外定义)

Here is a generalized structure that could help with this: (you can define it inside the view controller if this is a one-time thing or outside of it if you intend to reuse the mechanism elsewhere)

struct RandomItems
{
   var items : [String]
   var seen  = 0

   init(_ items:[String])
   { self.items = items }

   mutating func next() -> String
   {
     let index = Int(arc4random_uniform(UInt32(items.count - seen)))
     let item  = items.remove(at:index)
     items.append(item)
     seen = (seen + 1) % items.count
     return item
   }
}

要使用它,您需要在VC中声明一个变量,以跟踪您的成果:

To use it, you would declare a variable (in your VC) that will keep track of your fruits:

var fruits = RandomItems(["Mango", "Banana", "Apple","Kiwi", "Melon", "Pineapple"])

在按钮的代码中,使用该变量(水果)在每次执行时打印不重复的水果名称

And in the button's code use that variable (fruits) to print a non-repeating fruit name at each execution

func buttonPressed() // <- use your function here
{
    print( fruits.next() )
}

这篇关于生成随机的字符串而不会重新排列和重复先前的字符串吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆