Golang Program to Perform Slices Permutations of Numbers Entered by the User


A slice is a portion of data extracted from an array, list or a data structure. Permutations refer to the rearrangement of elements in a specific order.Here slice permutation means to generate all the possible permutations of the number entered by user. In this article, we will explore how to perform slices permutations of numbers entered by user in Golang, using two methods the recursive approach and the iterative approach, to generate all possible permutations of the given slice.

Explanation

Recursive: Our first trick is the generatePermutationsRecursive() function. It starts simple, handling small batches of numbers like a warm−up. Then it ramps up, playing with the order of numbers like a wizard weaving spells. The result? A bag full of unique number sequences.

Iterative: Next up is the generatePermutationsIterative function, joined by a stack that keeps things organized. Like a choreographed dance, numbers switch places gracefully. This routine produces a collection of different arrangements, showing off the magic of permutations.

Algorithm

  • If the length of the input slice is 0, return an empty two−dimensional slice. Create an empty two−dimensional slice to store permutations.

  • Initialise a stack with the same length as the input slice, and set all values in the stack to 0. Set the iteration variable i to 0. While i is less than the length of the input slice, repeat steps 6−13.

  • If the value at stack[i] is less than i, continue to step 7. Otherwise, set stack[i] to 0, increment i by 1, and go back to step 5. If i is even, swap the first element of the input slice with the element at index i. Otherwise, swap the element at index stack[i] with the element at index i.

  • Append a copy of the current input slice to the permutations slice. Increment the value at stack[i] by 1. Set it back to 0. Go back to step 5.

  • After the loop ends, return the permutations slice containing all generated permutations.

Syntax

func generatePermutationsRecursive(numbers []int) [][]int

This syntax represents a function that accepts integer slice numbers as input. It implements the recursive approach to generate permutations and returns a two−dimensional integer slice [][]int containing all possible permutations of the input slice.

func generatePermutationsIterative(numbers []int) [][]int

This syntax defines a function that takes integer slice numbers as input. It applies an iterative algorithm to generate permutations and returns a two−dimensional integer slice [][]int containing all possible permutations of the input slice.

Example

In this example we implement the recursive approach to perform slices permutations of numbers entered by user in Golang. Let us consider the input slice of numbers: [1, 2, 3]. Using the generatePermutationsRecursive function, we recursively generate all possible permutations of the input numbers. In this example, we start with the initial slice [1, 2, 3]. The function performs swaps and explores all possible combinations to generate permutations. The output is a two−dimensional slice containing all permutations: [[1 2 3] [1 3 2] [2 1 3] [2 3 1] [3 2 1] [3 1 2]].

package main

import "fmt"

func generatePermutationsRecursive(numbers []int) [][]int {
	if len(numbers) == 0 {
		return [][]int{}
	}

	if len(numbers) == 1 {
		return [][]int{{numbers[0]}}
	}

	permutations := [][]int{}

	for i, num := range numbers {
		remaining := make([]int, len(numbers)-1)
		copy(remaining[:i], numbers[:i])
		copy(remaining[i:], numbers[i+1:])

		subPermutations := generatePermutationsRecursive(remaining)

		for _, p := range subPermutations {
			permutations = append(permutations, append([]int{num}, p...))
		}
	}

	return permutations
}

func main() {
	numbers := []int{1, 2, 3}
	permutations := generatePermutationsRecursive(numbers)
	fmt.Println("Permutations:", permutations)
}

Output

Permutations: [[1 2 3] [1 3 2] [2 1 3] [2 3 1] [3 1 2] [3 2 1]]

Example

In this example, we have a slice of numbers [1, 2, 3] and using the generatePermutationsIterative() function, we start by checking the base case: if the input slice is empty, we return an empty slice. Otherwise, we initialize the permutations slice with the initial numbers slice. We also create a stack to keep track of indices.

package main

import "fmt"

func generatePermutationsIterative(numbers []int) [][]int {
	n := len(numbers)

	if n == 0 {
		return [][]int{}
	}

	permutations := [][]int{numbers}

	stack := make([]int, n)
	for i := range stack {
		stack[i] = 0
	}

	i := 0
	for i < n {
		if stack[i] < i {
			if i%2 == 0 {
				numbers[0], numbers[i] = numbers[i], numbers[0]
			} else {
				numbers[stack[i]], numbers[i] = numbers[i], numbers[stack[i]]
			}

			permutations = append(permutations, append([]int(nil), numbers...))
			stack[i]++
			i = 0
		} else {
			stack[i] = 0
			i++
		}
	}

	return permutations
}

func main() {
	numbers := []int{1, 2, 3}
	permutations := generatePermutationsIterative(numbers)
	fmt.Println("Permutations:", permutations)
}

Output

Permutations: [[3 2 1] [2 1 3] [3 1 2] [1 3 2] [2 3 1] [3 2 1]]

Real life implementation

Tailoring the Atmosphere

Different seating arrangements can influence the event's atmosphere. You can use permutations to create tables with diverse dynamics − mixing extroverts with introverts, professionals with newcomers, or guests from different cultural backgrounds. This thoughtful planning enhances the overall ambiance.

Handling Dynamic Guest Lists

Events often involve last−minute changes in attendance. If new guests are added or some cancel, you can quickly generate new seating arrangements using the permutations program. This flexibility ensures that the seating plan remains balanced and inclusive.

Conclusion

In this article we have looked at how we can perform slices permutations of numbers entered by user in Golang, we are going to use the recursive as well as iterative approach, the recursive approach generates permutations by recursively removing elements and combining them with the generated permutations. The iterative method uses a stack and swaps elements to generate all possible permutations. These methods provide efficient ways to generate permutations, enabling various applications such as combinatorial problems, algorithmic optimizations such as combinatorial problems, permutation−based algorithms, and more.

Updated on: 07-Sep-2023

116 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements