0

I'm working with a JavaScript canvas, and I'd like to recreate quite a common effect I've seen where moving particles create lines between them when then get close to each other.

My issue is that I'm essentially performing two loops inside each other. Please see pseudo code:

var particles = [ /* array of particles with x and y values */ ]
for(var i = 0; i < particles.length; i ++){
 for(var j = 0; j < particles.length; j ++){
 // check if j is close to i
 // if so, draw a line between them
 } 
}

First of all I found that this would double check one particle against itself. So I can add:

 if(i == j) continue

But then actually, I need a further case. For instance, if I have already checked when i = 1 and j = 8, I don't need to check when j = 1 and i = 8

Is there a common method of simplifying this checking procedure? I'm losing a fair bit of performance with the multiple checks.

asked Dec 9, 2014 at 12:14
1
  • 4
    Yes, for(var j = i+1 ...). Commented Dec 9, 2014 at 12:21

1 Answer 1

2

The usual way of saving effort here is

for(var j = i+1; j < particles.length; j++) {

This saves half of the comparisons in the naive double loop; and if you really do have to check every possible pair, you can't save any more than that.

answered Dec 9, 2014 at 12:32
2
  • 3
    I would also do "i < particles.length - 1" that way you won't go over your length. Commented Dec 9, 2014 at 12:34
  • @PieterB But if we loop with i < particles.length and start the iteration with i == particles.length - 1, then j = i + 1, so the test that j < particles.length will fail, so we'll stop both loops. Commented Aug 10, 2020 at 9:43

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.