prettyprint

2015年9月21日 星期一

Random Generator 亂數產生器


在 Apple 的官方網站 [1]上描述 arc4random_uniform() 這亂數產生器:

u_int32_t arc4random_uniform(u_int32_t upper_bound);

arc4random_uniform() 
will return a uniformly distributed random number less than upper_bound.

arc4random_uniform() 
is recommended over constructions like ``arc4random() % upper_bound'' as it avoids
"modulo bias" when the upper bound is not a power of two.
程式:

//
//  ViewController.swift
//  RandomGeneratorDemo
//
//  Created by Elvis Meng on 2015/9/21.
//  Copyright © 2015年 Elvis Meng. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let n:UInt32 = UInt32(arc4random_uniform(100)+1)
        print("n = \(n)")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
測試:
參考: 1. ARC4RANDOM(3), https://developer.apple.com/library/prerelease/mac/documentation/Darwin/Reference/ManPages/man3/arc4random_uniform.3.html

沒有留言:

張貼留言

prettyPrint();