# How do I create an array with random unique numbers in a specific range?

**URL:** <https://discourse.julialang.org/t/how-do-i-create-an-array-with-random-unique-numbers-in-a-specific-range/115901>\
**Category:** New to Julia\
**Tags:** question, random\
**Created:** [June 20, 2024, 4:14am UTC](https://discourse.julialang.org/t/how-do-i-create-an-array-with-random-unique-numbers-in-a-specific-range/115901 "2024-06-20T04:14:31Z")\
**Posts on this page:** 1\
**Page:** 2

<div class="post-metadata">

**Author:** ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)\
**Post date:** [June 24, 2024, 11:53am UTC](https://discourse.julialang.org/t/how-do-i-create-an-array-with-random-unique-numbers-in-a-specific-range/115901/22 "2024-06-24T11:53:30Z")

</div>

> [@jbytecode](#):
>
> ```julia
> julia> @time sample(1:100000, 100, replace = false);
> 0.000013 seconds (8 allocations: 3.602 KiB)
> 
> ```

`@btime` (from BenchmarkTools.jl) is a much more reliable way to time fast calculations like this (it calls the code several times in a loop to ensure sufficient timer resolution, and then repeats the timing multiple times and reports the minimum time to reduce noise). It looks like `@time` is greatly overestimating the time for `sample` here:

```julia
julia> @btime sample(1:100000, 100, replace = false);
  2.285 μs (8 allocations: 3.60 KiB)

julia> @btime randperm(100000)[1:100];
  647.933 μs (3 allocations: 782.17 KiB)

julia> @btime shuffle(1:100000)[1:100];
  744.786 μs (3 allocations: 782.17 KiB)

```

and, for comparison, the first ChatGPT solution from above (modified to take parameters for the numbers):

```julia
julia> @btime generate_unique_random_integers(100000, 100);
  3.531 μs (11 allocations: 4.50 KiB)

```

(This is pretty fast! But beware that `generate_unique_random_integers(k, n)` by this algorithm is best when n \ll k so that the sampled integers are unique on the first try with high probability. For k - n \ll k, I think the expected runtime approaches \Theta(n^2). In fact, this is essentially the [`self_avoid_sample!` algorithm](https://github.com/JuliaStats/StatsBase.jl/blob/87f372ca912e5da94cbd7531d2fa5724832df98a/src/sampling.jl#L235-L279) in StatsBase.jl, which is [used by `sample`](https://github.com/JuliaStats/StatsBase.jl/blob/87f372ca912e5da94cbd7531d2fa5724832df98a/src/sampling.jl#L525) for n \ll k unordered sampling without replacement.)

[Previous page](https://discourse.julialang.org/t/how-do-i-create-an-array-with-random-unique-numbers-in-a-specific-range/115901.md?page=1)
