I am trying to create randomly placed SVG circles, but I don't want them to be too close to each other. I am using firestore for the backend and d3.js to create circles. Each circle is placed due to its "xValue" and "yValue" in firebase, which are generated using Math.random. These values (coordinates) should be created in a special different way to avoid too close circles.
My first approach was to use Math.random again but check all existing xValues and yValues to find the distance between the circle that I am about to create, then if the distance is lower than 80, increase Math.random value 100. It doesn't work
function createRandomCoordinates() {
var coordinates = [];
getDocs(collection(db, "circles")).then((querySnapshot) => {
querySnapshot.forEach((doc) => {
coordinates.push({ ...doc.data() });
})
});
let randomXValue = Math.floor(Math.random()*1200);
let randomYValue = Math.floor(Math.random()*1200);
var distances = [];
for (let i = 0; i < coordinates.length; i++) {
var a = coordinates[i].xValue - randomXValue;
var b = coordinates[i].yValue - randomYValue;
var distance = Math.sqrt(a * a + b * b);
distances.push(distance);
if(distances.some((e) => e < 80)){
return {
randXVal: randomXValue + 100,
randYVal: randomYValue + 100
}
}else {
return {
randXVal: randomXValue,
randYVal: randomYValue
}
}
}
}
console.log(createRandomCoordinates().randXVal,createRandomCoordinates().randYVal )