Golang. Fisher-Yates algorithm


The user enters any number, letter, word, or whatever he wants, separated by a space. Let’s say he even enters card values (poker hand), such as A 3 J Q 10. Our job is to shuffle these cards.

To do this, it’s cool (and easy) to use the Fisher-Yates Algorithm. This algorithm works by iterating the array starting with the last element, and replacing the current element with a randomly chosen element. The process is repeated until the first element is reached. The result is a randomly shuffled array.

Here is my fiddly code for this “shuffle.”

package main

import (
	"bufio"
	"fmt"
	"math/rand"
	"os"
	"strings"
	"time"
)

func main() {

	r := bufio.NewReader(os.Stdin)

	s, _ := r.ReadString('\n')

	s = strings.TrimSpace(s)

	parsed := strings.Fields(s)

	len := len(parsed)

	rand.Seed(time.Now().UnixNano())

	for i := len - 1; i > 0; i-- {
		j := rand.Intn(i)
		parsed[i], parsed[j] = parsed[j], parsed[i]
	}

	fmt.Print(parsed)
}

Explanation:

In the main function, the program creates a new reader object to read input from the user, and then uses that object to read a string of words entered by the user. The program then removes extra spaces and splits the string into individual words.

Next, the program creates a variable len, which stores the number of words in the list. It then uses the rand.Seed function to run the random number generator so that it generates a different random number each time the loop is run. The loop, which will run as many times as there are words in the list. At each iteration of the loop, the program generates a random number between 0 and the current value of loop variable i and assigns it to variable j. Then it swaps the word at position i with the word at position j in the list.

Finally, the program prints the shuffled word list for the user to view. The Fisher-Yates permutation algorithm ensures that every possible ordering of the list is equally likely.


This entry was posted in Go (en). Bookmark the permalink.

Leave a Reply

🇬🇧 Attention! Comments with URLs/email are not allowed.
🇷🇺 Комментарии со ссылками/email удаляются автоматически.