[Question]
  [
This challenge is rather simple:  
You are given an array of positive (not including 0) integers, and have to select a random element from this array.
But here's the twist:  
The probability of selecting an element is dependent on the value of the integer, meaning as the integer grows larger, the probability of it to get selected does too!
# Example
You are given the array `[4, 1, 5]`.
The probability of selecting 4 is equal to *4 divided by the sum of all elements in the array*, in this case `4 / ( 4 + 1 + 5 ) = 4 / 10 =` **`40%`**.  
The probability of selecting 1 is `1 / 10` or **`10%`**.
# Input
An array of positive integers.
# Output
Return the selected integer if using a method, or directly print it to `stdout`.
# Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in bytes in any language wins.
* Standard loopholes are forbidden.
  
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
x`X
```
[Try it online!](https://tio.run/##y0rNyan8/78iIeL////RJjoKhjoKprEA "Jelly – Try It Online")
Look 'ma, no Unicode!
Explanation:
```
x`X
 `  Make monad from dyad and use same left and right arguments
x   Repeat each element of the left argument (implicit) list its respective number of times in the right argument list
  X Random element
```
[Answer]
# [R](https://www.r-project.org/), 25 bytes
```
function(s)sample(s,1,,s)
```
[Try it online!](https://tio.run/##K/qfpmD7P600L7kkMz9Po1izODG3ICdVo1jHUEenWPN/mkayhgmQbaqp@R8A "R – Try It Online")
Explanation:
```
function(s){
 sample(x = s, size = 1, replace = FALSE, prob = s)
}
```
Takes a sample from `s` of size `1` without replacement, with weights `s`; these are rescaled to be probabilities.
To verify the distribution, use [this link](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T6NYJ8/WULMkMSknVaM4MbcAROnk6YToFGtq6uf9T9NI1jDRMdQx1dQxNAACzf8A "R – Try It Online").
[Answer]
# [Pyth](https://pyth.readthedocs.io), 4 bytes
```
OsmR
```
**[Try it here.](https://pyth.herokuapp.com/?code=OsmR&input=%5B4%2C+1%2C+5%5D&debug=0)**
Saved one byte, thanks to @Jakube, with a rather unusual approach.
# [Pyth](https://pyth.readthedocs.io), 5 bytes
```
Osm*]
```
**[Try it here!](https://pyth.herokuapp.com/?code=Osm%2a%5D&input=%5B4%2C+1%2C+5%5D&debug=0)**
# How?
### #1
```
OsmR   - Full program.
   R   - Right Map...
  m    - ... Using Map. This essentially creates the list [[4,4,4,4], [1], [5,5,5,5,5]]. 
       - ... Credit goes to Jakube for this!
 s     - Flatten.
O      - Random element of ^. Display implicitly.
```
### #2
```
Osm*]   - Full program.
  m     - Map over the input.
    ]   - The current element, d, wrapped; [d].
   *    - Repeated d times.
 s      - Flatten.
O       - Random Element. Implicitly print the result.
```
[Answer]
## CJam (9 bytes)
```
q~_]ze~mR
```
[Online demo](http://cjam.aditsu.net/#code=q~_%5Dze~mR&input=%5B4%201%205%5D). This is a full program which takes input in CJam array format on stdin and prints the selected element to stdout.
### Dissection
```
q~   e# Read and parse input
_]z  e# Copy and transpose
e~   e# Run-length decode
mR   e# Select random element uniformly
```
[Answer]
# [Perl 6](https://perl6.org), 20 bytes
*Saved 1 byte thanks to @Brad Gilbert b2gills.*
```
{bag(@_ Zxx@_).pick}
```
[Try it online!](https://tio.run/##FcxBC4IwHIbxe5/ihTz8BzE2R3YwRfoYHZIV25KsyTR0RJ992ek5/Z7BhL5Iz4jMokL6XLWjpsV5WZqW8aG7Pb6p3FBm6SiRQ9UM1gdcpBCC8ZN2fNSxxBazwaxfEyaP0RgE/3b3PuL/kySLA9shJ6XUWkX7FTOefg "Perl 6 – Try It Online")
This takes 1 list argument. We zip 2 copies of this list using the `xx` operator. So with `@_ Zxx@_`, we get a list in which element `x` is presented `x` times. It is then coerced to `Bag`, which is a collection that stores objects along with how many times they appear in the collection. Finally, we pick a random element from this collection with `pick`, which takes the counts into the account and does The Right Thing™. 
[Answer]
# [Ruby](https://www.ruby-lang.org/), 32 bytes
```
->a{a.flat_map{|x|[x]*x}.sample}
```
[Try it online!](https://tio.run/##KypNqvyfpmD7X9cusTpRLy0nsSQ@N7GguqaiJroiVquiVq84MbcgJ7X2v5GBXklmbmqxQrVCgUJatEK0oY6RjrGOiY5prEKsQu1/AA "Ruby – Try It Online")
[Answer]
# [Python 3.6](https://docs.python.org/3/), 44 bytes
```
lambda A:choices(A,A)[0]
from random import*
```
Yay for built-ins. The other `A` in `choices(A, A)` is an optional `weights` argument.
[Try it online!](https://tio.run/##K6gsycjPM/7/PycxNyklUcHRKjkjPzM5tVjDUcdRM9ogliutKD9XoSgxLwVIZeYW5BeVaP1PU7BVwKmBKy2/SCFeITMPpCs9VcPQwEDTiktBoaAoM69EI00j2kRHwVBHwTRWU/M/AA "Python 3 – Try It Online")
[Answer]
# Mathematica, 19 bytes
```
RandomChoice[#->#]&
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~8~~ 6 bytes
```
tY"1Zr
```
Try it at [**MATL Online!**](https://matl.io/?code=tY%221Zr&inputs=%5B4%2C+1%2C+5%5D&version=20.4.1)
### Explanation
```
t    % Implicit input. Duplicate
Y"   % Run-length decoding
1Zr  % Randomly take one value with uniform distribution. Implicitly display
```
[Answer]
# [Python 3](https://docs.python.org/3/), 62 bytes
```
lambda k:choice(sum([x*[x]for x in k],[]))
from random import*
```
[Try it online!](https://tio.run/##FYu7DsMgDAD3fIVHEzE0artE6pdQBvKgsVIwcqhEv56Q6aTTXfrnjeO9@te7fl2YFgf7OG9M84rHL6ApvSnWs0ABirBbbaxSnRcOIC4uDRQSS@7rFdEVNf9ZcbipsYMkFDN6NIN@6Gdb6wk "Python 3 – Try It Online")
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), ~~88~~  ~~87~~ ~~86~~ 83 bytes
```
a->{int r=0,x=-1;for(int i:a)r-=i;for(r*=Math.random();r<1;)r+=a[++x];return a[x];}
```
[Try it online!](https://tio.run/##TZAxb8IwEIV3fsWNcU0sIrUdaozEUqkDE92iDFdIWtNwji4OBUX57akTUuib7j3bT9/5gCeMXZXTYf/dV81HaXewK7GuYYOW2tkMgmqPPuSFJSzhEF6oxttSFQ3tvHWk3t0b@dfJLS35NFsBgYEe41UbPLBZzM8mTnThOBoC@4KCY2PHgB/MBv2XYqS9O0ZC8zLRgqXBVMpzpjn3DRNgGuauH4j0FWwCnvhOzu7hGLCjrWdLn2kGKNrx4qCRCzhgUf4zuudM305vYGahwS6TxaRgpPzXMohTUlhV5WVdh8Wjv7oM2sd5Mn/qRCblvbm7TdtL7fOjco1XVQD0JUX331wz46VW3l3hIxbi2tHNuv4X "Java (OpenJDK 8) – Try It Online")
[Answer]
# J, ~~8~~ ~~7~~ 8 bytes
The 7 byter is invalid; I'll revert this to a previous edit when I get back to my computer in a day or two.
[Try it online!](https://tio.run/##y/r/P81Wz95BW79auY6LKzU5I18hTcFQwUTB9P9/AA)
```
?@+/{#~
```
:( selecting random elements from an array is costly.
**8 bytes**
```
#~{~1?+/
```
**9 bytes**
```
(1?+/){#~
```
# Explanation
```
?@+/{#~
?        Choose random number in range
  +/     Sum of the array
    {    Select that element from
     #~  The elements duplicated as many times as their value
```
[Answer]
# JavaScript (ES6), 50 bytes
```
a=>a.sort((a,b)=>b-a)[Math.random()**2*a.length|0]
```
Hopefully it's apparent how this works, but I'll explain it here anyway. It sorts the integers in descending order, then chooses one at random with a [beta distrubution (1/2,1)](http://www.wolframalpha.com/input/?i=beta+distribution+%281%2F2%2C1%29).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
```
εD¸.×}˜.R
```
[Try it online!](https://tio.run/##MzBNTDJM/f//3FaXQzv0Dk@vPT1HL@j//2gTHQVDHQXTWAA "05AB1E – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 27 bytes
```
($args[0]|%{,$_*$_})|Random
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X0MlsSi9ONogtka1WkclXkslvlazJigxLyU/9////w4aJjqGOqaaAA "PowerShell – Try It Online")
Takes input `$args[0]` as a literal array. Loops through each element `|%{...}` and each iteration constructs a new array `,$_` of `$_` elements -- e.g., for `4` this will create an array `@(4,4,4,4)`. Those array elements are then piped into `Get-Random` which will pluck out one of the elements with (pseudo) equal probability. Since, e.g., for `@(4,1,5)` this gives us `@(4,4,4,4,1,5,5,5,5,5)` this satisfies the probability requirements.
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 93 89 87 76+18 = 94 bytes
```
a=>{int i=-1,r=new Random().Next(a.Sum());while(r>=0)r-=a[++i];return a[i];}
```
[Try it online!](https://tio.run/##TY6/q8IwFIVn81fcMcW2KOgU00Vweoqo8IbSIaQXvVBveEnqD0r/9prlgdM533K@Y0NhncepD8RXOL9DxLsS31T@EP8pYTsTAhwHEaKJZGHXs90Qx7rJIUUFF9AwGV0NiYB0scy9ZnzCyXDr7jIrD/iK0pTnPkGmnjfqUPpKLzJfaFPP59Qoj7H3DKZOfZyU@Jc9HLWwN8QyE4OYbR0H12H56yliuofyIpOqbmBY5ut8NaZ9MYpx@gA "C# (.NET Core) – Try It Online")
An extra 18 bytes for `using System.Linq;`
### Acknowledgements
11 bytes saved thanks to Nevay, whose random number implementation was a lot more concise (as well as being an `int` instead of a `double`).
### Degolfed
```
a=>{
    int i=-1,
    r=new Random().Next(a.Sum());
    while(r>=0)
        r-=a[++i];
    return a[i];
}
```
### Explanation
Get a random number, `r`, between 0 and sum of elements. Then at each iteration subtract the current element from `r`. If `r` is less than `0`, then return this element. The idea is that there are bigger portions of the random number for the larger numbers in the array.
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), 7 bytes
```
ËÆD
c ö
```
[Test it here](https://ethproductions.github.io/japt/?v=1.4.5&code=y8ZECmMg9g==&input=WzQsMSw1XQ==)
---
## Explanation
Implicit input of array `U`.
```
Ë
```
Map over the array passing each element through a function where `D` is the current element.
```
ÆD
```
Generate an array of length `D` and fill it with `D`.
```
c
```
Flatten.
```
ö
```
Get a random element.
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 5 bytes
```
lS/mR
```
[Try it online!](https://tio.run/##S85KzP3/PydYPzfo/38DBQsFcwVjAA "CJam – Try It Online")
Note: seperate numbers by a space
[Answer]
# Perl, 31 bytes
```
@a=map{($_)x$_}@ARGV;$a[rand@a]
```
This assumes the input to be command line arguments. Note that it may run out of memory if the numbers are large.
[Answer]
# [Perl 5](https://www.perl.org/), 31 + 1 (-a) = 32 bytes
```
@p=map{($_)x$_}@F;say$p[rand@p]
```
[Try it online!](https://tio.run/##K0gtyjH9/9@hwDY3saBaQyVes0IlvtbBzbo4sVKlILooMS/FoSD2/38TBUMF03/5BSWZ@XnF/3V9TfUMDA3@6yYCAA "Perl 5 – Try It Online")
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 17 bytes
```
~{.({.}*}%.,rand=
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPn/v65aT6Nar1arVlVPpygxL8X2//9oEwVDBdNYAA "GolfScript – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes
```
Ｆ⪪θ;ＦＩι⊞υι‽υ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBI7ggJ7NEo1BHQclaSVNTASzmnFhcopEJ5AWUFmdolOooZGpacwUUZeaVaAQl5qXk52qUampa//9vYm1obfpft@y/bnEOAA "Charcoal – Try It Online") Link is to verbose version of code. Since Charcoal tries to be too clever, I'm having to use semicolon-delimited input for the array. Explanation:
```
  θ             Input variable as string
 ⪪ ;            Split on semicolons
Ｆ               Loop i over each string
     Ｉι         Cast i to integer
    Ｆ           Repeat that many times
       ⊞υι      Push i to (originally empty) list
          ‽υ    Random selection from list
                Implicitly print
```
[Answer]
# [Haskell](https://www.haskell.org/), 87 bytes
```
import System.Random
f l|m<-[x<$[1..x]|x<-l]>>=id=randomRIO(0,length m-1)>>=print.(m!!)
```
[Try it online!](https://tio.run/##HYyxCoMwFEVn8xVP6BBBQwLtZtw7FewoDoJpDM17SkzBgv@ehm73cu65y7S/jfcpOdzWEOH53aNB0U80r8he4E9sm@FoL4MS4hjPo2382HXazTr8N/39wWXtDdm4ADaqynALjqLgWJZVsiDB62DiJxCvmAXKdV5Zkb9ZYYFTdnJkODkCDRaUlDCo@lrfxvQD "Haskell – Try It Online")
[Answer]
# Javascript (ES6), ~~61~~ 54 bytes
-7 bytes thanks to @Justin Mariner
```
a=>a.find(m=>(n-=m)<0,n=Math.random()*eval(a.join`+`))
```
## Example code snippet
```
f=
a=>a.find(m=>(n-=m)<0,n=Math.random()*eval(a.join`+`))
console.log(f([4,1,5]))
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~78~~ 77 bytes
```
import System.Random
f l=randomRIO(0,sum l-1)>>=pure.((l>>= \n->n<$[1..n])!!)
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/PzO3IL@oRCG4srgkNVcvKDEvJT@XK00hx7YIzAzy9Ncw0CkuzVXI0TXUtLOzLSgtStXT0MgBMhVi8nTt8mxUog319PJiNRUVNf/nJmbmKdgqpClEG@oYGgCRQawCSGVBUWZeyX8A "Haskell – Try It Online") Usage example: `f [1,99]` probably yields `99`.
### Explanation:
* `f` takes a list of integers `l` and returns the randomly selected integer as `IO Int`.
* `l>>= \n->n<$[1..n]` constructs a list with each element `n` repeated `n` times.
* `randomRIO(0,sum l-1)` yields an integer in the range from 0 to the length of the list of repeated elements, which is exactly the sum of all elements, minus one to avoid a out of bound exception.
---
**Bonus:** 85 byte point-free version
```
import System.Random
(>>=).randomRIO.(,)0.pred.sum<*>(pure.).(!!).(>>= \n->n<$[1..n])
```
[Try it online!](https://tio.run/##HYqxCsMgFAD3fsULdNCSPnSP7p0K6ZhmEGKoNL7I0wz9emsLx8HBvVx@@22rNcS0c4HHJxcfcXS07PG0GmGtkcj/HG93FL1UmNgvmI84XKxIB3uUKLquqc3wpKul4TxpRJpljS4QGFhh0r1WDTXDb0scqNQv "Haskell – Try It Online")
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 51 bytes
```
for n in $@;{ printf $n\\n%.s `seq $n`;}|shuf|sed q
```
Takes space-separated or newline-separated input in one argument or multiple arguments.
[Try it online!](https://tio.run/##S0oszvj/Py2/SCFPITNPQcXBulqhoCgzryRNQSUvJiZPVa9YIaE4tRDIS7CurSnOKE2rKU5NUSj8//@/iYKhgikA)
[Validate the random frequencies](https://tio.run/##dVBBasMwELzrFYMiQ9KS1A4NgQZDL/1A6a0pWLHXWGDLiVemhjhvd6U00Fx60Apmd2Z256C5mho9pEkcx5hBN21vHdoSrjO6ZiG4b9JYlG2HAcZCve5QtJjPPY7HFMNiEQBLQlBetZAfxI5foLyoFMfOWFdCRstnRrTc@sJ7KyFn/r2TriP/vw1Hyh0VkfyzyZhOV40sqE8Btzf7M26qyu73Nlrxbdhmu8vIVV@OTAVOU1hq5LZzY2/NCct8/K5MTehIF6iNpaAsjKOG07kKwEL4Xp1mv4dwrmtKNzuo83XoM/664Om6FB7g85LjIc8EDcd/GckvI0R1x7gLpQihrJISkS8hmHumCttAeQMRbpmmZO1FsMEa2x8) with a more complicated test case.
[Answer]
# [Perl 6](http://perl6.org/), 21 bytes
```
{flat($_ Zxx$_).pick}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Oi0nsURDJV4hqqJCJV5TryAzObv2v7VCcWKlghJQ2NZOoTpNw1BPDyipUFGhYGRQq6SQll@kABQyNLD@DwA "Perl 6 – Try It Online")
`$_ Zxx $_` zips the input list with itself using the `xx` replication operator, turning (for example) `(1, 2, 3)` into `((1), (2, 2), (3, 3, 3))`. `flat` flattens that into a list of integers, and finally `pick` picks one at random.
[Answer]
# Java 8, ~~127~~ ~~122~~ 121 bytes
```
import java.util.*;a->{List l=new Stack();for(int i:a)for(int j=i;j-->0;Collections.shuffle(l))l.add(i);return l.get(0);}
```
-1 byte thanks to *@Nevay*.
Uses a similar approach as [*@ErikTheOutgolfer*'s Jelly answer](https://codegolf.stackexchange.com/a/142733/52210), by adding `n` times the item `n` to the list, and then select one randomly from that list.
**Explanation:**
[Try it here.](https://tio.run/##xZA/T8MwEMX3foonJoc6acp/atqFFQpSR8TgJk5x6tiRcwFVVT57cdPCAsxItuy707u73yvlu4xdrWyZr3e6qp0nlCGXtKRNcioAjEZ4liHtCtCbwnJDKs5ca2kwyIxsGjxKbbcDQFtSvpCZwnwfAk/LUmWEjIXKyytkJEK6CzechiTpDHNYTLGT8Wz7oBuCmVr1gQXJbM0iUTi/10JPZPT1L6dalHE8S8W9Myb01842SfPWFoVRzESRSWSeMx0Jr6j1FiZZKWJpJLqdOMyu26UJs48rvDudowoMbEFe21W/6QEgoD@1VLeEcZqCdKUaSHhpc1f1uCvlUfgQ7J0xAWDS6773nqYC@i6IwzMcHrsCi01DqkpcS0kdRhKzScb24L1R2ws@5pddhCFO@Elv2sG2n0Jj2bH@d@WfIMb8jJ/zC37Jr/g1v@G3fJz@wtQNut0n)
```
import java.util.*;        // Required import for List, Stack and Collections
a->{                       // Method with integer-array parameter and integer return-type
  List l=new Stack();      //  Create a List
  for(int i:a)             //  Loop (1) over the input array
    for(int j=i;j-->0;     //   Inner loop (2) from `i` down to 0
        Collections.shuffle(l))
                           //   and shuffle the List randomly after every iteration
      l.add(i);            //    Add `i` that many times to List `l`
                           //   End of inner loop (2) (implicit / single-line body)
                           //  End of loop (1) (implicit / single-line body)
  return l.get(0);         //  And then return the first item of the list
}                          // End of method
```
[Answer]
# [Dyalog APL](https://www.dyalog.com/), 8 bytes
```
/⍨⌷⍨1?+/
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v//Ud/UR20TqjX0H/WueNSzHUga2mvraz7q3WxWe2gFkDI2@P8fAA "APL (Dyalog Classic) – Try It Online")
## How?
* `/⍨`, `n` copies of `n` for each `n` in the argument.
* `⌷⍨`, at the index of
* `1?`, a random value between `1` and
* `+/`, the sum of the argument
[Answer]
# GNU APL 1.2, 26 23 bytes; 1.7 21 19 bytes
Approach inspired by [Erik the Outgolfer's Jelly answer](https://codegolf.stackexchange.com/a/142733/14280). Relies on `⎕IO` being 0 instead of 1, which is the default for GNU APL (sort of +5 bytes for `⎕IO←0`).
-3, -2 bytes thanks to @Zacharý
`∇` function form
```
∇f R
S[?⍴S←∊0 0⍉R∘.⍴R]∇
```
Anonymous lambda form
```
{S[?⍴S←∊0 0⍉⍵∘.⍴⍵]}
```
For the explanation, I will use `⍵` to represent the argument passed to the function, but it is equivalent to `R` in the `∇` form.
`⍵∘.⍴⍵` computes the outer product on the list using the reshape (`⍴`) operator. Effectively, this creates a table (like a multiplication table) but instead of multiplying, it repeats the element in the column a number of times equal to the element in the row. For the example given in the question, this is:
```
4 4 4 4    1 1 1 1    5 5 5 5   
4          1          5         
4 4 4 4 4  1 1 1 1 1  5 5 5 5 5
```
`0 0⍉⍵∘.⍴⍵` transposes the matrix and returns just the main diagonal. This gives us just the parts where the row and column in `⍵∘.⍴⍵` were the same i.e. we repeated the number a number of times equal to its value. For the example, this is:
```
4 4 4 4  1  5 5 5 5 5
```
`∊` turns its argument into a list. Using the transpose (`⍉`) operator, we got a vector containing 3 vectors. Enlist (`∊`) turns it into a single vector containing all the elements.
`S←...` assigns this new vector to vector `S`. `⍴S` gives us the length of that list. `?` is the random operator, so `?⍴S` gives us a random number between 0 and the length of the list (exclusive) (this is why it relies on `⎕IO` being 0; otherwise it's between 1 and the length, inclusive). `S[...]` returns the element at the given index.
]