Shuffle Algorithm

The Shuffle Algorithm, also known as the Fisher-Yates shuffle or the Knuth shuffle, is a widely-used method for generating a random permutation of a finite sequence of elements. This algorithm was first introduced by Ronald Fisher and Frank Yates in 1938, and was later popularized by Donald Knuth in his book "The Art of Computer Programming." The algorithm works by iterating through the sequence from the last element to the first, and at each step, swapping the current element with another randomly chosen element that comes before it (including the possibility of swapping with itself). By doing this, the algorithm ensures that each element in the sequence has an equal probability of ending up in any given position, thus creating a fair and unbiased shuffle. The Shuffle Algorithm has several advantageous properties, which make it suitable for various applications, such as shuffling a deck of cards in a card game, generating a random playlist of songs, or randomizing the order of questions in a quiz. The algorithm is efficient, as it requires only a single pass through the sequence with a time complexity of O(n), where n is the number of elements in the sequence. Additionally, the algorithm is easy to implement and can be adapted to work with different types of sequences and random number generators. Overall, the Shuffle Algorithm is a versatile and reliable method for achieving a random permutation of a finite sequence of elements, ensuring that randomness is introduced fairly and consistently in a wide range of applications.
/**
* Created by gazollajunior on 03/04/16.
*/
import java.util.Random
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
}
/* extension version */
fun <T> Iterable<T>.shuffle(): List<T> {
val list = this.toMutableList().apply { }
Collections.shuffle(list)
return list
}
fun main(args: Array<String>) {
println("\nOrdered list:")
val ordered = listOf<String>("Adam", "Clark", "John", "Tim", "Zack")
println(ordered)
println("\nshuffled list:")
val shuffled = shuffle(ordered as MutableList<String>)
print(shuffled)
val orderedB = listOf(1, 2, 3, 4, 5)
print(orderedB.shuffle())
}

LANGUAGE:

DARK MODE: