Here is a challenge for me, How can I code this properly? I really need some help to deal with it...
It's about weighted - randomizing actually. I try to explain this step by step with my bad English :) Sorry if any unnecessary information is given here, I'll be glad if anyone can make this simpler...
Let's say we want to randomly pick a city name based on it's desired weight.
Here we have an array of objects containing those city names and our sample desired weight and each city distance from the west.
var list = [
{ name: "New York", distance: 4, weight: 1 },
{ name: "Atlanta", distance: 3, weight: 1 },
{ name: "Dallas", distance: 2, weight: 1 },
{ name: "Los Angeles", distance: 1, weight: 1 },
];
So New York is far and Los Angeles is near. Ok now, I can pick a city based on its weight using this function (It's not necessary to show you the code behind this but feel free to ask for it if you want to take a look at it).
var random_item = getRandomItem(name, weight);
console.log(random_item);
The result of this code is one of those cities, for example New York.
My problem is: after picking up the very first city, I want a new array of modified weights in order to:
A) give the already picked up city weight of 0 (this way it can not repeat again Note: this is not the problem).
B) modify the weight of remainder cities based on their distance from the last picked up city with this logic: as much as cities are far from last picked up city they get more weight. (in another word I want to pick up cities based on as far as they can be form last city that already is picked up...)
For instance: if New York is the first picked up city, then the New York weight should be 0, and as the distance from Los Angeles is 3 (New York.distance: 4 vs Los Angeles.distance: 1) add Los angles.weight a 3 and make it 4.
Any idea or solution is appreciated...
(3 - 4) + 1 = 0- you have two with Zero weights given your logic. I recommend not adding the current weight. that will provide a signed value as a weight that cannot repeat.