Golang中的加权随机 [英] Weighted Random in Golang

查看:197
本文介绍了Golang中的加权随机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在Golang中进行加权随机,但出现错误:

I have to do weighted Random in Golang but I'm getting an error:

multiple-value randutil.WeightedChoice() in single-value context

代码:

package main

import "fmt"
import "github.com/jmcvetta/randutil"

func main() {    
    choices := make([]randutil.Choice, 0, 2)    
    choices = append(choices, randutil.Choice{1, "dg"})
    choices = append(choices, randutil.Choice{2, "n"})    
    result := randutil.WeightedChoice(choices)    
    fmt.Println(choices)
}

任何帮助将不胜感激.

推荐答案

func WeightedChoice(choices [] Choice)(Choice,error)
返回 Choice,error ,所以使用 result,err:= randutil.WeightedChoice(choices),就像这样的工作代码:

The func WeightedChoice(choices []Choice) (Choice, error)
returns Choice, error, so use result, err := randutil.WeightedChoice(choices), like this working code:

package main

import (
    "fmt"

    "github.com/jmcvetta/randutil"
)

func main() {
    choices := make([]randutil.Choice, 0, 2)
    choices = append(choices, randutil.Choice{1, "dg"})
    choices = append(choices, randutil.Choice{2, "n"})
    fmt.Println(choices) // [{1 dg} {2 n}]

    result, err := randutil.WeightedChoice(choices)
    if err != nil {
        panic(err)
    }

    fmt.Println(result) //{2 n}
}

输出:

[{1 dg} {2 n}]
{2 n}

这篇关于Golang中的加权随机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆