IOS Swift: looking for a cross compatible method to Java’s Random() PRNG that has identical output

Here’s my delimna: I am writing an application that needs to exactly reproduce the PRNG output from a game that was written in Java that uses the Java random() with a given seed to create all it’s initial game ‘world’ data.

The problem I am facing is that Java’s random() and ios Swift native PRNG do not generate the same values when given the exact same seeds.

Here are my test cases: In all cases the same ‘seed’ is used, and the formula is for a random Integer between 0 and 9.


In Java:

import java.util.Random;
long seed = 987234904; 
Random rnd = new Random(seed); 
int result = rnd.nextInt(10);

The Java random() ‘result’ = 0


Swift – using srand48() / drand48():

import UIKit 
var seed: Int = 987234904 
var result = Int(drand48()*10)

The ios Swift drand48() ‘result’ = 7


In Swift – using rand_r():

import UIKit 
var seed: UInt32 = 987234904 
var result = Int(Float(rand_r(&seed))/Float(INT32_MAX)*10)

The ios Swift rand_r() result = 4


In Swift – using the new GKLinearCongruentialRandomSource – which uses a simular Linear Congruential method that Java.util.random() was based on – suposedly:

import UIKit 
import GameplayKit 
if #available (iOS 9,*) { 
   let seed: UInt64 = 987234904 
   let random = GKLinearCongruentialRandomSource(seed: seed) 
   let result = random.nextIntWithUpperBound(10) // should be a random Int from 0 to 9 (total 10 possibilities }

result = 6


With that in mind – is there a ios Swift|Objective-C|C++ code snippit|library available that is the exact same in functionality and output as the Java’s version of random()?

Powered by WPeMatico

You may also like...

Comments are closed.