Is this a reasonable and idiomatic GoLang circular shift implementation? - go

Can anyone comment on whether this is a reasonable and idiomatic way of implementing circular shift of integer arrays in Go? (I deliberately chose not to use bitwise operations.)
How could it be improved?
package main
import "fmt"
func main() {
a := []int{1,2,3,4,5,6,7,8,9,10}
fmt.Println(a)
rotateR(a, 5)
fmt.Println(a)
rotateL(a, 5)
fmt.Println(a)
}
func rotateL(a []int, i int) {
for count := 1; count <= i; count++ {
tmp := a[0]
for n := 1;n < len(a);n++ {
a[n-1] = a[n]
}
a[len(a)-1] = tmp
}
}
func rotateR(a []int, i int) {
for count := 1; count <= i; count++ {
tmp := a[len(a)-1]
for n := len(a)-2;n >=0 ;n-- {
a[n+1] = a[n]
}
a[0] = tmp
}
}

Rotating the slice one position at a time, and repeating to get the total desired rotation means it will take time proportional to rotation distance × length of slice. By moving each element directly into its final position you can do this in time proportional to just the length of the slice.
The code for this is a little more tricky than you have, and you’ll need a GCD function to determine how many times to go through the slice:
func gcd(a, b int) int {
for b != 0 {
a, b = b, a % b
}
return a
}
func rotateL(a []int, i int) {
// Ensure the shift amount is less than the length of the array,
// and that it is positive.
i = i % len(a)
if i < 0 {
i += len(a)
}
for c := 0; c < gcd(i, len(a)); c++ {
t := a[c]
j := c
for {
k := j + i
// loop around if we go past the end of the slice
if k >= len(a) {
k -= len(a)
}
// end when we get to where we started
if k == c {
break
}
// move the element directly into its final position
a[j] = a[k]
j = k
}
a[j] = t
}
}
Rotating a slice of size l right by p positions is equivalent to rotating it left by l − p positions, so you can simplify your rotateR function by using rotateL:
func rotateR(a []int, i int) {
rotateL(a, len(a) - i)
}

Your code is fine for in-place modification.
Don't clearly understand what you mean by bitwise operations. Maybe this
package main
import "fmt"
func main() {
a := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
fmt.Println(a)
rotateR(&a, 4)
fmt.Println(a)
rotateL(&a, 4)
fmt.Println(a)
}
func rotateL(a *[]int, i int) {
x, b := (*a)[:i], (*a)[i:]
*a = append(b, x...)
}
func rotateR(a *[]int, i int) {
x, b := (*a)[:(len(*a)-i)], (*a)[(len(*a)-i):]
*a = append(b, x...)
}
Code works https://play.golang.org/p/0VtiRFQVl7
It's called reslicing in Go vocabulary. Tradeoff is coping and looping in your snippet vs dynamic allocation in this. It's your choice, but in case of shifting 10000 elements array by one position reslicing looks much cheaper.

I like Uvelichitel solution but if you would like modular arithmetic which would be O(n) complexity
package main
func main(){
s := []string{"1", "2", "3"}
rot := 5
fmt.Println("Before RotL", s)
fmt.Println("After RotL", rotL(rot, s))
fmt.Println("Before RotR", s)
fmt.Println("After RotR", rotR(rot,s))
}
func rotL(m int, arr []string) []string{
newArr := make([]string, len(arr))
for i, k := range arr{
newPos := (((i - m) % len(arr)) + len(arr)) % len(arr)
newArr[newPos] = k
}
return newArr
}
func rotR(m int, arr []string) []string{
newArr := make([]string, len(arr))
for i, k := range arr{
newPos := (i + m) % len(arr)
newArr[newPos] = k
}
return newArr
}

If you need to enter multiple values, whatever you want (upd code Uvelichitel)
package main
import "fmt"
func main() {
var N, n int
fmt.Scan(&N)
a := make([]int, N)
for i := 0; i < N; i++ {
fmt.Scan(&a[i])
}
fmt.Scan(&n)
if n > 0 {
rotateR(&a, n%len(a))
} else {
rotateL(&a, (n*-1)%len(a))
}
for _, elem := range a {
fmt.Print(elem, " ")
}
}
func rotateL(a *[]int, i int) {
x, b := (*a)[:i], (*a)[i:]
*a = append(b, x...)
}
func rotateR(a *[]int, i int) {
x, b := (*a)[:(len(*a)-i)], (*a)[(len(*a)-i):]
*a = append(b, x...)
}

Related

Change 2D slice in-place

I am implementing a matrix-matrix multiplication algorithm in Go and I cannot reason how to change the output matrix in-place. I have tried changing the input to a pointer but 2D slices cannot be pointers?
package main
import (
"fmt"
"strconv"
"math/rand"
"os"
"time"
)
func main() {
L := len(os.Args)
m, n, p, q, err := mapVars(L, os.Args)
if err != 0 {
fmt.Fprintf(os.Stderr, "error: Incorrect command line arguments.\n")
os.Exit(1)
}
fmt.Println("The product array has dimensions.")
fmt.Printf("\tC is %dx%d\n", m, q)
fmt.Println("\nPopulating matrix A.")
A, _ := createMat(m, n)
fmt.Println("Matrix A.")
printMat(m, A)
fmt.Println("\nPopulating matrix B.")
B, _ := createMat(p, q)
fmt.Println("Matrix B.")
printMat(p, B)
fmt.Println("\nPerforming row-wise matrix-matrix multiplication AB.")
startRow := time.Now()
C := rowMultMat(m, n, q, A, B)
dtRow := time.Since(startRow)
fmt.Printf("Time elapsed: %v\n", dtRow)
fmt.Println("Matrix C.")
printMat(q, C)
}
func mapVars(l int, args []string) (m int, n int, p int, q int, err int) {
if l == 2 {
m, _ := strconv.Atoi(args[1])
n, _ := strconv.Atoi(args[1])
p, _ := strconv.Atoi(args[1])
q, _ := strconv.Atoi(args[1])
fmt.Printf("Creating two arrays, A, B, with square dimensions.\n")
fmt.Printf("\tA is %dx%d\n\tB is %dx%d\n", m, n, p, q)
return m, n, p, q, 0
} else if (l == 5 || n != p) {
m, _ := strconv.Atoi(args[1])
n, _ := strconv.Atoi(args[2])
p, _ := strconv.Atoi(args[3])
q, _ := strconv.Atoi(args[4])
fmt.Println("Creating two arrays, A, B, with dimensions.")
fmt.Printf("\tA is %dx%d\n\tB is %dx%d\n", m, n, p, q)
return m, n, p, q, 0
} else {
fmt.Println("Incorrect command line arguments.\n")
return 0, 0, 0, 0, 1
}
}
func initMat(m int, n int) (M [][]float64, rows []float64) {
M = make([][]float64, m)
rows = make([]float64, n*m)
for i := 0; i < m; i++ {
M[i] = rows[i*n : (i+1)*n]
}
return M, rows
}
func createMat(m int, n int) (M [][]float64, rows []float64) {
M = make([][]float64, m)
rows = make([]float64, n*m)
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
rows[i*n + j] = float64(rand.Int63()%10)
}
M[i] = rows[i*n : (i+1)*n]
}
return M, rows
}
func printMat(row int, M [][]float64) {
for i := 0; i < row; i++ {
fmt.Printf("%v\n", M[i])
}
}
func rowMultMat(m int, n int, q int, A [][]float64, B [][]float64) (C [][]float64) {
C, _ = initMat(m, q)
var total float64 = 0.0
for i := 0; i < m; i++ {
for j := 0; j < q; j++ {
for k := 0; k < n; k++ {
total += A[i][k] * (B[k][j])
}
C[i][j] = total
total = 0
}
}
return C
}
Currently I am initializing the matrix inside rowMultMat because I am unable to pass C as a pointer to a 2D slice. For example, run main.go 2 3 3 2 will multiply a 2x3 with 3x2 to yield 2x2.
A slice is already a reference value. If you pass a slice into a function, the function can modify its contents (*) and the modifications will be visible to the caller once it returns.
Alternatively, returning a new slice is also efficient - because again, slices are just references and don't take up much memory.
(*) By contents here I mean the contents of the underlying array the slice points to. Some attributes like the slice's length cannot be changed in this way; if your function needs to make the slice longer, for example, you'll have to pass in a pointer to a slice.

Heapsort implementation in Go

I'm trying to implement code from Sedgewick's Algorithms textbook. The idea is to implement heapsort with the root of the heap stored in position 1 in the array.
Given the input S O R T E X A M P L E I expect a sorted output of A E E L M O P R S T X.
I'm having a bit of trouble implementing this, even when directly trying to translate the referenced Java code. This is what I have so far, which returns the following output:
package main
import (
"bufio"
"fmt"
"os"
"reflect"
"strings"
)
type Heap struct {
PQ []interface{}
}
func (h *Heap) Sort(pq []interface{}) {
n := len(pq)
for k := n / 2; k >= 1; k-- {
Sink(pq, k, n)
}
for n > 1 {
Exchange(pq, 1, n)
n = n - 1
Sink(pq, 1, n)
}
}
func Sink(pq []interface{}, k, n int) {
fmt.Println(k, n, pq)
for 2*k <= n {
j := 2 * k
if j < n && Less(pq, j, j+1) {
j = j + 1
}
Exchange(pq, k, j)
k = j
}
}
func Exchange(pq []interface{}, j, k int) {
curr := pq[j-1]
pq[j-1] = pq[k-1]
pq[k-1] = curr
}
func Less(pq []interface{}, j, k int) bool {
x, y := pq[j-1], pq[k-1]
if reflect.TypeOf(x) != reflect.TypeOf(y) {
fmt.Println("mismatched inputs", x, y)
panic("mismatched inputs")
}
switch x.(type) {
case int:
a, b := x.(int), y.(int)
if a > b {
return false
}
case float32:
a, b := x.(int), y.(int)
if a > b {
return false
}
case float64:
a, b := x.(int), y.(int)
if a > b {
return false
}
case string:
a, b := x.(string), y.(string)
if a > b {
return false
}
default:
panic("unhandled types, please add case.")
}
return true
}
func main() {
a := readStdin()
var h *Heap = new(Heap)
h.PQ = a
h.Sort(h.PQ)
fmt.Println(h.PQ)
}
func readStdin() []interface{} {
scanner := bufio.NewScanner(os.Stdin)
var items []interface{}
for scanner.Scan() {
item := scanner.Text()
tmp := strings.SplitAfter(item, " ")
items = make([]interface{}, len(tmp)+1)
for i, item := range tmp {
items[i+1] = item
}
}
if err := scanner.Err(); err != nil {
panic(err)
}
return items
}
mismatched inputs E <nil>
panic: mismatched inputs
which panics as expected because of the comparison between nil value at index 0 and the currents slice value from 1..n. Perhaps I'm looking at this problem a bit too closely, or more than likely, I am missing a key point in the heapsort implementation altogether. Thoughts?
The standard library contains a heap package that you can use to directly implement this.
Even if you want to re-implement it yourself, the idea of using an interface to access the underlying slice is a good one -- allowing you to focus on the abstract heap operations without the mess of dealing with various types.
Here's a complete working example of heapsort, running on a slice of runes. Note that *runeSlice type implements heap.Interface by defining the three methods of sort.Interface: Len, Less, Swap, and the additional two methods from heap.Interface: Push and Pop.
package main
import (
"container/heap"
"fmt"
)
type runeSlice []rune
func (r runeSlice) Len() int { return len(r) }
func (r runeSlice) Less(i, j int) bool { return r[i] > r[j] }
func (r runeSlice) Swap(i, j int) { r[i], r[j] = r[j], r[i] }
func (r *runeSlice) Push(x interface{}) {
*r = append(*r, x.(rune))
}
func (r *runeSlice) Pop() interface{} {
x := (*r)[len(*r)-1]
*r = (*r)[:len(*r)-1]
return x
}
func main() {
a := []rune("SORTEXAMPLE")
h := runeSlice(a)
heap.Init(&h)
for i := len(a) - 1; i >= 0; i-- {
a[0], a[i] = a[i], a[0]
h = h[:i]
heap.Fix(&h, 0)
}
fmt.Println(string(a))
}

Change slice content and capacity inside a function in-place

I am trying to learn Go, so here is my very simple function for removing adjacent duplicates from slice for exercise from the book by Donovan & Kernighan.
Here is the code: https://play.golang.org/p/avHc1ixfck
package main
import "fmt"
func main() {
a := []int{0, 1, 1, 3, 3, 3}
removeDup(a)
fmt.Println(a)
}
func removeDup(s []int) {
n := len(s)
tmp := make([]int, 0, n)
tmp = append(tmp, s[0])
j := 1
for i := 1; i < n; i++ {
if s[i] != s[i-1] {
tmp = append(tmp, s[i])
j++
}
}
s = s[:len(tmp)]
copy(s, tmp)
}
It should print out [0 1 3] - and I checked, actually tmp at the end of the function it has desired form. However, the result is [0 1 3 3 3 3]. I guess there is something with copy function.
Can I somehow replace input slice s with the temp or trim it to desired length?
Option 1
Return a new slice as suggested by #zerkms.
https://play.golang.org/p/uGJiD3WApS
package main
import "fmt"
func main() {
a := []int{0, 1, 1, 3, 3, 3}
a = removeDup(a)
fmt.Println(a)
}
func removeDup(s []int) []int {
n := len(s)
tmp := make([]int, 0, n)
tmp = append(tmp, s[0])
for i := 1; i < n; i++ {
if s[i] != s[i-1] {
tmp = append(tmp, s[i])
}
}
return tmp
}
Option 2
Use pointers for pass-by-reference.
The same thing in effect as that of option1.
https://play.golang.org/p/80bE5Qkuuj
package main
import "fmt"
func main() {
a := []int{0, 1, 1, 3, 3, 3}
removeDup(&a)
fmt.Println(a)
}
func removeDup(sp *[]int) {
s := *sp
n := len(s)
tmp := make([]int, 0, n)
tmp = append(tmp, s[0])
for i := 1; i < n; i++ {
if s[i] != s[i-1] {
tmp = append(tmp, s[i])
}
}
*sp = tmp
}
Also, refer to following SO thread:
Does Go have no real way to shrink a slice? Is that an issue?
Here's two more slightly different ways to achieve what you want using sets and named types. The cool thing about named types is that you can create interfaces around them and can help with the readability of lots of code.
package main
import "fmt"
func main() {
// returning a list
a := []int{0, 1, 1, 3, 3, 3}
clean := removeDup(a)
fmt.Println(clean)
// creating and using a named type
nA := &newArrType{0, 1, 1, 3, 3, 3}
nA.removeDup2()
fmt.Println(nA)
// or... casting your orginal array to the named type
nB := newArrType(a)
nB.removeDup2()
fmt.Println(nB)
}
// using a set
// order is not kept, but a set is returned
func removeDup(s []int) (newArr []int) {
set := make(map[int]struct{})
for _, n := range s {
set[n] = struct{}{}
}
newArr = make([]int, 0, len(set))
for k := range set {
newArr = append(newArr, k)
}
return
}
// using named a typed
type newArrType []int
func (a *newArrType) removeDup2() {
x := *a
for i := range x {
f := i + 1
if f < len(x) {
if x[i] == x[f] {
x = x[:f+copy(x[f:], x[f+1:])]
}
}
}
// check the last 2 indexes
if x[len(x)-2] == x[len(x)-1] {
x = x[:len(x)-1+copy(x[len(x)-1:], x[len(x)-1+1:])]
}
*a = x
}

How do I reverse a slice in go?

How do I reverse an arbitrary slice ([]interface{}) in Go? I'd rather not have to write Less and Swap to use sort.Reverse. Is there a simple, builtin way to do this?
The standard library does not have a built-in function for reversing a slice. Use a for loop to reverse a slice:
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
}
Use type parameters to write a generic reverse function in Go 1.18 or later:
func reverse[S ~[]E, E any](s S) {
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
}
}
Use reflect.Swapper to write a function that works with arbitrary slice types in Go version 1.8 or later:
func reverse(s interface{}) {
n := reflect.ValueOf(s).Len()
swap := reflect.Swapper(s)
for i, j := 0, n-1; i < j; i, j = i+1, j-1 {
swap(i, j)
}
}
Run the code on the Go playground.
The functions in this answer reverse the slice inplace. If you do not want to modify the original slice, copy the slice before reversing the slice.
Here's another possible way to reverse generic slice (go 1.18)
// You can edit this code!
// Click here and start typing.
package main
import (
"fmt"
"sort"
)
func main() {
nums := []int64{10, 5, 15, 20, 1, 100, -1}
ReverseSlice(nums)
fmt.Println(nums)
strs := []string{"hello", "world"}
ReverseSlice(strs)
fmt.Println(strs)
runes := []rune{'h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd'}
ReverseSlice(runes)
for _, r := range runes {
fmt.Print(string(r), " ")
}
}
func ReverseSlice[T comparable](s []T) {
sort.SliceStable(s, func(i, j int) bool {
return i > j
})
}
Running the program above should output:
[-1 100 1 20 15 5 10]
[world hello]
d l r o w o l l e h
Program exited.
go playground
This will return a reversed slice without modifying the original slice.
Algorithm used from official wiki page: https://github.com/golang/go/wiki/SliceTricks#reversing
func reverse(s []interface{}) []interface{} {
a := make([]interface{}, len(s))
copy(a, s)
for i := len(a)/2 - 1; i >= 0; i-- {
opp := len(a) - 1 - i
a[i], a[opp] = a[opp], a[i]
}
return a
}
There are my code example, you can run it in playground
package main
import (
"fmt"
"reflect"
"errors"
)
func ReverseSlice(data interface{}) {
value := reflect.ValueOf(data)
if value.Kind() != reflect.Slice {
panic(errors.New("data must be a slice type"))
}
valueLen := value.Len()
for i := 0; i <= int((valueLen-1)/2); i++ {
reverseIndex := valueLen - 1 - i
tmp := value.Index(reverseIndex).Interface()
value.Index(reverseIndex).Set(value.Index(i))
value.Index(i).Set(reflect.ValueOf(tmp))
}
}
func main() {
names := []string{"bob", "mary", "sally", "michael"}
ReverseSlice(names)
fmt.Println(names)
}
Here is the function I'm using with generics (go 1.18+). You can use it to reverse any kind of slice or even a string (using the split/join trick). It doesn't change the original slice.
package main
import (
"fmt"
"strings"
)
func Reverse[T any](original []T) (reversed []T) {
reversed = make([]T, len(original))
copy(reversed, original)
for i := len(reversed)/2 - 1; i >= 0; i-- {
tmp := len(reversed) - 1 - i
reversed[i], reversed[tmp] = reversed[tmp], reversed[i]
}
return
}
func main() {
a := []string{"a", "b", "c"}
fmt.Println(a, Reverse(a))
b := []uint{0, 1, 2}
fmt.Println(b, Reverse(b))
c := "abc"
fmt.Println(c, strings.Join(Reverse(strings.Split(c, "")), ""))
}
Better Go Playground
This generic slice reversal function should do it for you:
func ReverseSlice[T comparable](s []T) []T {
var r []T
for i := len(s) - 1; i >= 0; i-- {
r = append(r, s[i])
}
return r
}

What's wrong with my Priority Queue's Pop method?

Based on Rob Pike's load balancer demo, I implemented my own priority queue, but my Pop method is not right, can anyone tell me what's wrong?
package main
import (
"fmt"
"container/heap"
)
type ClassRecord struct {
name string
grade int
}
type RecordHeap []*ClassRecord
func (p RecordHeap) Len() int { return len(p) }
func (p RecordHeap) Less(i, j int) bool {
return p[i].grade < p[j].grade
}
func (p *RecordHeap) Swap(i, j int) {
a := *p
a[i], a[j] = a[j], a[i]
}
func (p *RecordHeap) Push(x interface{}) {
a := *p
n := len(a)
a = a[0 : n+1]
r := x.(*ClassRecord)
a[n] = r
*p = a
}
func (p *RecordHeap) Pop() interface{} {
a := *p
*p = a[0 : len(a)-1]
r := a[len(a)-1]
return r
}
func main() {
a := make([]ClassRecord, 6)
a[0] = ClassRecord{"John", 80}
a[1] = ClassRecord{"Dan", 85}
a[2] = ClassRecord{"Aron", 90}
a[3] = ClassRecord{"Mark", 65}
a[4] = ClassRecord{"Rob", 99}
a[5] = ClassRecord{"Brian", 78}
h := make(RecordHeap, 0, 100)
for _, c := range a {
fmt.Println(c)
heap.Push(&h, &c)
fmt.Println("Push: heap has", h.Len(), "items")
}
for i, x := 0, heap.Pop(&h).(*ClassRecord); i < 10 && x != nil; i++ {
fmt.Println("Pop: heap has", h.Len(), "items")
fmt.Println(*x)
}
}
EDIT: besides the way cthom06 pointed out, another way to fix this is to create a pointer array as follows,
a := make([]*ClassRecord, 6)
a[0] = &ClassRecord{"John", 80}
a[1] = &ClassRecord{"Dan", 85}
......
EDIT:
Oh I should've seen this right away.
heap.Push(&h, &c)
You push the address of c, which gets reused on each iteration of range. Every record in the heap is a pointer to the same area in memory, which ends up being Brian. I'm not sure if this is intended behavior or a compiler bug, but
t := c
heap.Push(&h, &t)
works around it.
Also: Your for loop is wrong.
for h.Len() > 0 {
x := heap.Pop(&h...
should fix it.

Resources