jeudi 5 mars 2020

Randomly grab three locations by slicing an array based off of comparison of location

I know my title was poorly written. I have an array and I am grabbing 3 random locations out of it. The third location can not be a restaurant. This will make sense when you see the code.

What I would like to do is make sure each location is at least 1 mile away from the previous location.

CODE: Here is my existing code. Currently it grabs three locations but they could be really close to each other.

for (let i = a.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [a[i], a[j]] = [a[j], a[i]];
}
let third = a[0];
let [first, second] = a.filter(l => !l.restaurant).slice(1);
let selectedLocations = [first, second, third];

function calculateDistance(lat1, lon1, lat2, lon2) {

            let Rm = 3961;
            let Rk = 6373

            lat1 = deg2rad(lat1);
            lon1 = deg2rad(lon1);
            lat2 = deg2rad(lat2);
            lon2 = deg2rad(lon2);

            let dlat = lat2 - lat1;
            let dlon = lon2 - lon1;

            let a  = Math.pow(Math.sin(dlat/2),2) + Math.cos(lat1) * Math.cos(lat2) * Math.pow(Math.sin(dlon/2),2);
            let c  = 2 * Math.atan2(Math.sqrt(a),Math.sqrt(1-a)); // great circle distance in radians
            let dm = c * Rm; // great circle distance in miles
            let dk = c * Rk; // great circle distance in km

            let mi = round(dm);
            let km = round(dk);
            let ft = Math.round(mi * 5280.0);

            return mi
}

    function deg2rad(deg) {
        let rad = deg * Math.PI/180; // radians = degrees * pi/180
        return rad;
    }

    function round(x) {
        return Math.round( x * 100) / 100;
    }

Remember the (third) location is grabbed first. Once I have the third location I would like to go through the array until I find another location at least 1 mile away from the third location.

This new location will become the (second) location and then once I have that location (second) I need to go through the array again and find one at least 1 mile away from it. This will be the final (first) location.




Aucun commentaire:

Enregistrer un commentaire