How do I sort a slice of ints by the first digit of each int?
I am trying to write my own custom sort:
type ByFirstDigit []int
func (s ByFirstDigit) Len() int {
return len(s)
}
func (s ByFirstDigit) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s ByFirstDigit) Less(i, j int) bool {
return s[i][0] < s[j][0]
}
But I get this error:
s[j][0] (type int does not support indexing)
@RayfenWindspear has the easiest to use and read answer, but is correct about the performance hit. If performance is more important than maintainability, you can do the same thing using iterative division to get the most-significant base-10 digit:
var i int
for i = n; i >= 10; i = i / 10 {}
// i == most significant digit
Note that you have to declare i
outside the loop to be able to use it after the loop finds the most-significant digit. I'd also benchmark both with your own data set to see what the real performance impact is in your particular situation.
Full playground example, courtesy of Rayfen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With