Shuffle an array in golang

Go program for Shuffle the elements of array. Here problem description and explanation.

package main
import "math/rand"
import "fmt"
import "time"
/*
  Go program for
  Shuffle the array elements
*/

// Function which is swapping two array elements 
// of given location.
func swapElement(arr[] int, i int, j int) {
	// Get i location element
	var temp int = arr[i]
	// Set new values
	arr[i] = arr[j]
	arr[j] = temp
}
// Returns the random location of array elements
func randomLocation(min, max int) int {
	// Calculate random number between given range
	return rand.Intn(max+1 - min) + min
}
// Function which is shuffle given array elements
func shuffleElement(arr[] int, size int) {
	// (i,j) indicate locations
	var j int = 0
	var i int = 0
	// Variable which is controlling the 
	// execution process of loop
	var counter int = 0
	// Loop which is shuffling random elements in array
	for (counter < size) {
		// Get random location of array index
		i = randomLocation(0, size - 1)
		j = randomLocation(0, size - 1)
		if i != j {
			// Swap array elements
			swapElement(arr, i, j)
			counter++
		}
	}
}
// Function which is display array elements
func display(arr[] int, size int) {
	for i := 0 ; i < size ; i++ {
		// Disply element value
		fmt.Print("  ", arr[i])
	}
	fmt.Print("\n")
}
func main() {
	rand.Seed(time.Now().UnixNano())
	// Define array of integer elements
	var arr = [] int {1, 0, -3, 8, 7, 3, 
		9, 4, 2, 5, 10, 6}
	var size int = len(arr)
	// Before shuffling  array elements
	fmt.Println(" Initial array elements")
	display(arr, size)
	fmt.Println(" After Shuffle array elements")
	shuffleElement(arr, size)
	display(arr, size)
	shuffleElement(arr, size)
	display(arr, size)
	shuffleElement(arr, size)
	display(arr, size)
}

Output

 Initial array elements
  1  0  -3  8  7  3  9  4  2  5  10  6
 After Shuffle array elements
  0  4  -3  6  1  7  2  9  3  8  10  5
  1  2  9  -3  0  7  8  3  4  6  5  10
  0  6  -3  9  7  8  1  4  10  3  5  2


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved