Getting the first digit int

How to sort an int fragment with the first digit of each int?

I am trying to write my own custom view:

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)

+4
source share
3 answers

@RayfenWindspear has the easiest way to use and read the answer, but true in terms of performance. If performance is more important than maintainability, you can do the same using iterative division to get the most significant base-10 figure:

var i int
for i = n; i >= 10; i = i / 10 {}
// i == most significant digit

, i , , . , , .

, Rayfen.

+5

, . []int https://godoc.org/strconv#Itoa. , .

https://play.golang.org/p/S4j3NlfinD

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 {
    si := strconv.Itoa(s[i])
    sj := strconv.Itoa(s[j])
    return si[0] < sj[0]
}
+1

, :

package main

import "sort"
import "fmt"
import "math"

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 firstDigit( s[i] ) < firstDigit( s[j] )
}

func firstDigit( x int ) int {
    return int( math.Abs( float64( x ) ) / math.Pow( 10, float64( numDigits(x) - 1 ) ) )
}

func numDigits( x int ) int {
    if ( x == 0 ) { return 1 }
    return int( math.Floor( math.Log10( math.Abs( float64(x) ) ) ) ) + 1
}

func main() {
    ints := []int{3, 20, 400, -500, 101}
    sort.Sort( ByFirstDigit( ints ) )
    fmt.Println( ints )
}

( ): https://play.golang.org/p/uLyBMlra2N

0

Source: https://habr.com/ru/post/1683544/


All Articles