1

I'm building an app for both Android and iOS. In the app, I need to generate psuedorandom numbers that match in both the iOS version and the Android version. I'be seen many implementations of custom random number generators but some are in C++ or PHP... I only know Java and Swift. Can someone help me and point me to a random generator that would work on both iOS and Android or can someone tell em the steps on how to create my own random number generator?

Edit: By 'match' I meant that I need to be able to seed it so that it will produce the same output every single time.

Erosion
  • 21
  • 3

2 Answers2

0
randomValue = arc4random() % 255;

Generate Randome Value between 0 to 255 On iOS

Gaurav Patel
  • 532
  • 1
  • 5
  • 19
0

I'm interpreting "match" to mean you'd like the iOS and Android implementations to yield the same sequence of values if seeded identically. You can do this using a standard implementation of Mersenne Twister, mt19937. Apple has an implementation available in Swift via GameplayKit. You can confirm its behavior and replicability in a Playground:

import GameplayKit

let source = GKMersenneTwisterRandomSource(seed: 123)
source.nextUniform()               // => 0.3132002
source.nextUniform()               // => 0.5559791
source.nextIntWithUpperBound(20)   // => 13

let source2 = GKMersenneTwisterRandomSource(seed: 123)
source2.nextUniform()              // => 0.3132002
source2.nextUniform()              // => 0.5559791
source2.nextIntWithUpperBound(20)  // => 13

According to Apple's documentation,

...if you initialize a GKMersenneTwisterRandomSource instance and a compatible implementation using the same seed value, both generate the same sequence of numbers.

I'm reading that to say it should produce a "match" with a C++ or Java reference implementation, source for which can be downloaded from the mt19937 site linked above.


ADDENDUM

It looks like the GameplayKit implementation gives reproducible results, but the output is not consistent with the reference implementation from Hiroshima. Here's a port to Swift that I did a couple of years ago of the standard C implementation for mt19937. This produces identical outcomes as the C reference implementation when seeded identically. So does the Java port available at the link provided earlier, so this should give you a solution which is consistent across platforms.

pjs
  • 18,696
  • 4
  • 27
  • 56