Farid Blaster
Farid Blaster

Reputation: 984

how to make random percentage with dynamic array?

lets say we have datas:

var datas = [{animal:"chicken"}, {animal: "cow"}, {animal: "duck"}];
var after_massage = [];

datas.forEach(function(key){

   after_massage.push({animal: key.animal}, {percentage: randomPercent(); })

 })

Right now i dont know how to give each object got random percentage and total of 3 object cant be more than 100% percent

Upvotes: 0

Views: 2066

Answers (3)

Jack jdeoel
Jack jdeoel

Reputation: 4584

You want got random percentage and total of 3 object cant be more than 100% percent ,so need to reduce percent by got random number like this...

var datas = [{animal:"chicken"}, {animal: "cow"}, {animal: "duck"}];
var after_massage = [];
var percent = 100,
r = 0;
datas.forEach(function(key){    
   after_massage.push({animal: key.animal,percentage: randomPercent()});
 })

function randomPercent(){               
 percent = percent - r ;
 r = Math.floor(Math.random() * percent);
 return r;  
}
console.log(after_massage);

You will see total percent of 3 object is not more than 100.

Upvotes: 0

utxin
utxin

Reputation: 64

I am not sure what you want to achieve so its a little hard to formulate an answer. But you can go about it in 2 ways I could think of.

1) Split 1 by the length of your array (i.e. 1/3 = 33%) and then generate a random number like so:

function generateRandomPercentage(arrayLength){
    var maxPercentageValue = (1 / arrayLength) * 100;
    return Math.floor(Math.random() * maxPercentageValue );
}

2) Have a diminishing percentage value based on what percentage is left over.

var percentUsed = 0;

datas.forEach(function(key){
   var randomPercent = generateRandomPercentage(percentageUsed );
   percentUsed = percentUsed + randomPercent ;
   after_massage.push({animal: key.animal, percentage: randomPercent })
 });

function generateRandomPercentage(percentageRemaining){
        var maxPercentageValue = (100 - percentageRemaining);
        return Math.floor(Math.random() * maxPercentageValue );
}

Both methods will ensure you have a sum total of less than 100%.

Upvotes: 1

Phillip Chan
Phillip Chan

Reputation: 993

You can accomplish this by keeping track of a max number that your random number can hit and then keep decrementing. Theoretically, this can go on infinitely:

var datas = [{animal:"chicken"}, {animal: "cow"}, {animal: "duck"}];
var after_massage = [];
var max = 1;

var getRandomPercent = function(max) {
    var percentage = Math.random() * (max - 0) + 0;
    // every time we generate a random number, we'll decrement
    max = max - percentage;
    return percentage;
}

datas.forEach(function(key){
   after_massage.push({animal: key.animal, percentage: getRandomPercent(max) })
 });

console.log(after_massage);

See JSFiddle

Upvotes: 1

Related Questions