Optimal refactor of divisibles from map

Chris Townsend

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?

Burak Serdar

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.

editar em
0

deixe-me dizer algumas palavras

0comentários
loginDepois de participar da revisão

Artigos relacionados

Optimal way to transfer values from a Map<K, V<List>> to a Map<otherKey, otherValue<List>>

How to refactor/fix algorithim from mutating a reference to using inline variable

Refactor to remove Taks.Run from my code

How to get the optimal threshold from ROC curve in Python?

How to get the optimal number of clusters from the clusGap function as an output?

refactor too many if...else statements while reading map structure in java

RxPy3 group_by cria "groupedobservables", mas flat_map não funciona - Reactive Python for Data Science Refactor

How do I refactor a response from Parse (or any data source) in React or React Native?

What's more optimal: query chaining parent & child or selecting from parent's child objects

Getting optimal email deliverability from multiple domains using SendGrid with our SaaS product

What would be an optimal way to perform DNS query from bash in python3?

What is the optimal way to create a new column in Pandas dataframe based on conditions from another row?

What's more optimal: query chaining parent & child or selecting from parent's child objects

Removing elements from a Map

Creating paths from a map

Collect map from other map by stream

Update map with values from another map

How to extract keys from Map.Map?

Get the value of multiple map (Map inside of map) from postman

return object from array map

Pass Map from servlet to Angularjs

Golang: Json from URL as map

lambda retrieve integer from map

Reproducing the result from Map() with mapply()

Example of an Fmap to distinguish from map?

Arcpy map algebra from reticulate

Map operators extracted from substring

Remove values from Ruby map

Map JSON from API Javascript

TOP lista

  1. 1

    R Shiny: use HTML em funções (como textInput, checkboxGroupInput)

  2. 2

    O Chromium e o Firefox exibem as cores de maneira diferente e não sei qual deles está fazendo certo

  3. 3

    Como assinar digitalmente um documento PDF com assinatura e texto visíveis usando Java

  4. 4

    R Folheto. Dados de pontos de grupo em células para resumir muitos pontos de dados

  5. 5

    Gerenciar recurso shake de Windows Aero com barra de título personalizado

  6. 6

    Como obter dados API adequados para o aplicativo angular?

  7. 7

    UITextView não está exibindo texto longo

  8. 8

    Por que meus intervalos de confiança de 95% da minha regressão multivariada estão sendo plotados como uma linha de loess?

  9. 9

    Acessando relatório de campanhas na AdMob usando a API do Adsense

  10. 10

    Usando o plug-in Platform.js do Google

  11. 11

    Como posso modificar esse algoritmo de linha de visada para aceitar raios que passam pelos cantos?

  12. 12

    Dependência circular de diálogo personalizado

  13. 13

    Coloque uma caixa de texto HTML em uma imagem em uma posição fixa para site para desktop e celular

  14. 14

    iOS: como adicionar sombra projetada e sombra de traço no UIView?

  15. 15

    Como usar a caixa de diálogo de seleção de nomes com VBA para enviar e-mail para mais de um destinatário?

  16. 16

    Tabela CSS: barra de rolagem para a primeira coluna e largura automática para a coluna restante

  17. 17

    How to create dynamic navigation menu select from database using Codeigniter?

  18. 18

    Converter valores de linha SQL em colunas

  19. 19

    ChartJS, várias linhas no rótulo do gráfico de barras

  20. 20

    用@StyleableRes注释的getStyledAttributes。禁止警告

  21. 21

    não é possível adicionar dependência para com.google.android.gms.tasks.OnSuccessListener

quentelabel

Arquivo