15

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

23

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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)
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.
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]

Comments

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 Comment

This is not guranteed to run without errors. Also it might be very improbable for certain input.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.