Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the first digit of an int

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)

like image 293
gogofan Avatar asked Mar 09 '23 08:03

gogofan


1 Answers

@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.

like image 174
Adrian Avatar answered Mar 15 '23 19:03

Adrian