当前位置:网站首页>Using swift language features, write a pseudo-random number generator casually
Using swift language features, write a pseudo-random number generator casually
2022-07-03 12:38:00 【iWillook】
//
// 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..<self {
task()
}
}
}
5.repetitions {
print(generator.random())
}
var randomNumberSet: Set<Int> = []
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()
边栏推荐
猜你喜欢
Self made pop-up input box, input text, and click to complete the event.
剑指Offer03. 数组中重复的数字【简单】
1-2 project technology selection and structure
Record your vulnhub breakthrough record
阿里 & 蚂蚁自研 IDE
Sword finger offer10- I. Fibonacci sequence
[download attached] password acquisition tool lazagne installation and use
Sword finger offer07 Rebuild binary tree
Sword finger offer09 Implementing queues with two stacks
LeetCode 0556. Next bigger element III - end of step 4
随机推荐
Self made pop-up input box, input text, and click to complete the event.
The solution to change the USB flash disk into a space of only 2m
Introduction to concurrent programming (II)
ImportError: No module named examples. tutorials. mnist
Wechat applet - basic content
剑指Offer06. 从尾到头打印链表
elastic_ L04_ introduction. md
Take you to the installation and simple use tutorial of the deveco studio compiler of harmonyos to create and run Hello world?
剑指Offer03. 数组中重复的数字【简单】
2.9 overview of databinding knowledge points
Nodejs+Express+MySQL实现登陆功能(含验证码)
社交社区论坛APP超高颜值UI界面
最新版盲盒商城thinkphp+uniapp
Airflow installation jump pit
repo Manifest Format
Keep learning swift
347. Top k high frequency elements
2020-11_ Technical experience set
在网上炒股开户可以吗?资金安全吗?
Apache Mina开发手册