2017-05-06 70 views
-3

我希望函數能夠生成隨機字符串而不重複。 例如這個功能也許會打印:ABCC生成隨機字符串,無需重複快速

func randomString(length:Int) -> String { 
let charSet = "ABCDEF" 
var c = charSet.characters.map { String($0) } 
var s:String = "" 
for _ in (1...length) { 
    s.append(c[Int(arc4random()) % c.count]) 
} 
return s 
} print(randomString(length: 4)) 

,我想只打印隨機唯一的字符串,如:ABCD

+0

自從玩卡片遊戲?你有沒有聽說過「洗牌」這個概念?洗牌的人,並處理前四個。 – matt

+1

http://stackoverflow.com/questions/27761557/shuffling-a-string-in-swift(其中你的問題實際上只是一個副本) – matt

+0

或這一個:http://stackoverflow.com/questions/26845307/生成隨機字母數字字符串在迅速 – iWheelBuy

回答

0
func randomString(length: Int) -> String { 
    let charSet = "ABCDEF" 
    var charSetArray = charSet.characters.map { String($0) } 
    var randArray: [String] = [] 
    while charSetArray.count > 0 { 
     let i = Int(arc4random_uniform(UInt32(charSetArray.count))) 
     randArray.append(charSetArray[i]) 
     charSetArray.remove(at: i) 
    } 
    var output: String = "" 
    for i in 0..<length { 
     output.append(randArray[i]) 
    } 
    return output 
} 
1
import GameplayKit 

func randomString(length : Int) -> String { 
    let charSet = Array("ABCDEFGHIJKLMNOPQRSTUVWXYZ".characters) 
    let shuffled = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: charSet) as! [Character] 
    let array = shuffled.prefix(length) 
    return String(array) 
} 

print(randomString(length: 4)) 
+0

重複的字符可能與您的答案 – iWheelBuy

+0

以什麼方式?這組字符被混洗。沒有一個是重複的。第一個'長度'項目是從混洗陣列的前部取得的。集合中的字符在哪裏可以重複? –

+0

數組(「ABCA」.characters) – iWheelBuy

0

如何使用:

let randomString = "ABCDEF".random(length: 3)! 

返回值是可選的,因爲該長度可能超過提供的字符串的長度。

退房全面實施:

import UIKit 
import PlaygroundSupport 

extension MutableCollection where Indices.Iterator.Element == Index { 
    mutating func shuffle() { 
     let c = count 
     guard c > 1 else { return } 
     for (firstUnshuffled , unshuffledCount) in zip(indices, stride(from: c, to: 1, by: -1)) { 
      let d: IndexDistance = numericCast(arc4random_uniform(numericCast(unshuffledCount))) 
      guard d != 0 else { continue } 
      let i = index(firstUnshuffled, offsetBy: d) 
      swap(&self[firstUnshuffled], &self[i]) 
     } 
    } 
} 

extension Sequence { 
    func shuffled() -> [Iterator.Element] { 
     var result = Array(self) 
     result.shuffle() 
     return result 
    } 
} 

extension String { 

    func random(length: Int) -> String? { 
     let uniqueCharacters = Array(Set(characters.map({ String($0) }))) 
     guard length <= uniqueCharacters.count else { return nil } 
     guard length > 0 else { return nil } 
     return uniqueCharacters[0..<length].shuffled().joined() 
    } 
}