登录
首页 >  Golang >  Go问答

最有效的方法来存储复杂数据

来源:stackoverflow

时间:2024-03-12 23:57:25 394浏览 收藏

学习知识要善于思考,思考,再思考!今天golang学习网小编就给大家带来《最有效的方法来存储复杂数据》,以下内容主要包含等知识点,如果你正在学习或准备学习Golang,就都不要错过本文啦~让我们一起来看看吧,能帮助到你就更好了!

问题内容

我有一个表,用于根据号码前缀存储语音通话的费用:

Prefix  ratio 
44      0.01597
447     0.04958
447530  0.03
447531  0.048
447532  0.04950
1       0.1
97      0.1

在表中查找号码的前缀并不复杂,因为需要最大匹配前缀。 例如

4475122112的前缀是447

4475302112 的前缀是 447530

我想将表缓存在内存中,以通过减少数据库交互来提高性能。 由于获取号码前缀(及其速率)需要在缓存上进行搜索

我发现了两种方法:

  1. 将它们存储在纯地图中。在地图上搜索可以很简单,只需扫描整个地图即可(也许是懒惰)。
  2. 创建树形链表结构。短前缀靠近根,最长前缀靠近叶子。

现在,缓存此类数据的最佳方法是什么?还是有其他机制?


解决方案


将它们存储在地图中,然后尝试您要查找其成本的数字。如果数字(钥匙)不在地图中,则剪掉其最后一位数字并重复。这样,如果您找到匹配项,则保证这将是最长的前缀。

这是一个示例查找函数:

var prefixcostmap = map[uint64]float64{
    44:     0.01597,
    447:    0.04958,
    447530: 0.03,
    447531: 0.048,
    447532: 0.04950,
    1:      0.1,
    97:     0.1,
}

func lookup(num uint64) (longestprefix uint64, cost float64, ok bool) {
    longestprefix = num

    for longestprefix > 0 {
        cost, ok = prefixcostmap[longestprefix]
        if ok {
            break
        }
        longestprefix = longestprefix / 10 // cut off last digit
    }

    return
}

测试它:

fmt.println(lookup(4475122112))
fmt.println(lookup(4475302112))
fmt.println(lookup(999))

输出(在Go Playground上试试):

447 0.04958 true
447530 0.03 true
0 0 false

注意:这不支持以 0 开头的数字。如果您还需要处理这个问题,您可以将数字存储为字符串值,因此将保留初始 0 数字。

这是 string 版本的样子:

var prefixcostmap = map[string]float64{
    "44":     0.01597,
    "447":    0.04958,
    "447530": 0.03,
    "447531": 0.048,
    "447532": 0.04950,
    "1":      0.1,
    "97":     0.1,
    "0123":   0.05,
}

func lookup(num string) (longestprefix string, cost float64, ok bool) {
    longestprefix = num

    for longestprefix != "" {
        cost, ok = prefixcostmap[longestprefix]
        if ok {
            break
        }
        longestprefix = longestprefix[:len(longestprefix)-1] // cut off last digit
    }

    return
}

测试它:

fmt.println(lookup("4475122112"))
fmt.println(lookup("4475302112"))
fmt.println(lookup("999"))
fmt.println(lookup("0123456"))

输出(在 Go Playground 上尝试):

447 0.04958 true
447530 0.03 true
 0 false
0123 0.05 true

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>