2

I am shuffleing a list in Kotlin & Python using the same seed but i am getting different sequence. Cod on Python and Kotlin is as follows:

Kotlin

var trainInput = arrayListOf<Int>(1,2,3,4,5)
val randomSeed = 1549786796.toLong()
trainInput.shuffle(Random(randomSeed))

Output: [1, 3, 5, 2, 4]

Python:

import numpy as np
arr = np.array([1,2,3,4,5])
np.random.seed(1549786796)
np.random.shuffle(arr)

Ouput: [3 2 4 1 5]

Can anyone please point out how can I get the same sequence on both platforms?

Thanks.

EDIT I have also checked the library java-random (https://pypi.org/project/java-random/) suggested by Stef but this only generates the random number. I need to shuffle the list that generates the same sequence.

Mustansar Saeed
  • 2,730
  • 2
  • 22
  • 46
  • Java and numpy use different random number generators, so why do you expect them to yield the same results? See https://stackoverflow.com/questions/11162798/generating-the-same-random-number-in-java-and-python and in particular https://pypi.org/project/java-random/ – Stef Jan 19 '21 at 08:04
  • @Stef: I am working on `Machine Learning` problem, I want to compare the results and for that to be the same, input sequence should have to be same. I was wondering, if I can get the same sequence. – Mustansar Saeed Jan 19 '21 at 08:06
  • 1
    so `java-random` (see link above) should be your friend :) – Stef Jan 19 '21 at 08:07
  • @Stef: `java-random` only generates the random number. I want to `shuffle` the list that generates the same sequence. – Mustansar Saeed Jan 19 '21 at 09:57
  • 1
    Implement some simple random number generator (e.g. https://stackoverflow.com/a/3062783/51685) in both languages and use it to power your Fisher-Yates shuffle implementation? – AKX Jan 19 '21 at 10:01
  • If you need the same input sequence, why not just make the input sequence the same? Forget about the randomisation. – voyager42 Jan 19 '21 at 13:12

1 Answers1

1

Combining Stef and AKX answer produces the desired output. i.e., using java-random package on Python side to produce the same random number using same seed and then applying Fisher-Yates algorithm produces the same sequence.

import numpy as np
import javarandom as jrandom

r = jrandom.Random(1549786796)

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])

def randomize(arr, n):
    # Start from the last element and swap one by one. We don't
    # need to run for the first element that's why i > 0
    for i in range(n - 1, 0, -1):
        # Pick a random index from 0 to i
        j = r.nextInt(i + 1)

        # Swap arr[i] with the element at random index
        arr[i], arr[j] = arr[j], arr[i]
    return arr

Output: [7 5 1 4 6 2 3 8]

The above output is same on Kotlin and Python.

Thank you.

Mustansar Saeed
  • 2,730
  • 2
  • 22
  • 46