Generate all permutations in go - algorithm

I am looking for a way to generate all possible permutations of a list of elements. Something similar to python's itertools.permutations(arr)
permutations ([])
[]
permutations ([1])
[1]
permutations ([1,2])
[1, 2]
[2, 1]
permutations ([1,2,3])
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]
With the difference that I do not care whether permutations would be generated on demand (like a generator in python) or all together. I also do not care whether they will be lexicographically sorted. All I need is to somehow get these n! permutations.

There are a lot of the algorithms that generate permutations. One of the easiest I found is Heap's algorithm:
It generates each permutation from the previous one by choosing a pair
of elements to interchange.
The idea and a pseudocode that prints the permutations one after another is outlined in the above link. Here is my implementation of the algorithm which returns all permutations
func permutations(arr []int)[][]int{
var helper func([]int, int)
res := [][]int{}
helper = func(arr []int, n int){
if n == 1{
tmp := make([]int, len(arr))
copy(tmp, arr)
res = append(res, tmp)
} else {
for i := 0; i < n; i++{
helper(arr, n - 1)
if n % 2 == 1{
tmp := arr[i]
arr[i] = arr[n - 1]
arr[n - 1] = tmp
} else {
tmp := arr[0]
arr[0] = arr[n - 1]
arr[n - 1] = tmp
}
}
}
}
helper(arr, len(arr))
return res
}
and here is an example of how to use it (Go playground):
arr := []int{1, 2, 3}
fmt.Println(permutations(arr))
[[1 2 3] [2 1 3] [3 2 1] [2 3 1] [3 1 2] [1 3 2]]
One thing to notice that the permutations are not sorted lexicographically (as you have seen in itertools.permutations). If for some reason you need it to be sorted, one way I have found it is to generate them from a factorial number system (it is described in permutation section and allows to quickly find n-th lexicographical permutation).
P.S. you can also take a look at others people code here and here

Here's code that iterates over all permutations without generating them all first. The slice p keeps the intermediate state as offsets in a Fisher-Yates shuffle algorithm. This has the nice property that the zero value for p describes the identity permutation.
package main
import "fmt"
func nextPerm(p []int) {
for i := len(p) - 1; i >= 0; i-- {
if i == 0 || p[i] < len(p)-i-1 {
p[i]++
return
}
p[i] = 0
}
}
func getPerm(orig, p []int) []int {
result := append([]int{}, orig...)
for i, v := range p {
result[i], result[i+v] = result[i+v], result[i]
}
return result
}
func main() {
orig := []int{11, 22, 33}
for p := make([]int, len(orig)); p[0] < len(p); nextPerm(p) {
fmt.Println(getPerm(orig, p))
}
}

var res [][]int
func permute(nums []int) [][]int {
res=make([][]int,0)
n:=len(nums)
var backTrack func(int)
backTrack=func(first int){
if first == n{
temp:=make([]int, n)
copy(temp,nums)
res = append(res, temp)
}
for i:=first;i<n;i++{
nums[first],nums[i] = nums[i],nums[first]
backTrack(first+1)
nums[first],nums[i] = nums[i],nums[first]
}
}
backTrack(0)
return res
}

In my case I had a reference to an array, then I've did a few changes in your example:
func generateIntPermutations(array []int, n int, result *[][]int) {
if n == 1 {
dst := make([]int, len(array))
copy(dst, array[:])
*result = append(*result, dst)
} else {
for i := 0; i < n; i++ {
generateIntPermutations(array, n-1, result)
if n%2 == 0 {
// Golang allow us to do multiple assignments
array[0], array[n-1] = array[n-1], array[0]
} else {
array[i], array[n-1] = array[n-1], array[i]
}
}
}
}
numbers := []int{0, 1, 2}
var result [][]int
generateIntPermutations(numbers, len(numbers), &result)
// result -> [[0 1 2] [1 0 2] [2 1 0] [1 2 0] [2 0 1] [0 2 1]]

Another Working code
package permutations
import "fmt"
func AllPermutation(a []int) {
var res [][]int
calPermutation(a, &res, 0)
fmt.Println(res)
}
func calPermutation(arr []int, res *[][]int, k int) {
for i := k; i < len(arr); i++ {
swap(arr, i, k)
calPermutation(arr, res, k+1)
swap(arr, k, i)
}
if k == len(arr)-1 {
r := make([]int, len(arr))
copy(r, arr)
*res = append(*res, r)
return
}
}
func swap(arr []int, i, k int) {
arr[i], arr[k] = arr[k], arr[i]
}
//result [[1 2 3] [1 3 2] [2 1 3] [2 3 1] [3 2 1] [3 1 2]]

Here is another variation:
// heap algorithm
func permutations(arr []int, l int, p [][]int) [][]int {
if l == 1 { p = append(p, append([]int{}, arr...)) }
for i := 0 ; i < l ; i++ {
p = permutations(arr, l-1, p)
if l % 2 == 1 {
arr[0], arr[l-1] = arr[l-1], arr[0]
} else {
arr[i], arr[l-1] = arr[l-1], arr[i]
}
}
return p
}

Related

Go: sort.Slice using foreign slice to sort

I'm coding on leetcode 973.
func kClosest(points [][]int, k int) [][]int {
sort.Slice(points, func(i, j int) bool {
if hypot(points[i]) > hypot(points[j]){
return false
}else{
return true
}
})
return points[:k]
}
func hypot(point []int) int {
ans := 0
for _, n := range point{
ans+=n*n
}
return ans
}
this is one of the answer. But this resolution involves redundant computation of distance, so i want to create a slice to restore the distance. and i'm trying to sort slice points using this foreign data like
func kClosest(points [][]int, k int) [][]int {
dist := make([]int, len(points))
for i:=0; i< len(points); i++{
dist[i] = hypot(points[i])
}
sort.Slice(points, func(i, j int) bool {
if dist[i] > dist[j]{
dist[i], dist[j] = dist[j], dist[i]
return false
}else{
return true
}
})
return points[:k]
}
func hypot(point []int) int {
ans := 0
for _, n := range point{
ans+=n*n
}
return ans
}
But in this case only slice dist is sorted while the slice points doesn't change.
I'm trying to refer to the source code but they seem to be wrapped.
Thanks if anyone could explain it to me or tell me where i can find the answer.
The purpose and responsibility of less() function you pass to sort.Slice() is to tell the is-less relation of 2 elements of the sortable slice. It should not perform changes on the slice, and it should be idempotent. Your less function is not idempotent: if you call it twice with the same i and j, it may return different result even if the slice is not modified between the calls.
Genesis: your original solution
Your original, improved solution is this:
func kClosest(points [][]int, k int) [][]int {
sort.Slice(points, func(i, j int) bool {
return hypot(points[i]) < hypot(points[j])
})
return points[:k]
}
Using an indices slice
One way of sorting a slice based on another is to create a slice holding the indices, sort this indices slice (based on the reference slice), and once we have the final index order, assemble the result.
Here's how it could look like:
func kClosest2(points [][]int, k int) [][]int {
dist := make([]int, len(points))
indices := make([]int, len(points))
for i := range dist {
indices[i] = i
dist[i] = hypot(points[i])
}
sort.Slice(indices, func(i, j int) bool {
return dist[indices[i]] <= dist[indices[j]]
})
result := make([][]int, k)
for i := range result {
result[i] = points[indices[i]]
}
return result
}
Creating sortable pairs
Another approach is to create pairs from the points and their distances, and sort the pairs.
Here's how it could be done:
func kClosest3(points [][]int, k int) [][]int {
type pair struct {
dist int
point []int
}
pairs := make([]pair, len(points))
for i := range pairs {
pairs[i].dist = hypot(points[i])
pairs[i].point = points[i]
}
sort.Slice(pairs, func(i, j int) bool {
return pairs[i].dist <= pairs[j].dist
})
result := make([][]int, k)
for i := range result {
result[i] = pairs[i].point
}
return result
}
Implementing sort.Interface and using a swap() method that swaps in both slices
Title says it all. We implement sort.Interface ourselves whose less() method will report based on the distance slice, but the swap() function will perform swapping on both slices:
type mySorter struct {
dist []int
points [][]int
}
func (m mySorter) Len() int { return len(m.dist) }
func (m mySorter) Swap(i, j int) {
m.dist[i], m.dist[j] = m.dist[j], m.dist[i]
m.points[i], m.points[j] = m.points[j], m.points[i]
}
func (m mySorter) Less(i, j int) bool { return m.dist[i] < m.dist[j] }
func kClosest4(points [][]int, k int) [][]int {
dist := make([]int, len(points))
for i := range dist {
dist[i] = hypot(points[i])
}
ms := mySorter{dist, points}
sort.Sort(ms)
return points[:k]
}
Testing the solutions
Here's a test code for all the above solutions:
solutions := []func(points [][]int, k int) [][]int{
kClosest, kClosest2, kClosest3, kClosest4,
}
for _, solution := range solutions {
points := [][]int{
{3, 5},
{0, 5},
{0, 0},
{1, 2},
{6, 0},
}
fmt.Println(solution(points, len(points)))
}
Which will output (try it on the Go Playground)
[[0 0] [1 2] [0 5] [3 5] [6 0]]
[[0 0] [1 2] [0 5] [3 5] [6 0]]
[[0 0] [1 2] [0 5] [3 5] [6 0]]
[[0 0] [1 2] [0 5] [3 5] [6 0]]

Strange Behavior of append in two dimension slice

I am a bit new to Go Language, and trying to build a function which will subdivide a slice into a number of slices with almost equal sizes. In case the size of the main slice does not fit into the number of sub-slices, I plan to redistribute the remaining elements to the sub-slices in order.
I have built the following code:
package main
import (
"fmt"
stc "strconv"
"strings"
)
func main() {
myslice := make([]int, 12)
myslice = []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
fmt.Println("Original Slice = ", myslice)
newdiv := subslices(myslice, 4)
fmt.Println(newdiv)
}
func subslices(sl []int, dividnet int) [][]int {
var res [][]int
minsize := len(sl) / dividnet
for i := 0; i < dividnet; i++ {
res = append(res, sl[i*minsize:i*minsize+minsize])
}
for i := 0; i < dividnet; i++ {
fmt.Printf("res[%d] = %v\n", i, res[i])
}
fmt.Println(res)
if rem := len(sl) % dividnet; rem != 0 {
fmt.Println("remaining elements = ", rem)
for j := 0; j < rem; j++ {
tobeadd := sl[minsize*dividnet+j]
fmt.Println("element to be added = ", tobeadd)
fmt.Printf("res[%d] before append = %v\n", j, res[j])
res[j] = append(res[j], tobeadd)
fmt.Printf("res[%d] after append = %v\n", j, res[j])
}
}
return res
}
func gentwodim(x, y int) [][]int {
res := make([][]int, x)
for z := range res {
res[z] = make([]int, y)
}
for i := 0; i < x; i++ {
for j := 0; j < y; j++ {
res[i][j] = i + j
}
}
return res
}
A Sample in Go Play
sample of the above code
The output of the code is as follows:
res[0] = [1 2]
res[1] = [3 4]
res[2] = [5 6]
res[3] = [7 8]
[[1 2] [3 4] [5 6] [7 8]]
remaining elements = 2
element to be added = 9
res[0] before append = [1 2]
res[0] after append = [1 2 9] // up to this step the code works fine
element to be added = 10
res[1] before append = [9 4] // I did not get why res[1] is changed by replacing 3 with 9
res[1] after append = [9 4 10]
[[1 2 9] [9 4 10] [10 6] [7 8]]
However, after appending the first remaining element which shown in res[0] after append = [1 2 9], the 2nd sub-slice is changed as shown from res[1] = [3 4] to res[1] before append = [9 4]
I have tried to debug and understand what I have missed or coded wrong here, but could not.
I would appreciate your support.
Avoid the problem by distributing the "extra" values as you slice things up:
func subslices(sl []int, dividnet int) [][]int {
var res [][]int
var i int
for len(sl) > 0 {
i = len(sl) / (dividnet - len(res))
res = append(res, sl[:i])
sl = sl[i:]
}
return res
}

Generate Permutations - Swap Function

I'm going thru the EPI book and adapting the solutions in Go. I don't understand the solution for "generating permutations". Below is my implementation in Go (which works correctly):
func permutations(A []int) [][]int {
result := [][]int{}
var directedPermutations func(i int)
directedPermutations = func(i int) {
if i == len(A)-1 {
B := make([]int, len(A))
copy(B, A)
result = append(result, B)
return
}
for j := i; j < len(A); j++ {
A[i], A[j] = A[j], A[i]
directedPermutations(i + 1)
A[i], A[j] = A[j], A[i]
}
}
directedPermutations(0)
return result
}
Below is the result:
16.3_generate_permutations$ go run main.go
input: [1 2 3]
[[1 2 3] [1 3 2] [2 1 3] [2 3 1] [3 2 1] [3 1 2]]
Specifically, I'm confused as to why the values are swapped before and after the recursive case. I've stepped thru with a debugger and see that for each successive call values are swapped to generate the permutation.
Is the swap before recursive case and swap back afterwards a common pattern?

How to return the sorted indices for Counting Sort?

I want to return the sorted indices for x array from the Counting Sort algorithm below, it must be simple but I can not figure out how to do that! Can someone please guide me on how to do that in Matlab or Golang or any idomatic c-style demonstration for the algorithm below? thanks a lot in advance.
x=[6 2 5 3 2 2 ];
MAX=10;
n = length(x);
C = zeros(MAX,1); // intialize counting array
for j = 1:n
C(x(j)) = C(x(j)) + 1;
end
z=1;
sorted_x = zeros(n,1); // empty array -container for sorted elements
for j = 1:n;
while ( C(j) >0)
sorted_x(z) = j;
z=z+1;
C(j) = C(j) - 1;
end
end
the code above returns the sorted_x=[2 2 2 3 5 6]
But I want to modify it to also return the sorted_indices=[2 5 6 4 3 1]
Thanks
You can use a map to store the indices -
package main
import "fmt"
func main(){
nums := [6]int{6, 2, 5, 3, 2, 2}
count := make(map[int][]int)
for i, v := range nums {
count[v] = append(count[v], i+1)
}
output := []int{}
for i := 0; i < 10; i++ {
output = append(output, count[i]...)
}
for i := 0; i < len(output); i++ {
fmt.Printf("%d ", nums[output[i]-1])
}
fmt.Println()
fmt.Println("The indices are:")
fmt.Println(output)
}
Output -
2 2 2 3 5 6
The indices are:
[2 5 6 4 3 1]
In matlab the second output value of sort function is the indices. Simply try this:
[sorted, s_ind] = sort(x);
For example, using the Go sort package,
package main
import (
"fmt"
"sort"
)
type AX struct{ A, X []int }
func (ax AX) Len() int {
return len(ax.A)
}
func (ax AX) Swap(i, j int) {
ax.A[i], ax.A[j] = ax.A[j], ax.A[i]
ax.X[i], ax.X[j] = ax.X[j], ax.X[i]
}
func (ax AX) Less(i, j int) bool {
return ax.A[i] < ax.A[j]
}
func sortAX(a []int) (x []int) {
x = make([]int, len(a))
for i := range x {
x[i] = i
}
sort.Stable(AX{A: a, X: x})
return x
}
func main() {
a := []int{6, 2, 5, 3, 2, 2}
fmt.Println("a:", a)
x := sortAX(a)
fmt.Println("a:", a)
fmt.Println("x:", x)
}
Output (Go indices start at 0):
a: [6 2 5 3 2 2]
a: [2 2 2 3 5 6]
x: [1 4 5 3 2 0]
References:
Go: Package sort

What is wrong with the following merge sort algorithm?

As the question states, I'm having trouble finding where is the issue within the following algorithm. It is the aux function for mergesort, i.e. the one used for combining sorted arrays.
func Merge(toSort *[]int, p, q, r int) {
arr := *toSort
L := arr[p:q]
R := arr[q:r+1]
fmt.Println(L)
fmt.Println(R)
i := 0
j := 0
for index := p; index <= r; index++ {
if i >= len(L) {
arr[index] = R[j]
j += 1
continue
} else if j >= len(R) {
arr[index] = L[i]
i += 1
continue
}
if L[i] > R[j] {
fmt.Println("right smaller")
arr[index] = R[j]
j += 1
continue
}
if L[i] <= R[j] {
fmt.Println("left smaller")
arr[index] = L[i]
i += 1
continue
}
}
}
For arr := []int{1,7,14,15,44,65,79,2,3,6,55,70} it gives as output [1 2 2 2 2 2 2 2 3 6 55 70].
Golang Play link
The JavaScript equivalent for this function works as expected, but I don't know why it isn't working in Go
Thank you
Golang slices are passed by reference. So you don't need to pass a pointer into the function in the first place, but you do need to take explicit copies of L and R or else merge into a different slice entirely. You are currently writing into the same underlying memory from which you are getting your values.
Code like L := arr[p:q] does not create a copy. I suppose you are overwriting your L and R parts during the assignments to arr. Have a look at http://blog.golang.org/slices to understand how slices work. (E.g. you'll basically never write stuff like toSort *[]int as []int is almost kinda pointer)
This seems to work: http://play.golang.org/p/vPo2ZKXtI9
You don't need all the indexes: slices are already views into an array. Here's a complete example using purely slice manipulation:
package main
import "fmt"
// Merge takes two sorted, increasing slices of ints and
// returns a slice combining them into a single sorted, increasing
// slice.
func Merge(a, b []int) []int {
res := make([]int, 0, len(a)+len(b))
for len(a) > 0 || len(b) > 0 {
if len(b) == 0 || len(a) > 0 && a[0] <= b[0] {
res = append(res, a[0])
a = a[1:]
} else {
res = append(res, b[0])
b = b[1:]
}
}
return res
}
func main() {
a := []int{1, 2, 5, 6, 3, 4, 7, 9}
fmt.Println(Merge(a[:4], a[4:]))
}

Resources