I have a function that takes input of packs which is a map of the pack size and the quantity and it takes a total quantity for an order.
I need to get all the divisibles for the pack sizes, remove all the under 1 values, and then pick the best divisible which is the lowest number remaining. This number is the key from the supplied packsizes
Note: I have a function further up the trace which eliminates any possibility of there not being a divisible.
Code:
func optimalDivisble(packs map[int]int, oq int) (int, error) {
divisables := make(map[int]float64)
for key := range packs {
divisables[key] = float64(oq) / float64(key)
}
// Remove zero divisibles
filteredDivisibles := make(map[int]float64)
for key, divisable := range divisables {
if divisable >= 1 {
filteredDivisibles[key] = divisable
}
}
// Get divisables
var divisableSlice []float64
for _, filteredDivisible := range filteredDivisibles {
divisableSlice = append(divisableSlice, filteredDivisible)
}
sort.Float64s(divisableSlice)
for key, filteredDivisible := range filteredDivisibles {
if filteredDivisible == divisableSlice[0] {
return key, nil
}
}
return 0, errors.New("Could not find a divisable for quantity")
}
Could someone help refactor this, as seeing 3 for loops doesn't seem ideal. What would be more idiomatic to Go?
You can process the packs, compute the min divisible and get the key for it in a single loop. You don't need the intermediate steps:
var minDiv float64
var minKey int
minSet:=false
for key := range packs {
divisable:=float64(oq) / float64(key)
if divisable>=1 {
if minDiv>divisable || !minSet {
minDiv=divisable
minKey=key
minSet=true
}
}
}
// minKey is what you need
Este artigo é coletado da Internet.
Se houver alguma infração, entre em [email protected] Delete.
deixe-me dizer algumas palavras