geom/ints/statistics.go
Sander Schobers 73c6048f09 Added more methods to the ints package.
- Added some statistical (related to summing and countings digits) and math methods (related to powers and square roots).
2019-12-21 13:01:47 +01:00

114 lines
1.8 KiB
Go

package ints
import "strconv"
// Digit returns the n'th digit of i
func Digit(n int, i uint) int {
return int(Digit64(int64(n), i))
}
// Digit64 returns the n'th digit of i
func Digit64(n int64, i uint) int64 {
for i >= 9 {
n /= 1000000000
i -= 9
}
for i >= 6 {
n /= 1000000
i -= 6
}
for i >= 3 {
n /= 1000
i -= 3
}
for i > 0 {
n /= 10
i--
}
return n % 10
}
// Faculty returns the faculty of i.
func Faculty(i int) int {
if i < 2 {
return 1
}
return i * Faculty(i-1)
}
// Faculty64 returns the faculty of i.
func Faculty64(i int64) int64 {
if i < 2 {
return 1
}
return i * Faculty64(i-1)
}
// IsPalindromic returns if the integer n is palindromic (reads the same backwards).
func IsPalindromic(n int) bool {
if n < 10 {
return true
}
if n%10 == 0 {
return false
}
s := strconv.Itoa(n)
max := (len(s) + 1) / 2
for i := 0; i < max; i++ {
if s[i] != s[len(s)-i-1] {
return false
}
}
return true
}
// Permutations returns all possible permutations of the the set integers.
func Permutations(set []int) [][]int {
var n = len(set)
if n == 0 {
return nil
}
var res = make([][]int, 0, Faculty(n))
var p = append([]int(nil), set...)
var c = make([]int, n)
res = append(res, append([]int(nil), p...))
i := 0
for i < n {
if c[i] < i {
if i%2 == 0 {
p[0], p[i] = p[i], p[0]
} else {
p[c[i]], p[i] = p[i], p[c[i]]
}
res = append(res, append([]int(nil), p...))
c[i] = c[i] + 1
i = 0
} else {
c[i] = 0
i++
}
}
return res
}
// SumDigits returns the sum of the digits of n.
func SumDigits(n int) int {
var sum int
for n > 0 {
sum += n % 10
n /= 10
}
return int(sum)
}
// SumDigits64 returns the sum of the digits of n.
func SumDigits64(n int64) int {
var sum int64
for n > 0 {
sum += n % 10
n /= 10
}
return int(sum)
}