在 Kotlin 和 Python 上获得相同的洗牌顺序
Get same sequence of shuffle on Kotlin and Python
我正在 shuffle
ing list
in Kotlin
& Python
使用相同的 seed
但我得到不同的序列。 Python 和 Kotlin 上的 Cod 如下:
Kotlin
var trainInput = arrayListOf<Int>(1,2,3,4,5)
val randomSeed = 1549786796.toLong()
trainInput.shuffle(Random(randomSeed))
输出:
[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)
输出: [3 2 4 1 5]
任何人都可以指出如何在两个平台上获得相同的序列吗?
谢谢。
编辑
我还检查了 Stef 建议的库 java-random
(https://pypi.org/project/java-random/),但这只会生成随机数。我需要 shuffle
生成相同序列的列表。
结合 Stef 和 AKX answer 产生所需的输出。即,在 Python 端使用 java-random
包使用相同的 seed
产生相同的随机数,然后应用 Fisher-Yates
算法产生相同的序列。
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
输出:[7 5 1 4 6 2 3 8]
以上输出在 Kotlin 和 Python 上相同。
谢谢。
我正在 shuffle
ing list
in Kotlin
& Python
使用相同的 seed
但我得到不同的序列。 Python 和 Kotlin 上的 Cod 如下:
Kotlin
var trainInput = arrayListOf<Int>(1,2,3,4,5)
val randomSeed = 1549786796.toLong()
trainInput.shuffle(Random(randomSeed))
输出: [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)
输出: [3 2 4 1 5]
任何人都可以指出如何在两个平台上获得相同的序列吗?
谢谢。
编辑
我还检查了 Stef 建议的库 java-random
(https://pypi.org/project/java-random/),但这只会生成随机数。我需要 shuffle
生成相同序列的列表。
结合 Stef 和 AKX answer 产生所需的输出。即,在 Python 端使用 java-random
包使用相同的 seed
产生相同的随机数,然后应用 Fisher-Yates
算法产生相同的序列。
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
输出:[7 5 1 4 6 2 3 8]
以上输出在 Kotlin 和 Python 上相同。
谢谢。