Swift for Xojo™ Developers (cont’d) : RANDOM

Here is a Swift class that replicates the RANDOM class from Xojo™
note : some “functions” have become read-only computed variables

this will be incorporated in my larger “SYSTEM” class soon

//
//  dsRANDOM.swift
//  SwiftTemplate
//
//  Created by David Sisemore on 2/26/22.
//

import Foundation

public func rnd() -> CGFloat {
  return CGFloat(arc4random()) /  CGFloat(UInt32.max)
}

public class random : NSObject {
  private var zSeed : Int = 0
  var s : Double = 0.0
  var v2 : Double = 0.0
  var cachedNumberExists = false
  convenience override init() {
    self.init()
    self.seed=Int(Date().timeIntervalSince1970)
  }
  public var seed : Int {
    get { return zSeed }
    set { zSeed = newValue; srand48(zSeed) }
  }

  public func randomizeSeed() {
    self.seed=Int(Date().timeIntervalSince1970)
    self.seed=Int(self.lessThan(1000000))
  }

  // returns value from 0 to 1
  public var number : Double { return drand48() }

  public func inRange(_ minR: Int,_ maxR:Int) -> Int {
    let minD:CGFloat=CGFloat(minR)
    let maxD:CGFloat=CGFloat(maxR)
    return Int(((maxD-minD)*number) + 0.5)
  }

  public func lessThan(_ range:Int) -> Int {
    return inRange(0,range)
  }

  public var gaussian : Double {
    var u1, u2, v1, x : Double
    if !cachedNumberExists {
      repeat {
        u1 = Double(arc4random()) / Double(UINT32_MAX)
        u2 = Double(arc4random()) / Double(UINT32_MAX)
        v1 = 2 * u1 - 1;
        v2 = 2 * u2 - 1;
        s = v1 * v1 + v2 * v2;
      } while (s >= 1 || s == 0)
      x = v1 * sqrt(-2 * log(s) / s);
    }
    else {
      x = v2 * sqrt(-2 * log(s) / s);
    }
    cachedNumberExists = !cachedNumberExists
    return x
  }
}
2 Likes