Detecting object collision with spatial partitioning in JavaScript - javascript

I'm trying to create a system of many objects that preform an action when they collide with each other, I'm using the P5.min.js library.
I've set up an array for the grid and an array for the objects, but I can't figure out the right way to go through each grid cell and check only the objects inside that cell before moving on to the next cell.
Here's what I've got so far
let molecules = [];
const numOfMolecules = 100;
let collisions = 0;
let check = 0;
let maxR = 10; //max molecule radius
let minR = 2; //min molecule radius
let numOfCol = 5;
let numOfRow = 5;
let CellW = 600/numOfCol; //gridWidth
let CellH = 600/numOfRow; //gridHeight
let remain = numOfMolecules;
let gridArray = [];
function setup() {
createCanvas(600, 600);
background(127);
for (let i = 0; i < numOfMolecules; i++) {
molecules.push(new Molecule());
}
}
function draw() {
background(127);
molecules.forEach(molecule => {
molecule.render();
molecule.checkEdges();
molecule.step();
});
drawGrid();
splitIntoGrid();
collision();
displayFR();
}
function drawGrid() {
for (i = 0; i < numOfRow+1; i++){
for (j = 0; j < numOfCol+1; j++){
noFill();
stroke(0);
rect(CellW*(j-1), CellH*(i-1), CellW, CellH);
}
}
}
function splitIntoGrid(){
for (let i = 0; i < numOfRow; i++){
for (let j = 0; j < numOfCol; j++){
tempArray = [];
molecules.forEach(molecule => {
if (molecule.position.x > (CellW*j) &&
molecule.position.x < (CellW*(j+1)) &&
molecule.position.y > (CellH*i) &&
molecule.position.y < (CellH*(i+1))) {
tempArray.push(molecule.id);
}
});
}
}
}
How I'm checking collision between all objects:
function collision() {
for (let i=0; i < molecules.length; i++){
for (let j=0; j < molecules.length; j++){
let diff = p5.Vector.sub(molecules[j].position, molecules[i].position);
check++;
if (i != j && diff.mag() <= molecules[j].radius + molecules[i].radius){
collisions++;
molecules[j].changeColor();
}
}
}
}
As far as I can see, I need to put these for loops inside another one going through each cell in the grid, but I don't know how to limit the search to which ever tempArray(s) the object is in
If this makes any sense, this is what I'm trying to do
function collision() {
for (let k = 0; k < gridArray.length; k++){
for (let i=0; i < gridArray.tempArray.length; i++){
for (let j=0; j < gridArray.tempArray.length; j++){
let diff = p5.Vector.sub(gridArray.tempArray[j].position, gridArray.tempArray.position);
check++;
if (i != j && diff.mag() <= gridArray.tempArray[j].radius + gridArray.tempArray[i].radius){
collisions++;
gridArray.tempArray[j].changeColor();
gridArray.tempArray[i].changeColor();
}
}
}
}
}

The grid cell is represented by an array of array gridArray. You need to have a collection of molecules for each grid cell. My recommendation would be to use Sets instead of an Array since the order is irrelevant. The idea is to be able to access the set of molecules on a given grid cell (i,j) with the syntax:
gridArray[i][j]
The following code will create an array of numOfRow arrays:
const numOfRow = 5;
const gridArray = (new Array(numOfRow)).fill([]);
gridArray with look like this:
[ [], [], [], [], [] ]
Inside splitIntoGrid you are checking which molecules are in which grid cells. This is good. However, for each grid cell, you are overwriting the global variable tempArray. Therefore, at the end of the function's execution, tempArray will only hold the molecules of the last grid cell, which isn't what you want. For a given grid cell, we will add the right molecules to a Set associated with this grid cell.
The Set data structure has an #add method which appends a new element to the set:
function splitIntoGrid() {
for (let i = 0; i < numOfRow; i++) {
for (let j = 0; j < numOfCol; j++) {
gridArray[i][j] = new Set();
molecules.forEach(molecule => {
if (molecule.position.x > (CellW*j)
&& molecule.position.x < (CellW*(j+1))
&& molecule.position.y > (CellH*i)
&& molecule.position.y < (CellH*(i+1))) {
gridArray[i][j].add(molecule);
}
});
}
}
}
Now you're ready to check for collisions on each grid cells. We will have a total of four loops inside one another. Two to navigate through the grid and two to compare the molecules that are contained inside each grid cell:
function collision() {
for (let i = 0; i < numOfRow; i++) {
for (let j = 0; j < numOfCol; j++) {
gridArray[i][j].forEach(moleculeA => {
gridArray[i][j].forEach(moleculeB => {
const diff = p5.Vector.sub(moleculeA.position, moleculeB.position);
if (moleculeA != moleculeB && diff.mag() <= moleculeA.radius + moleculeB.radius) {
collisions++;
moleculeA.changeColor();
moleculeB.changeColor();
}
});
});
}
}
}
In the above code, #forEach comes in handy.

Related

Code stops execution without throwing error

I am trying to implement Conway's game of life using checkboxes. In theory I should start with some checkbox checked randomly (and possibly some other manually checked by the user) and then go to the next generation by hitting a button. The code I made so far starts with just unchecked checkboxes (the random part is a detail I will care about later).
Here's my code:
function createBoard( rows = 30, columns = 50 ) {
let board = document.createElement('div');
document.body.appendChild(board);
for(let i = 0; i < rows; i++) {
let row = document.createElement('div');
for(let j = 0; j < columns; j++) {
let checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.className = "cb";
row.appendChild(checkbox);
}
board.appendChild(row);
}
}
function nextGen( rows = 30, columns = 50 ) {
function neighbourhood( r, c ) {
let sum = 0;
for( let i = -1; i < 2; i++ ) {
for( let j = -1; j < 2; j++ ) {
if( r + i >= 0 && c + j >= 0 && r + i < rows && c + j < columns && (i || j) ) {
sum += current[r+i][c+j];
}
}
}
return sum;
}
let checkboxes = document.querySelectorAll('.cb');
const flatBoard = Array.prototype.map.call(checkboxes, cb => cb.checked);
let current = flatBoard.reduce((cur, cb, i) => (!(i%columns) ? cur.push([cb]) : cur[cur.length-1].push(cb)) && cur, []);
let counter = 0;
console.log("ONE");
for(let i = 0; i < rows; i++) {
for(let j = 0; j < columns; j++) {
console.log("TWO");
const sum = neighbourhood(i,j);
checkboxes[counter++].checked = sum == 3 || current[i][j] && sum == 2;
}
}
}
createBoard();
let nextButton = document.getElementById('next');
nextButton.addEventListener('click', nextGen, false);
<button id="next">Next</button>
Does anyone know why when you hit the button, the first console.log() is being executed while the second is not?
nextGen is called with an argument that is determined by the DOM API: the event object. This will be the first argument and set the parameter variable rows. This means the for condition on rows will be false and so you have no iterations of the outer for loop.
To fix this particular problem, make sure that nextGen is called without any arguments:
nextButton.addEventListener('click', () => nextGen(), false);

How to print a 2d matrix using JS?

I created a sudoku solver in python. I want to display it in a 9X9 grid but don't know how to do it. I think javascript can be used for this, but I don't have much idea about that language. Can someone provide me some suggestions on how to do it?
Bro here i present a code for you in which you can display a 9*9 board in the webpage whose elements are inserted by the user itself. The code starts...
function InputBoard(){
var Board = new Array(9); // Create one dimensional Array
for (var i = 0; i < Board.length; i++) { // create 2D Array using 1D
Board[i] = [];
}
var index = 0;
var s =prompt("Enter Elements");
for (var i = 0; i < 9; i++) {
for (var j = 0; j < 9; j++) { // Initialize 2D array elements
Board[i][j] = s[index++];
}
}
for (var i = 0; i < 9; i++) {
for (var j = 0; j < 9; j++) {
document.write(Board[i][j] + " "); // Display 2D Array
}
document.write("<br>");
}
return Board;
}
InputBoard();

how to fill in the value in the array

i have code like this in actionscript3,
var map: Array = [
[[0,1,0],[0,1,0]],
[[0,1,0], [0,1,0]]];
var nom1: int = 0;
var nom2: int = 0;
var nom3: int = 1;
var nom4: int = 18;
stage.addEventListener (Event.ENTER_FRAME, beff);
function beff (e: Event): void
{
map[nom1][nom2][nom3] = nom4
}
stage.addEventListener (MouseEvent.CLICK, brut);
function brut(e: MouseEvent):void
{
trace (map)
}
when run, it gets an error in its output
what I want is to fill in each "1" value and not remove the "[" or "]" sign
so when var nom1, var nom2 are changed
Then the output is
[[[0,18,0],[0,18,0]],
[[0,18,0],[0,18,0]]]
please helps for those who can solve this problem
If what you want to achieve is to replace every 1 by 18 in this nested array, you could try :
for (var i = 0; i < map.length; i++) {
var secondLevel = map[i];
for (var j = 0; j < secondLevel.length; j++) {
var thirdLevel = secondLevel[j];
for (var k = 0; k < thirdLevel.length; k++) {
if (thirdLevel[k] === 1) {
thirdLevel[k] = 18;
}
}
}
}
Note that, this would only work for nested arrays with 3 levels of depth

Merge two arrays by value

I have a specific cuestion about merge arrays:
I'm using google charts and I need to do something like this
Combo Chart
To do something like that I need to fill this matrix
I did fine with axis x and axis y:
$scope.data= [];
$scope.data[0]= ['Months'];
angular.forEach($scope.consultors, function(consultor) {
$scope.data[0].push(consultor.no_user);
})
angular.forEach(months, function(month) {
$scope.data.push([month])
})
but, my problem is when i try to put $scope.relatorias, inside of $scope.data.
This is $scope.relatorias, this variable has the data of every consultor group by month, like this:
If you open each array look like this
I just need push ganancias_netas, but my problem is when there is an empty month, for example anapaula has data in every month but renato hasn't.
I have try to user for or for each but is doesn't work, I'm not an expert in matrix and this is my first time working on it.
fiddle: http://fiddle.jshell.net/rfcabal/5ftw7c8d/
/// UPDATE ///
I added this code that first fill with 0 $scope.data and then search for the values in relatorios and shoudl fill $scope.data, but for some reason jus fill with the last found value.
for (var i = 1; i < $scope.data.length; i++) {
for (var a = 1; a < $scope.data[0].length; a++) {
$scope.data[i][a] = 0;
for (var b = 0; b < $scope.relatorios[a-1].length; b++) {
console.log(a-1+' '+b+' '+3);
console.log($scope.relatorios[a-1][b]['ganancias_netas'])
$scope.data[i][a] = $scope.relatorios[a-1][b]['ganancias_netas'];
}
}
}
Thanks for your help
I just solved with 2 for
First i fill every data space with 0
for (var i = 1; i < $scope.data.length; i++) {
for (var a = 1; a < $scope.data[0].length; a++) {
$scope.data[i][a] = 0;
}
}
The i jus remplace where fecha_emision equal to position 1 of every array.
for (var a = 0; a < $scope.relatorios.length; a++) {
for (var b = 0; b < $scope.relatorios[a].length; b++) {
for (var i = 1; i < $scope.data.length; i++) {
var index = $scope.data[i].indexOf($scope.relatorios[a][b]['fecha_emision']);
if(index >= 0) {
$scope.data[i][a+1] = parseFloat($scope.relatorios[a][b]['ganancias_netas']);
}
}
}
}

detecting range overlaps in Google Calendar-Style event list

I need help fixing my existing code to accomplish what I am trying to do.
with the following sample data:
var SAMPLE_DATA = [{start: 30, end: 150}, {start: 540, end: 600}, {start: 560, end: 620}, {start: 610, end: 670}];
I need to do the following:
iterate through each sample object
determine if the current objects range (obj.start:obj.end) overlaps with any other object ranges.
record the total number of overlaps for that object into totalSlots property
determine the "index" of the object (used for it's left-to-right positioning)
mockup of what I am trying to accomplish:
As you can see in the mockup, slotIndex is used to determine the left-to-right ordering of the display. totalSlots is how many objects it shares space with (1 meaning it is the only object). 100 / totalSlots tells me how wide the square can be (i.e. totalSlots=2, means it is 100 / 2, or 50% container width).
Current Output from my code
Obj[0] slotIndex=0, totalSlots=0
Obj[1] slotIndex=1, totalSlots=1
Obj[2] slotIndex=1, totalSlots=2
Obj[3] slotIndex=0, totalSlots=1
expected/desired output from my code:
Obj[0] slotIndex=0, totalSlots=0
Obj[1] slotIndex=0, totalSlots=1
Obj[2] slotIndex=1, totalSlots=2
Obj[3] slotIndex=0, totalSlots=1
the code:
detectSlots: function(oldEventArr) {
oldEventArr.sort(this.eventSorter);
var newEventArr = [],
n = oldEventArr.length;
for (var i = 0; i < n; i++) {
var currObj = oldEventArr[i];
if ('undefined' == typeof currObj.totalSlots) {
currObj.slotIndex = 0;
currObj.totalSlots = 0;
}
for (var x = 0; x < n; x++) {
if (i == x) {
continue;
}
var nextObj = oldEventArr[x];
if (currObj.start <= nextObj.end && nextObj.start <= currObj.end) {
currObj.totalSlots++;
nextObj.slotIndex++;
}
}
newEventArr.push(currObj);
}
return newEventArr;
}
Please help me figure out what is going wrong in my code. I'm about 90% sure the problem lies in the if(currObj.start <= nextObj.end && nextObj.start <= currObj.end) statement where I am assigning/incrementing the values but I could use an extra set of eyes on this.
The slotIndex value can be calculated by using graph colouring algorithm. Note that brute force algorithm is exponential in time and will only be a viable solution for a small set of overlapping slots. Other algorithms are heuristics and you won't be guaranteed the least slot possible.
Here is an example of heuristic for your problem:
...
// init
var newEventArr = [], n = oldEventArr.length;
for (var i = 0; i < n; i+=1) {
var currObj = oldEventArr[i];
newEventArr.push({"start":currObj.start,"end":currObj.end,"slotIndex":undefined,"totalSlots":0});
}
var link = {};
// create link lists and totals
for (var i = 0; i < n; i+=1) {
var currObj = newEventArr[i];
if (!link.hasOwnProperty(""+i))
link[""+i] = {};
for (var j = i+1; j < n; j+=1) {
var nextObj = newEventArr[j];
var not_overlap = (currObj.end <= nextObj.start || nextObj.end <= currObj.start);
if (!not_overlap) {
currObj.totalSlots+=1;
nextObj.totalSlots+=1;
link[""+i][""+j] = 1;
if (!link.hasOwnProperty(""+j))
link[""+j] = {};
link[""+j][""+i] = 1;
}
}
}
var arrities = [];
for (var i = 0; i < n; i+=1) {
arrities.push( {"arrity":newEventArr[i].totalSlots, "indx":i} );
}
// sort by arrities [a better solution is using a priority queue]
for (var i = 0; i < n-1; i+=1) {
var current_arrity = -1, indx = -1;
for (var j = i; j < n; j+=1) {
if (arrities[j].arrity > current_arrity) {
indx = j;
current_arrity = arrities[j].arrity;
}
}
var temp = arrities[i];
arrities[i] = arrities[indx];
arrities[indx] = temp;
}
for (var i = 0; i < n; i+=1) {
var nodeIndex = arrities[i].indx;
// init used colors
var colors = [];
for (var j = 0; j < n; j+=1) {
colors.push(0);
}
//find used colors on links
for (var k in link[""+nodeIndex]) {
var color = newEventArr[k].slotIndex;
if (color || color === 0)
colors[color] += 1;
}
//find the first unused color
for (var j = 0; j < n; j+=1) {
if (colors[j] <= 0) {
// color the node
newEventArr[nodeIndex].slotIndex = j;
break;
}
}
}
return newEventArr;
...
like this
var not_overlap = (currObj.end <= nextObj.start || nextObj.end <= currObj.start);
if (!not_overlap) { ...
or
var overlap = (currObj.end > nextObj.start && nextObj.end < currObj.start);
if (overlap) { ...

Categories