Skip to content

Instantly share code, notes, and snippets.

@hackerzhut
Created August 7, 2018 00:48
Show Gist options
  • Save hackerzhut/0aadde77449e313af0b52ed6c4eec74a to your computer and use it in GitHub Desktop.
Save hackerzhut/0aadde77449e313af0b52ed6c4eec74a to your computer and use it in GitHub Desktop.
Selections Permutation
package main
import (
"bytes"
"fmt"
"strconv"
)
func selectionHelper(runners string, chosen string) {
if runners == "" {
fmt.Println(chosen)
return
}
for index := 0; index < len(runners); index++ {
char := runners[index : index+1]
chosen = chosen + char
runners = runners[0:index] + runners[index+1:]
selectionHelper(runners, chosen)
runners = runners[0:index] + char + runners[index:]
chosen = chosen[:len(chosen)-1]
}
}
func insert(s []int, at int, val int) []int {
// Make sure there is enough room
s = append(s, 0)
// Move all elements of s up one slot
copy(s[at+1:], s[at:])
// Insert the new element at the now free position
s[at] = val
return s
}
func getAllCombinations(runners []int, combinations int, chosen []int, result chan<- []int) {
for index, runner := range runners {
if combinations > 1 {
crunners := make([]int, len(runners))
copy(crunners, runners)
getAllCombinations(
append(crunners[:index], crunners[index+1:]...),
combinations-1,
append(chosen, runner),
result,
)
} else {
result <- append(chosen, runner)
}
}
}
//GetSelections get selections for a given runner count
func GetSelections(count int) {
var runners, chosen []int
var buff bytes.Buffer
for r := 1; r <= 4; r++ {
runners = append(runners, r)
buff.WriteString(strconv.Itoa(r))
}
result := make(chan []int)
go func() {
defer close(result)
defer fmt.Println("closing channel")
getAllCombinations(runners, 3, chosen, result)
}()
for result := range result {
fmt.Println(result)
}
// selectionHelper(buff.String(), "")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment