If you have some information or images stored in an array and every time you wish to show those things in random order, then you may need to shuffle the array. Fisher-Yates algorithm is one of the efficient algorithms that can be implemented to achieve this task.

Suppose we have an array a[] containing n elements. The modern Fisher-Yates algorithm follows the given steps-

Iterate through the array from i=n to 1 (assuming the array starts from 0 and we will skip the first element). So, the loop runs n-1 times.

At each iteration,choose a random number j between 0 and i and select the random element a[j].

Swap a[i] and a[j].

To generate the random number we will use the JavaScript’s built-in math function Math.random() which returns any floating number between 0 and 1. Since, we need an integer we will round it up using Math.floor() function.

Knowing how to handle collision between different objects of varying shapes will come in handy if you are into game development or just enjoy solving algorithmic problems. In this post I discussed the conditions to determine the collision between circles, non-rotated rectangles and collision between rectangle and circle.

Circle-Circle collision

Two circles collide if the distance between them is less than the sum of their radii. i.e

The distance is calculated using Pythagoras formula by taking the sum of the square of the differences of x-coordinates and y-coordinates of two circles and square rooting them.

Now, let’s write the code-

var c1={
x:30,
y:25,
r:10;
}
var c2={
x:20,
y:25,
r:10;
}
var dx=c1.x-c2.x,
dy= c1.y-c2.y,
dist=Math.sqrt(dx*dx+dy*dy),
rdist=c1.r+c2.r;
if(dist<=rdist){
console.log("Collision detected!");
}

Rectangle-Rectangle Collision

Rectangles collide if there is no gap between them and here the rectangles considered must be non-rotating.

We find the closest point of the rectangle from the circle’s center. If the distance of this point from the center is less than the radius, then the two shapes collide. The nearest point is found by clamping circle’s center to rectangle’s coordinates.

var circle={
x:40,
y:60,
r:20;
}
var rect={
x:35,
y:50,
w:100,
h:50;
}
var nX=circle.x-Math.max(rect.x,Math.min(circle.x,rect.x+rect.w),
nY=circle.y-Math.max(rect.y,Math.min(circle.y,rect.y+rect.h);
if(nX*nX+nY*nY<=circle.r*circle.r){
console.log("Collision!");
}

Note that the rectangle here must not also be rotated.