# Randomly select from an array

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 so shortest code in bytes in any language wins.
• Standard loopholes are forbidden.

# Perl 6, 21 bytes

{flat($_ Zxx$_).pick}


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.

# JavaScript ES6, 40 bytes.

(a)=>a[parseInt(Math.random()*a.length)]

## Example

((a)=>a[parseInt(Math.random()*a.length)])([4,1,5])

• From the question: 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!. For example, if the array is [4,1,5], you should get a 5 more often than a 1. – H.PWiz Sep 14 '17 at 22:31

# Clojure, 64 bytes

(defn a[i](rand-nth(reduce #(concat %(take %2(repeat %2)))[]i)))


Appends each item item number of times to a new list, then takes a random element.

Finally a clojure answer that's not incredibly much longer than other answers :D

# 05AB1E, 21 bytes

O/ždT6m/svy-D0‹s})1kè


Try it online!

Here's a weird implementation for you, uses microseconds on the system's CPU for the randomized seed.

O/                     # [.4,.1,.5] | Push prob distribution.
ždT6m/               # ?????????? | 0 < x < 100000 divided by 100000.
s              # [.4,.1,.5] | Swap...
v             # For each prob in distribution...
y-           # Remove from random number b/w 0 and 1.
D0‹        # Dupe each, find if this number made the random number less than 0.
s})     # Continue loop, swapping current random diff to the front of the stack.
1kè  # First instance of the random number going negative is our random return.


# Clojure, 46 bytes

(fn[s](rand-nth(flatten(map #(repeat % %)s))))


Try it online!

The usual Clojure pain: simple idea, long-ass (for golfing) function names.

# TI-BASIC, 20 bytes

Ans→L₁
SortD(L₁
L₁(1+int(rand²dim(L₁


Input and output are stored in Ans. If you see a box, L₁ is L1. Same algorithm as my JavaScript answer.