Generating unique random values with SecureRandom

563 Views Asked by At

i'm currently implementing a secret sharing scheme.(shamir) In order to generate some secret shares, I need to generate some random numbers within a range. FOr this purpose, I have this very simple code:

val sharesPRG = SecureRandom()
fun generateShares(k :Int): List<Pair<BigDecimal,BigDecimal>> {
 val xs = IntArray(k){ i  -> sharesPRG.nextInt(5)}
 return xs
 }

I have left out the part that actually creates the shares as coordinates, just to make it reproduceable, and picked an arbitrarily small bound of 5. My problem is that I of course need these shares to be unique, it doesnt make sense to have shares that are the same. So would it be possible for the Securerandom.nextint to not return a value that it has already returned? Of course I could do some logic where I was checking for duplicates, but I really thought there should be something more elegant

1

There are 1 best solutions below

0
David Soroko On BEST ANSWER

If your k is not too large you can keep adding random values to a set until it reaches size k:


fun generateMaterial(k: Int): Set<Int> = mutableSetOf<Int>().also {
    while (it.size < k) {
        it.add(sharesPRG.nextInt(50))
    }
}

You can then use the set as the source material to your list of pairs (k needs to be even):

fun main() {
    val pairList = generateMaterial(10).windowed(2, 2).map { it[0] to it[1] }
    println(pairList)
}