Last active
June 13, 2017 22:25
-
-
Save lion4ik/f5114fa2aef75bcd36d32ea57ac48e2c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.security.SecureRandom | |
/** | |
* Created by alexeypushkarev on 04.06.17. | |
*/ | |
fun randomArrayOfUniques(size: Int, maxValue: Int): List<Int> { | |
if (size > maxValue) { | |
throw IllegalArgumentException("maxValue should be greater than size") | |
} | |
val generatedList = mutableListOf<Int>() | |
val generatedArray = IntArray(size, { i -> generateUnique(generatedList, maxValue) }) | |
return generatedArray.toList() | |
} | |
fun generateUnique(alreadyUsedValues: MutableList<Int>, maxVal: Int): Int { | |
val random: SecureRandom = SecureRandom.getInstance("SHA1PRNG") | |
var rnd: Int = random.nextInt(maxVal) | |
while (alreadyUsedValues.contains(rnd)) { | |
rnd = random.nextInt(maxVal) | |
} | |
alreadyUsedValues.add(rnd) | |
return rnd | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment