利用Swift语言特性,随手写个伪随机数生成器

利用Swift语言特性,随手写个伪随机数生成器,第1张

//
//  main.swift
//  Ultimate
//
//  Created by Mewlan Musajan on 2/13/22.
//
//  Apple Inc. “The Swift Programming Language (Swift 5.5).” Apple Books. https://books.apple.com/us/book/the-swift-programming-language-swift-5-4/id881256329

protocol RandomNumberGenerator {
    func random() -> Double
}

// Linear Congruential Generator
class LinearCongruentialGenerator: RandomNumberGenerator {
    var lastRandom = 42.0
    let m = 139968.0
    let a = 3877.0
    let c = 29573.0
    func random() -> Double {
        lastRandom = ((lastRandom * a + c)
                        .truncatingRemainder(dividingBy: m))
        return lastRandom / m
    }
}
let generator = LinearCongruentialGenerator()
print("Here's a random number: \(generator.random())")
print("And another one: \(generator.random())")

extension Int {
    func repetitions(task: () -> Void) {
        for _ in 0.. = []
8.repetitions {
    randomNumberSet.update(with: Int(generator.random() * 10))
}

8.repetitions {
    if var someNumber = randomNumberSet.popFirst() {
        if someNumber == 0 {
            someNumber = 1
        }
        print(someNumber, terminator: "")
    }
}
print()

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/993672.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存