Random weighted number generator

by odiseo

JavaScript

/* 
 * Question 2
*/
//As data structures are not an important part of the problem, I'll simplify and use a simple javascript object
var cities = {
  'Seattle': 60,
  'Spokane': 21,
  'Olympia': 5
};
//Calling the function
console.log(getRandomWeighted(cities));

/*
* Returns any city by random, weighted by population
*/
function getRandomWeighted(cities) {
    //We'll need to see how much population weight all cities sum up
    var totalWeight = 0;
    for (var city in cities) {
        totalWeight += cities[city];
    }
    
    //Then we create a new array, where every incidence in population will be a member of the array
    var citiesWeights = [];
    var currentWeigth = 0;
    for (var city in cities) {
        var currentCity = cities[city];
        for (var i = 0; i < currentCity; i++) {
            citiesWeights[currentWeigth] = city;
            currentWeigth ++;
        }
    }
    
    //Generating a random array within the bounds of the new array, and returning its index
    var rand = Math.floor(Math.random()*totalWeight);
    var res = citiesWeights[rand];
    return res;
}