英文:
Is there a built in min function for a slice of int arguments or a variable number of int arguments in golang?
问题
前导:我刚开始接触Go语言,对它还不太熟悉。
这可能是一个愚蠢的问题,因为执行这些计算非常简单,但我还是要问一下,因为在谷歌上没有找到答案。
是否有一个内置函数可以返回一个int切片的最小值参数:
func MinIntSlice(v []int) (m int) {
if len(v) > 0 {
m = v[0]
}
for i := 1; i < len(v); i++ {
if v[i] < m {
m = v[i]
}
}
return
}
或者返回可变数量的int参数的最小值:
func MinIntVariable(v1 int, vn ...int) (m int) {
m = v1
for i := 0; i < len(vn); i++ {
if vn[i] < m {
m = vn[i]
}
}
return
}
如果没有的话,最好的“约定”是创建一个包含这样的辅助函数的包吗?
英文:
Precursor: I'm just starting to get my feet wet with golang.
This may prove to a be a silly question as it's quite easy to perform these calculations but I'm going to ask it anyway as I didn't find an answer when Googling.
Is there a built in function that returns the minimum of a slice of int arguments:
func MinIntSlice(v []int) (m int) {
if len(v) > 0 {
m = v[0]
}
for i := 1; i < len(v); i++ {
if v[i] < m {
m = v[i]
}
}
return
}
OR the minimum of a variable number of int arguments:
func MinIntVarible(v1 int, vn ...int) (m int) {
m = v1
for i := 0; i < len(vn); i++ {
if vn[i] < m {
m = vn[i]
}
}
return
}
If not, is the best "convention" simply to create a package that contains helpers like this?
答案1
得分: 56
编辑:这个答案已经过时了。截至1.21版本,Go语言中已经有了内置函数min
和max
。请参考Jonas的答案。
Go语言中没有内置的函数来实现这个功能。
如果你只需要在一个包中使用这个功能,你可以编写一个未导出的函数(比如minIntSlice
)。
如果你需要在多个包中使用这个功能,你可以创建一个包,并将类似的函数放在其中。你应该考虑将这个包设为内部包(https://golang.org/s/go14internal)。
以下是改进你的代码的几点建议:
-
MinIntSlice
对于一个空的切片会返回0。然而0也是一个有效的最小元素。我认为在空切片上调用 panic 是一个更好的选择。 -
使用 range 循环:
for i, e := range v { if i==0 || e < m { m = e } }
通过不给出值的索引,它将给出最小值0,这个值在给定的值中可能不存在,所以你还需要对索引应用条件。
英文:
Edit: This answer is out of date. There are now built-in functions min
and max
in Go as of 1.21. See Jonas' answer.
There is no built-in for this.
If you need this functionality only in one package you can write an un-exported function (e.g. minIntSlice
).
If you need this functionality in multiple packages you can create a package and put similar functions there. You should consider making this package internal (https://golang.org/s/go14internal).
A few suggestions how to improve your code:
-
MinIntSlice
will return 0 for an empty slice. However 0 is a valid min element as well. I think calling panic on an empty slice is a better option. -
Use range loop:
for i, e := range v { if i==0 || e < m { m = e } }
by not giving the index of value it will give you the minimum value 0, which may not be present in given values, so you also have to apply condition on index.
答案2
得分: 18
如@kostya正确指出,Golang中没有内置的min或max函数。
然而,我建议稍微不同的解决方案:
func MinMax(array []int) (int, int) {
var max int = array[0]
var min int = array[0]
for _, value := range array {
if max < value {
max = value
}
if min > value {
min = value
}
}
return min, max
}
通过这样做,解决了空切片的问题:会出现运行时错误(index out of range
),而最大值是免费的。
英文:
As @kostya correctly stated there is no built-in min or max function in Golang.
However, I would suggest a slightly different solution:
func MinMax(array []int) (int, int) {
var max int = array[0]
var min int = array[0]
for _, value := range array {
if max < value {
max = value
}
if min > value {
min = value
}
}
return min, max
}
By that the problem of an empty slice is solved: a runtime error shows up (index out of range
) and the max value is for free.
答案3
得分: 4
min := s[0]
for i := 1; i < len(s); i++ {
if min > s[i] {
min = s[i]
}
}
> min > s[i]? min = s[i] : min
英文:
min := s[0]
for i :=1; i < len(s); i++ {
if min > s[i] {
min = s[i]
}
}
> min > s[i]? min = s[i] : min
答案4
得分: 3
如果你不关心输入数组
import . "sort"
func MinIntSlice(v []int){
Ints(v)
return z[0]
}
func MaxIntSlice(v []int){
Ints(v)
return z[len(v)-1]
}
// and MinMax version
func MinMax(v []int)(int,int){
Ints(v)
return z[0],z[len(v)-1]
}
英文:
if you don't care about input array
import . "sort"
func MinIntSlice(v []int){
Ints(v)
return z[0]
}
func MaxIntSlice(v []int){
Ints(v)
return z[len(v)-1]
}
// and MinMax version
func MinMax(v []int)(int,int){
Ints(v)
return z[0],z[len(v)-1]
}
答案5
得分: 3
这个包包含了一些用于单独值或切片的Min
和Max
函数的实现。在使用go get
之后,可以像这样使用它:
import (
"fmt"
"<完整的URL>/go-imath/ix" // 用于int类型的函数
)
...
fmt.Println(ix.Min(100, 152)) // 输出: 100
fmt.Println(ix.Mins(234, 55, 180)) // 输出: 55
fmt.Println(ix.MinSlice([]int{2, 29, 8, -1})) // 输出: -1
英文:
This package contains some implementations of Min
and Max
functions for separate values or slices. After go get
it can be used like:
import (
"fmt"
"<Full URL>/go-imath/ix" // Functions for int type
)
...
fmt.Println(ix.Min(100, 152)) // Output: 100
fmt.Println(ix.Mins(234, 55, 180)) // Output: 55
fmt.Println(ix.MinSlice([]int{2, 29, 8, -1})) // Output: -1
答案6
得分: 2
标准包中没有这种操作的函数。
然而,gonum库提供了floats.Min(x)
和floats.Max(x)
等函数(以及其他用于处理数值数据的有趣函数)。
用法:
package main
import (
"fmt"
"gonum.org/v1/gonum/floats"
)
func main() {
x := []float64{1, 6, 9, -3, -5}
minX := floats.Min(x)
maxX := floats.Max(x)
fmt.Printf("最小值:%f,最大值:%f\n", minX, maxX)
}
结果:
最小值:-5.000000,最大值:9.000000
英文:
There is no function for such operation in the standard packages.
However, the gonum library offers the functions floats.Min(x)
and floats.Max(x)
(and other interesting functions for manipulation of numerical data).
Usage:
package main
import (
"fmt"
"gonum.org/v1/gonum/floats"
)
func main() {
x := []float64{1, 6, 9, -3, -5}
minX := floats.Min(x)
maxX := floats.Max(x)
fmt.Printf("Min: %f, max %f\n", minX, maxX)
}
Results:
Min: -5.000000, max 9.000000
答案7
得分: 2
从Go 1.21
版本开始,现在有内置函数可以获取给定参数的max
和min
,同时还有一个新的slices
包可以实现对切片的相同操作。
https://tip.golang.org/ref/spec#Min_and_max
min(2, -5, 8, 1.2) // 结果: -5
max(2, -5, 8, 1.2) // 结果: 8
对于切片,可以使用slices
包:
https://pkg.go.dev/slices
import "slices"
x := []float64{2, -5, 8, 1.2}
slices.Min(x) // 结果: -5
slices.Max(x) // 结果: 8
英文:
As of Go 1.21
there are now built-in functions to get the max
and min
for a given number of arguments as well as a new slices
package to achieve the same for slices.
https://tip.golang.org/ref/spec#Min_and_max
min(2, -5, 8, 1.2) // Result: -5
max(2, -5, 8, 1.2) // Result: 8
For slices, use the slices
package:
https://pkg.go.dev/slices
import "slices"
x := []float64{2, -5, 8, 1.2}
slices.Min(x) // Result: -5
slices.Max(x) // Result: 8
答案8
得分: 1
对于包含数百万个项目的大型切片(例如作为[]int
的25兆像素图像),通过分块计算最小值和最大值可以获得显著的性能提升:
func GetMinMax(data []int) (int, int) {
minVal := data[0]
maxVal := data[0]
for i := range data {
if data[i] < minVal {
minVal = data[i]
}
if data[i] > maxVal {
maxVal = data[i]
}
}
return minVal, maxVal
}
func GetMinMaxConcurrent(data []int) (int, int) {
numChan := make(chan int)
numChunks := runtime.NumCPU()
chunkSize := len(data) / numChunks
// 处理
var wg sync.WaitGroup
for i := 0; i < numChunks; i++ {
wg.Add(1)
go func(i, chunkSize int, numChan chan int) {
startIndex := i * chunkSize
endIndex := startIndex + chunkSize
if endIndex > len(data) {
endIndex = len(data)
}
minVal, maxVal := GetMinMax(data[startIndex:endIndex])
numChan <- minVal
numChan <- maxVal
wg.Done()
}(i, chunkSize, numChan)
}
// 收集结果
resultsChan := make(chan int)
defer close(resultsChan)
go func(numChan, resultsChan chan int) {
arr := make([]int, 0)
for num := range numChan {
arr = append(arr, num)
}
minVal, maxVal := GetMinMax(arr)
resultsChan <- minVal
resultsChan <- maxVal
}(numChan, resultsChan)
wg.Wait()
close(numChan) // 需要关闭通道以便结果例程可以返回
return <-resultsChan, <-resultsChan
}
这段代码对于小型切片来说性能不高,只有在切片足够大以从并发处理中受益时才使用。
英文:
For huge slices containing millions of items (for example a 25 megapixel image as []int
) you can get significant performance gains by calculating min/max in chunks:
func GetMinMax(data []int) (int, int) {
minVal := data[0]
maxVal := data[0]
for i := range data {
if data[i] < minVal {
minVal = data[i]
}
if data[i] > maxVal {
maxVal = data[i]
}
}
return minVal, maxVal
}
func GetMinMaxConcurrent(data []int) (int, int) {
numChan := make(chan int)
numChunks := runtime.NumCPU()
chunkSize := len(data) / numChunks
// Process
var wg sync.WaitGroup
for i := 0; i < numChunks; i++ {
wg.Add(1)
go func(i, chunkSize int, numChan chan int) {
startIndex := i * chunkSize
endIndex := startIndex + chunkSize
if endIndex > len(data) {
endIndex = len(data)
}
minVal, maxVal := GetMinMax(data[startIndex:endIndex])
numChan <- minVal
numChan <- maxVal
wg.Done()
}(i, chunkSize, numChan)
}
// Collect results
resultsChan := make(chan int)
defer close(resultsChan)
go func(numChan, resultsChan chan int) {
arr := make([]int, 0)
for num := range numChan {
arr = append(arr, num)
}
minVal, maxVal := GetMinMax(arr)
resultsChan <- minVal
resultsChan <- maxVal
}(numChan, resultsChan)
wg.Wait()
close(numChan) // needed so results routine can return
return <-resultsChan, <-resultsChan
}
This code is not performant for small slices, only use if your slice is big enough to benefit from processing chunks concurrently.
答案9
得分: 0
使用排序可以简化代码:
func MinIntSlice(v []int) int {
sort.Ints(v)
return v[0]
}
func MaxIntSlice(v []int) int {
sort.Ints(v)
return v[len(v)-1]
}
但不要忘记根据你的需求修改处理长度为零的切片的方式。
英文:
With sorting it can be shorter:
<!-- language-all: lang-go -->
func MinIntSlice(v []int) int {
sort.Ints(v)
return v[0]
}
func MaxIntSlice(v []int) int {
sort.Ints(v)
return v[len(v)-1]
}
But don't forget to modify it for zero length slices on your taste.
答案10
得分: 0
使用 @kostya 的 答案
-
使用 range 循环:
for i, e := range v { if i==0 || e < m { m = e } }
不给出值的索引,它将给出最小值 0,这个值可能不存在于给定的值中
英文:
Using @kostya's answer
-
Use range loop:
for i, e := range v { if i==0 || e < m { m = e } }
by not giving the index of value it will give you the minimum value 0, which may not be present in given values
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论