Golang Program to Print all Permutations of a given String


A permutation is an arrangement of the characters of a string in a specific order. In some cases we need to print all the permutations of a string to create anagram games or puzzle games where users need to find out the letters hidden in the string. In this article we are going to print all permutations of a string in golanguage using two different approaches that include the recursive and the iterative approach. These methods allow us to generate all possible permutations of a given string, enabling various applications such as generating anagrams, solving permutation−based problems, and more.

Explanation

To tackle the concept of permutations − the art of rearranging characters within a string to explore all possible combinations. The program offers two distinct approaches, each with its unique charm:

Recursive Approach: The generatePermutationsRecursive() function initiates the journey, handling the base case of single characters adeptly. By recursively weaving characters together and exploring various combinations, it gracefully constructs permutations, unraveling the magic of arrangement possibilities.

Input string: abc
Permutations:  ["abc", "acb", "bac", "bca", "cab", "cba"].

Iterative Approach: Enter the permuteIterative function, introducing a dynamic iteration process. Through clever swaps and an array of indices, this approach artfully orchestrates permutations. It capitalizes on the dance of swapping elements to generate the mesmerizing kaleidoscope of potential orders.

Algorithm

  • Create a recursive function, generatePermutationsRecursive, that takes a string str as a parameter.

  • If the length of the string is 1, return the string itself as the only permutation. Initialise an empty slice called permutations to store the generated permutations.

  • For each character c in the string: Remove c from the string and assign it to a variable called remaining. Recursively call generatePermutationsRecursive with remaining as the parameter.

  • For each permutation p returned from the recursive call, append c + p to the permutations slice.

  • Return the permutations slice containing all generated permutations.

Syntax

func generatePermutationsRecursive(str string)

The syntax declares a function named generatePermutationsRecursive that takes a string parameter str. It uses a helper recursive function to generate permutations by appending characters to a prefix and exploring all possible combinations.

func generatePermutationsIterative(str string)

The syntax defines a function named generatePermutationsIterative that accepts a string parameter str. It utilises an iterative algorithm to generate permutations by swapping characters in the string and keeping track of indices.

Example

In this example, we are going to print all permutations of a string in golanguage, let us consider a input string "abc", now using the generatePermutationsRecursive function, we remove the first character "a" and recursively generate permutations for the remaining characters "bc". We obtain the permutations "bc" and "cb". Then, we append "a" to each permutation, resulting in "abc" and "acb". This process is repeated for each character, and the final output is the set of all permutations: ["abc", "acb", "bac", "bca", "cab", "cba"].

package main

import (
	"fmt"
)

func generatePermutationsRecursive(str string) []string {
	if len(str) == 1 {
		return []string{str}
	}

	permutations := []string{}

	for i, c := range str {
		remaining := str[:i] + str[i+1:]
		subPermutations := generatePermutationsRecursive(remaining)

		for _, p := range subPermutations {
			permutations = append(permutations, string(c)+p)
		}
	}

	return permutations
}

func main() {
	str := "abc"
	permutations := generatePermutationsRecursive(str)
	fmt.Println("Permutations:", permutations)
}

Output

Permutations: [abc acb bac bca cab cba]

Example

In this example, we use an iterative approach to print all permutations of a string in golanguage. Start by iterating through the stack and swapping elements, we can generate all possible permutations. Here we have a string "ABC" we use the iterative approach to generate all permutations of the string. The permuteIterative function takes the input string and prints all the permutations.

package main

import "fmt"

func permuteIterative(str string) {
	n := len(str)

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

	fmt.Println("Permutations:")
	fmt.Println(str)

	i := 0
	for i < n {
		if stack[i] < i {
			if i%2 == 0 {
				str = swap(str, 0, i)
			} else {
				str = swap(str, stack[i], i)
			}
			fmt.Println(str)
			stack[i]++
			i = 0
		} else {
			stack[i] = 0
			i++
		}
	}
}

func swap(str string, i, j int) string {
	strBytes := []byte(str)
	strBytes[i], strBytes[j] = strBytes[j], strBytes[i]
	return string(strBytes)
}

func main() {
	str := "ABC"
	permuteIterative(str)
}

Output

Permutations:
ABC
BAC
CBA
ACB
BCA
CAB

Real life implementation

Scrabble and Anagram Games

In word games like Scrabble or anagram−based puzzles, players are given a set of letters and are challenged to find all valid words that can be formed using those letters. The program's permutation generation can be used to efficiently generate and verify these possible word combinations.

Word Searches

Word search puzzles involve finding specific words hidden in a grid of letters, usually arranged in a rectangular matrix. The program's permutation generation can help generate possible word orientations and positions in the grid.

Conclusion

In this article we have looked at how we can print all permutations of a string in golanguage. We are going to discuss two methods: in the first example we have used the generatePermutationsRecursive() function and in the second method includes swapping elements to get the results . It can be very useful for creating scrabble and anagram games and word search puzzles, these methods provide efficient ways to generate all possible arrangements of the characters in a string, enabling various applications in problem−solving and algorithmic challenges.

Updated on: 07-Sep-2023

346 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements