Created
September 10, 2021 10:29
-
-
Save scspijker/7f5abca77b9aa28a8c58d46ce8d22ed1 to your computer and use it in GitHub Desktop.
Golang - Printing all possible orders of elements in an array. WARNING: HIGHLY INEFFICIENT, JUST FOR FUN, DON'T USE IN PRODUCTION
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"strings" | |
) | |
func main() { | |
source := []string{ | |
"One", | |
"Two", | |
"Three", | |
"Four", | |
"Five", | |
"Six", | |
} | |
current := make([]string, len(source)) | |
recursiveCombinationPrinter(source, current, 0) | |
} | |
// Prints all possible combinations recursively | |
// Arguments: | |
// - source: Source array of elements to pick from | |
// - current: Array that is filled by method with current combination | |
// - index: Current depth of recursive function | |
func recursiveCombinationPrinter(source []string, current []string, index int) { | |
// Current combination is ready to be printed, print it | |
if index == len(source)+len(current) { | |
fmt.Println(strings.Join(current, ", ")) | |
return | |
} | |
// Loop through all element, and recursively call self | |
// Remove current element from the source for the next call. | |
for i := 0; i < len(source); i++ { | |
// Use an element | |
current[index] = source[i] | |
// Remove this element, as it can only occur once. | |
newSource := make([]string, len(source)) | |
copy(newSource, source) | |
newSource = removeIndex(newSource, i) | |
// Call recursively to determine element for next index | |
recursiveCombinationPrinter(newSource, current, index+1) | |
} | |
} | |
// Very memory inefficient but simple way to do this. Don't in production. | |
func removeIndex(s []string, index int) []string { | |
if len(s) == 0 { | |
return s | |
} | |
return append(s[:index], s[index+1:]...) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment