> For the complete documentation index, see [llms.txt](https://trizen.gitbook.io/sidef-lang/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://trizen.gitbook.io/sidef-lang/programming_tasks/p/probabilistic_choice.md).

# Probabilistic choice

```ruby
define TRIALS = 1e4
 
func prob_choice_picker(options) {
    var n = 0
    var a = []
    options.each { |k,v|
        n += v
        a << [n, k]
    }
    func {
        var r = 1.rand
        a.first{|e| r <= e[0] }[1]
    }
}
 
var ps = Hash(
   aleph  => 1/5,
   beth   => 1/6,
   gimel  => 1/7,
   daleth => 1/8,
   he     => 1/9,
   waw    => 1/10,
   zayin  => 1/11
)
 
ps{:heth} = (1 - ps.values.sum)
 
var picker = prob_choice_picker(ps)
var results = Hash()
 
TRIALS.times {
    results{picker()} := 0 ++
}
 
say "Event   Occurred  Expected  Difference"
for k,v in (results.sort_by {|k| results{k} }.reverse) {
    printf("%-6s  %f  %f  %f\n",
        k, v/TRIALS, ps{k},
        abs(v/TRIALS - ps{k})
    )
}
```

#### Output:

```
Event   Occurred  Expected  Difference
aleph   0.196300  0.200000  0.003700
beth    0.165600  0.166667  0.001067
gimel   0.143700  0.142857  0.000843
daleth  0.123900  0.125000  0.001100
he      0.111800  0.111111  0.000689
waw     0.101900  0.100000  0.001900
zayin   0.088100  0.090909  0.002809
heth    0.068800  0.063456  0.005344
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://trizen.gitbook.io/sidef-lang/programming_tasks/p/probabilistic_choice.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
