Reputation: 1
I would like to make a script that calculate how many "5" I need to reach 4.95 rating.
I created an object:
var obMed = {
5: 0,
4: 0,
3: 0,
2: 0,
1: 0
};
I got this function to update previous object with my rating
function upOB(a,b,c,d,e) {
obMed["5"] = a;
obMed["4"] = b;
obMed["3"] = c;
obMed["2"] = d;
obMed["1"] = e;
return obMed;
}
And this function to get the rating value
function med(obj) {
div = obj["5"] + obj["4"] + obj["3"] + obj["2"] + obj["1"];
somma = (obj["5"] * 5) + (obj["4"] * 4) + (obj["3"] * 3) + (obj["2"] * 2) + (obj["1"] * 1);
media = (somma/div).toFixed(2);
return media;
}
At this point I would like to add 1 to object["5"] until my average is greater than or equal to 4.95 but I'm really stuck.
I tried loops with no results, probably I wrote them bad.
Upvotes: 0
Views: 131
Reputation: 6327
If you do the equations you get the following relation (using the same variable names that your code uses)
function getNeed(div, somma) {
return Math.ceil((4.95*div - somma) / 0.05);
}
As I understand that div
is the total amount of votes sent, and somma
is the sum of all scores.
Math behind the method
current score: somma / div
if you add N
votes of 5 stars, the new score would be: (somma + N * 5) / (div + N)
If you want that to be equal to 4.95, then you do (somma + N * 5) / (div + N) = 4.95
, and the result is that:
N = (4.95*div - somma) / 0.05
Then you'll have to ceil that value as @dvsoukup commented, as you cannot have a non-integer amount of votes. This way, for example, you would have as a result 7 if the value of the computed N
was 6.72.
Upvotes: 1
Reputation: 10374
It's a math problem. You calculate your average in this way:
( k1*1 + k2*2 + k3*3 + k4*4 + k5*5 ) / (k1 + k2 + k3 + k4 + k5)
Where k1..5 is the number of votes. You want to know the number j of votes to reach 4.95.
Your position is:
( k1*1 + k2*2 + k3*3 + k4*4 + (k5+j)*5 ) / (k1 + k2 + k3 + k4 + k5+j) = 4.95
With some math passage, that I save you, your result is:
j = 79*k1 + 59*k2 + 39*k3 + 19*k4 - k5
Apply this formula and you will get your desired number
Coming back with javascript, you have to consider:
var missingFives = 79*obMed[1]+59*obMed[2]+39*obMed[3]+19*obMed[4]-obMed[5];
Upvotes: 0