Skip to content

Shuffle isn't correct #14

@niyaznigmatullin

Description

@niyaznigmatullin
fun <T:Comparable<T>>shuffle(items:MutableList<T>):List<T>{
    val rg : Random = Random()
    for (i in 0..items.size - 1) {
        val randomPosition = rg.nextInt(items.size)
        val tmp : T = items[i]
        items[i] = items[randomPosition]
        items[randomPosition] = tmp
    }
    return items
}

This algorithm doesn't shuffle it correctly, not every permutation is equiprobable. You have to do:

val randomPosition = rg.nextInt(i + 1)

to fix it.

More information:
https://blog.codinghorror.com/the-danger-of-naivete/

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions