# Draw two distinct random integers from \`1:n\`

**URL:** https://discourse.julialang.org/t/draw-two-distinct-random-integers-from-1-n/72289
**Category:** Performance
**Tags:** statistics, performance, random
**Created:** [November 30, 2021, 11:46am UTC](https://discourse.julialang.org/t/draw-two-distinct-random-integers-from-1-n/72289 "2021-11-30T11:46:37Z")
**Posts on this page:** 1
**Showing post:** 16

<div class="post-metadata">

### Author: ![lmiq](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lmiq/32/18314_2.png) [@lmiq](https://discourse.julialang.org/u/lmiq)
#### Post date: [November 30, 2021, 12:54pm UTC](https://discourse.julialang.org/t/draw-two-distinct-random-integers-from-1-n/72289/16 "2021-11-30T12:54:41Z")

</div>

Yes, that. It is not completely evident that those index transformations are more expensive than a call to `rand()` though. (unfortunately to get the indexes right I would spend all day…). But a simple guess suggests that it might be something of the same order:

```julia
julia> function iter(n,draw)
           for i in 1:1000
               draw(n)
           end
           nothing
       end
iter (generic function with 1 method)

julia> function draw2(n)
           a = rand(1:n^2 - n)
           b = mod(a,n) + div(n^3,n) # <--- some random stuff
           if b >= a
               b += 1
           end
           a, b
       end
draw2 (generic function with 1 method)

julia> @btime iter(3,$draw2)
  13.623 μs (0 allocations: 0 bytes)

julia> function draw3(n)
           a = rand(1:n)
           b = rand(1:n-1)
           if b >= a
               b += 1
           end
           a, b
       end
draw2 (generic function with 1 method)

julia> @btime iter(3,$draw3)
  14.473 μs (0 allocations: 0 bytes)

```

---

_[View the full topic](https://discourse.julialang.org/t/draw-two-distinct-random-integers-from-1-n/72289)._
