Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Created July 9, 2016 09:01
Show Gist options
  • Save KentarouKanno/115133299e07c1f146181acecf5fdc68 to your computer and use it in GitHub Desktop.
Save KentarouKanno/115133299e07c1f146181acecf5fdc68 to your computer and use it in GitHub Desktop.
Swift Algorithm

Swift Algorithm

★ 確率に準じて配列からランダムに抽出する

// firstが10%, secondが20%, thirdが70%の確率
let array = [["text": "first","per": 10],["text": "second","per": 20],["text": "third","per": 70]]


do {
    
    var target = Int(arc4random_uniform(100) + 1)
    
    let result = array.reduce("") { (str, value) -> String in
        
        if !str.isEmpty {
            return str
        }
        
        if let val = value["per"] as? Int where target >= val {
            target -= val
            return str
        } else {
            return value["text"] as! String
        }
    }
}

var target = Int(arc4random_uniform(100) + 1)

let result = array.reduce("") { (str, value) -> String in
    
    if !str.isEmpty {
        return str
    }
    
    if let val = value["per"] as? Int where target >= val {
        target -= val
        return str
    } else {
        return value["text"] as! String
    }
}


var results: [String] = []

for i in 0...99 {
    
    var target = Int(arc4random_uniform(100) + 1)
    
    let result = array.reduce("") { (str, value) -> String in
        
        if !str.isEmpty {
            return str
        }
        
        if let val = value["per"] as? Int where target >= val {
            
            target -= val
            return str
        } else {
            
            switch value["text"] as! String {
            case "first":
                return "first"
            case "second":
                return "second"
            case "third":
                return "third"
            default: ()
            }
        }
        
        print("abc")
        return str
    }
    
    results.append(result)
}
results.count
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment