Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse Slice of strings

Tags:

go

I don't understand what is wrong with the below implementation, I had a look at sort.StringSlice and it looks the same.

type RevStr []string

func(s RevStr) Len() int { return len(s) }
func(s RevStr) Less(i, j int) bool { return s[i] < s[j] }
func(s RevStr) Swap(i, j int) { s[i], s[j] = s[j], s[i] }

func Reverse(input string) string {
  rs := RevStr(strings.Split(input, " "))
  sort.Reverse(rs)
  return strings.Join(rs, " ")
}
like image 212
RockNinja Avatar asked Jan 15 '16 17:01

RockNinja


3 Answers

sort.Reverse doesn't sort the data, but rather returns a new sort.Interface that will sort the data in reverse order. So you don't really need your own type:

func Reverse(input string) string {
    s := strings.Split(input, " ")
    sort.Sort(sort.Reverse(sort.StringSlice(s)))
    return strings.Join(s, " ")
}

Playground: http://play.golang.org/p/w49FDCEHo3.

EDIT: If you just need to reverse a slice of strings, just do:

func reverse(ss []string) {
    last := len(ss) - 1
    for i := 0; i < len(ss)/2; i++ {
        ss[i], ss[last-i] = ss[last-i], ss[i]
    }
}

Playground: http://play.golang.org/p/UptIRFV_SI

like image 166
Ainar-G Avatar answered Oct 04 '22 04:10

Ainar-G


Nothing is wrong with your RevStr type (though you could just use sort.StringSlice). You're not calling sort.Sort on the reversed implementation:

https://golang.org/pkg/sort/#example_Reverse

package main

import (
    "fmt"
    "sort"
)

func main() {
    s := []int{5, 2, 6, 3, 1, 4} // unsorted
    sort.Sort(sort.Reverse(sort.IntSlice(s)))
    fmt.Println(s)
}
like image 30
JimB Avatar answered Oct 04 '22 04:10

JimB


Although @Ainar-G has provided a way to reverse a slice of strings, I think it's nicer to use two variables in for loop to reverse. But it's only my personal opinion, a matter of style :)

func reverse(s []string) []string {
    for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
        s[i], s[j] = s[j], s[i]
    }
    return s
}

Playground link with example of usage: http://play.golang.org/p/v1Cy61NFv1

like image 29
mraron Avatar answered Oct 04 '22 04:10

mraron