14

I am trying to create 10 element array of unique random integers. However I am unable to create array with unique values. Is there in Julia something like Pythons sample function ?

numbers = zeros(Array(Int64, 10))
rand!(1:100, numbers)

Thanks.

3 Answers 3

20

There is a sample function in StatsBase:

using StatsBase
a = sample(1:100, 10, replace = false)

This will draw a sample of length 10 from 1:100 without replacement.

2
  • 1
    What if instead of a vector (a in this example) you want to create a matrix (A), with let's say 5 columns. Is there a way to do this? Something like: A = sample(1:100, 10, 5, replace = false)
    – godines
    Mar 21, 2019 at 18:54
  • 1
    I think there is some issue with sampling matrices. But you can always sample a vector of dimension m*n and then reshape it into a (m, n) matrix.
    – amrods
    Mar 26, 2019 at 0:45
8

If performance is not an issue (i.e. the sample range isn't too large, or the sample count is close to the sample range), and if you don't want to use an additional package for whatever reason, try:

a = randperm(100)[1:10]

1

unique(itr[, dim])

Returns an array containing only the unique elements of the iterable itr

unique([rand(1:100) for r in 1:20])[1:10]

Set()

A set is a collection of elements, just like an array or dictionary, with no duplicated elements.

{rand(1:100) for r in 1:20}[1:10]
1
  • 1
    This is not guranteed to run without errors. Also it might be very improbable for certain input.
    – reschu
    Mar 24, 2016 at 14:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.