# A better way to chose a random neighbor

**URL:** https://discourse.julialang.org/t/a-better-way-to-chose-a-random-neighbor/80979
**Category:** New to Julia
**Tags:** optimization
**Created:** [May 12, 2022, 8:36pm UTC](https://discourse.julialang.org/t/a-better-way-to-chose-a-random-neighbor/80979 "2022-05-12T20:36:12Z")
**Posts on this page:** 1
**Showing post:** 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: [May 12, 2022, 8:41pm UTC](https://discourse.julialang.org/t/a-better-way-to-chose-a-random-neighbor/80979/2 "2022-05-12T20:41:57Z")

</div>

> [@lsaravia](#):
>
> `x=[i,j] .+ rand(neighborhood)`

This allocates an array `[i,j]` on every iteration. Better to use a tuple `(i,j) .+ rand(neighborhood)`.

> [@lsaravia](#):
>
> ```julia
> # check boundaries
> if !(x[1] > fil || x[1] <1 || x[2] > col || x[2]<1)
> 
> ```

I would usually recommend employing [ghost cells](https://discourse.julialang.org/t/finite-difference-laplacian-with-five-point-stencil/25014/2) to avoid these kinds of boundary checks in inner loops.

---

_[View the full topic](https://discourse.julialang.org/t/a-better-way-to-chose-a-random-neighbor/80979)._
