Jonas Grønbek
Jonas Grønbek

Reputation: 2019

get all ranges between map keys golang

So I have following structs, and I want to iterate through FiniteSet to get all ranges between the actual keys from the range. By that I mean get ranges excluding the keys. The reason for float64 is because I want to handle Math.inf() too. I am not sure if this is the best approach though.

type (
    FiniteSet struct {
        set map[float64]nothing
    }

    nothing struct{}

    Range struct {
        lowerBoundary float64
        upperBoundary float64
    }
)

e.g

map[float64]nothing {
    math.Inf(-1): nothing{},
    1: nothing{},
    2: nothing{},
    5: nothing{},
    math.Inf(): nothing{}
}

I want the output to be yield

[]Range {
        Range{math.inf(-1), 0}, 
        Range{3,4}, 
        Range{6, math.Inf()}
    }
}

I would include my attempt on the implementation, if it weren't such a mess. I doubt it will provide anything but confusion to the question.

Upvotes: 0

Views: 454

Answers (1)

Mihai
Mihai

Reputation: 10757

package main

import (
    "fmt"
    "math"
    "sort"
)

type (
    FiniteSet struct {
        set map[float64]nothing
    }

    nothing struct{}

    Range struct {
        lowerBoundary float64
        upperBoundary float64
    }
)

func main() {

    data := map[float64]nothing{
        math.Inf(-1): nothing{},
        1:            nothing{},
        2:            nothing{},
        5:            nothing{},
        math.Inf(1):  nothing{},
    }

    r := process(data)

    fmt.Printf("%v\n", r)
}

func process(data map[float64]nothing) []Range {

    keys := make([]float64, 0)
    for k := range data {
        keys = append(keys, k)
    }

    sort.Float64s(keys)

    r := make([]Range, 0)

    for i := 0; i < len(keys)-1; i++ {
        if 1 == keys[i+1]-keys[i] {
            continue
        }

        var current Range
        if keys[i] == math.Inf(-1) {
            current.lowerBoundary = keys[i]
        } else {
            current.lowerBoundary = keys[i] + 1
        }

        if keys[i+1] == math.Inf(1) {
            current.upperBoundary = keys[i+1]
        } else {
            current.upperBoundary = keys[i+1] - 1
        }

        r = append(r, current)

    }

    return r
}

Upvotes: 1

Related Questions