Using variables inside javascript for loop few times - javascript

I don't know how to name a title for my question. Here is the problem:
//Setup all the stats.
var randomStat = Math.floor(Math.random() * ((monster.level + 5) - monster.level + 1) + monster.level);
var multiplier = randomStat * itemQuality.qualityMultiplier;
//Assign the Stats.
var strength = Math.floor(multiplier * itemSubType.strengthMultiplier / 2); //divide each stat by 2 for better balance
var endurance = Math.floor(multiplier * itemSubType.enduranceMultiplier / 2);
var agility = Math.floor(multiplier * itemSubType.agilityMultiplier / 2);
var dexterity = Math.floor(multiplier * itemSubType.dexterityMultiplier / 2);
var wisdom = Math.floor(multiplier * itemSubType.wisdomMultiplier / 2);
var intelligence = Math.floor(multiplier * itemSubType.intelligenceMultiplier / 2);
var luck = Math.floor(multiplier * itemSubType.luckMultiplier / 2);
What it does, is create a randomStat variable and multiplier variable, then use them for each stat. My problem is that if each stat i.e. "strengthMultiplier" is the same as "enduranceMultiplier" which is the case sometimes, then stats will be exactly the same, because randomStat and multiplier is called just once and is used for every stat.
I am trying to create a loop for it, to call it 7 times, and each time its called use it for a single stat, up to 7 stats total.
I could of course create 2 new variables for each stat (total 14) but I hope there is better way to do that, using loops.
I am using javascript, so any help is welcome with javascript only, not jquery or anything else. Thanks :)

You might keep your stats in an array or an object (the latter shown here), and iterate over those:
var stats = {
strenght: null,
endurance: null,
agility: null,
dexterity: null,
wisdom: null,
intelligence: null,
luck: null
};
for (var stat in stats) {
// todo: consider using Object.hasOwnProperty here.
var randomStat = Math.floor(Math.random() * ((monster.level + 5) - monster.level + 1) + monster.level);
var multiplier = randomStat * itemQuality.qualityMultiplier;
stats[stat] = Math.floor(multiplier * itemSubType[stat + 'Multiplier'] / 2);
}
That would store values in a stats dict, i.e. as stats.luck instead of luck.

Related

Is there any problem with converting this excel formula to javascript?

Here is the excel formula:
=E2-(J2*2*G2)-(K2*E2*2)/30+IF((L2+M2)>60,((L2+M2)-60)*H2+60*G2,(L2+M2)*G2)+(N2/$AE$1)*$AE$2+(Q2*$AE$5+P2*$AE$4+O2*$AE$3)
Here what I tried (Javascript):
var E2 = $("#sentence").val();
var J2 = $("#deduction").val();
var G2 = 55145;
var K2 = $("#absence").val();
var L2 = $("#overtime").val();
var M2 = 0;
var H2 = 50050;
var N2 = $("#transportation").val();
var sixty;
if ((L2 + M2) > 60) {
sixty = ((L2 + M2) - 60) * H2 + 60 * G2;
} else {
sixty = (L2 + M2) * G2;
};
var result = E2 - (J2 * 2 * G2) - (K2 * E2 * 2) / 30 + sixty;
I couldn't find the way to conver this part of formula:
+(N2/$AE$1)*$AE$2+(Q2*$AE$5+P2*$AE$4+O2*$AE$3)
Here I found the problem:
Even if one of the variables sets to null, then the formula does not work properly.
It looks like some pretty basic math.
let total = (N2 / AE1) * AE2 + (Q2 * AE5 + P2 * AE4 + O2 * AE3 )
This is basically impossible to translate without seeing the actual spreadsheet but that should get you started. Also, make sure to take into consideration order of operations because the computer is going to evaluate it from left to right unless there are parenthesis (where it will evaluate those first).

Vue Js - Calculation Criteria in Reverse

Am Having situation where i had to reverse a calculation criteria to make it clear :
i have sub_total field which is editable and user can change the value of it
first the pre tax is applied to this sub_total and give me pre_total
second the vato tax is applied to the sum of ( sub_total and pre_total ) and give me vato_total
third the tx tax is applied to the sub_total and give me tx_total
the final step is the grand total which is the sum of sub_total + pre_total + vato_total + tx_total .
and here is the demonstration code of the above steps :
let subtotal_with_ewa = Number((this.subtotal_price / 100) * this.unit.reservation.prices.ewa_parentage) + Number(this.subtotal_price);
this.total_ewa = parseFloat((this.subtotal_price / 100) * this.unit.reservation.prices.ewa_parentage).toFixed(2)
this.total_vat = parseFloat((subtotal_with_ewa / 100 ) * this.unit.reservation.prices.vat_parentage).toFixed(2);
this.total_ttx = parseFloat((this.subtotal_price / 100) * this.unit.reservation.prices.tourism_percentage).toFixed(2);
this.total_price = parseFloat(subtotal_with_ewa + Number(this.total_vat) + Number(this.total_tourism)).toFixed(2);
this.unit.reservation.prices.total_price_raw = parseFloat(subtotal_with_ewa + Number(this.total_vat) + Number(this.total_ttx) ).toFixed(2);
this.unit.reservation.prices.total_price = this.unit.reservation.prices.total_price_raw ;
this.total_price = this.unit.reservation.prices.total_price ;
this.unit.reservation.prices.price = this.subtotal_price
and it's working perfect as the following screen shot
now the question is : what do i do to make the whole operation as reverse i mean what i had to do if i changed the grand total value i need to re-calcuate those values till get the sub_total again .... any ideas ?
You need to make computed properties they will recompute any time a dependancy is changed, for example:
subtotal_with_ewa(){
return Number((this.subtotal_price / 100) *
this.unit.reservation.prices.ewa_parentage) + Number(this.subtotal_price);
}
You can use getters and setters with computed properties or separate them from the bound v-model on the fields.
The below functions should solve the problem.
the function accepts the percentage of each tax as argument and returns a json will all the values.
function fromSubTotal(subTotal, pre, vato, tx) {
const preAmount = subTotal * pre / 100
const vatoAmount = (subTotal + pre) * vato / 100
const txAmount = subTotal * tx / 100
const total = subTotal + preAmount + vatoAmount + txAmount
return {subTotal, preAmount, vatoAmount, txAmount, total}
}
function fromTotal(total, pre, vato, tx) {
const subTotal = (total * 100) / (100 + pre + tx + (1.01 * pre * vato))
return fromSubTotal(subTotal, pre, vato, tx)
}
// eg.
console.log(fromSubTotal(100,1,1,1))
console.log(fromTotal(103.01,1,1,1))

How to use if-statement with randgen [duplicate]

This question already has answers here:
Random number, which is not equal to the previous number
(16 answers)
Closed 4 years ago.
I'm trying to make sure two randomly generated numbers don't match, is there a way to do this in an if-statement?
i'm fairly new to javascript and couldn't find anything that answered my question, rand2 and rand3 both pick from the same list and it would make the outcome seem odd if they matched. my code also stopped working when i put the if-statement in (if i messed that up i guess it wouldn't matter if i got an answer).
function sentence() {
var rand1 = Math.floor(Math.random() * 2);
var rand2 = Math.floor(Math.random() * 12);
var rand3 = Math.floor(Math.random() * 12);
var rand4 = Math.floor(Math.random() * 10);
var rand5 = Math.floor(Math.random() * 10);
var rand6 = Math.floor(Math.random() * 10);
// var randCol = [rand1,rand2,rand3,rand4,rand5];
// var i = randGen();
if (rand2 == rand3) {
// whatever changes one
} else {
//
}
You could use a do while statement that runs while the numbers are the same, therefore will terminate as soon as the random numbers generated are different.
e.g.
var rand2 = 1;
var rand3 = 1;
do {
rand2 = Math.floor(Math.random() * 12);
rand3 = Math.floor(Math.random() * 12);
} while(rand2 === rand3 );
Hope that helps :)

calculate multiple input value in javascript

I have 5 input fields (range sliders) and I'm trying to return a result when any of the input values changes.
The problem is "value4" is used 2 times in the equation and this is causing the problem. If I change "value4" my result does not change.
function output(){
var value1 = document.getElementById('NumberOfEmployees_input').value;
var value2 = document.getElementById('AverageSalary_input').value;
var value3 = document.getElementById('AverageTime_input').value;
var value4 = document.getElementById('WorkdaysWeek_input').value;
var value5 = document.getElementById('AccountingHours_input').value;
document.getElementById('saving').innerHTML =
(((parseInt(value1) * parseInt(value2))/(parseInt(value4) * parseInt(1920))) * (parseInt(value3) * parseInt(value4) * parseInt(48)))
+ (parseInt(value5) * parseInt(13500)) - parseInt(183600);
}
Can anybody give me a hint?
Thank you!
Your equation can be simplified, you added too many brackets (I removed the parseInt() function to make it more readable).
It is equivalent to:
value4 is canceled:
You may have made an error in your equation.
The code is very difficult to read. I suggest simplifying the code by first, shortening the variable names. Then apply parseInt at an early stage to reduce clutter afterwards.
Plus, there is no need to parseInt(123) since 123 is already Integer.
function output(){
var v1 = parseInt(document.getElementById('NumberOfEmployees_input').value);
var v2 = parseInt(document.getElementById('AverageSalary_input').value);
var v3 = parseInt(document.getElementById('AverageTime_input').value);
var v4 = parseInt(document.getElementById('WorkdaysWeek_input').value);
var v5 = parseInt(document.getElementById('AccountingHours_input').value);
var n = v1 * v2; // nominator
var d = v4 * 1920 * v3 * v4 * 48; // denominator
document.getElementById('saving').innerHTML = (n/d) + (v5 * 13500) - 183600;
}
Here is your equation
(
(
(parseInt(value1) * parseInt(value2))
/
(parseInt(value4) * parseInt(1920))
) *
(parseInt(value3) * parseInt(value4) * parseInt(48))
)
+ (parseInt(value5) * parseInt(13500))
- parseInt(183600);
v1 • v2
(----------- • v3 • v4 • 48) + (v5 • 13500) - 183600
v4 • 1920
// valueN has been substituted with vN
By observation, v4 cancels out.
This reduces your chain of math to
( (parseInt(value1)*parseInt(value2)*parseInt(value3)*48) / 1920 )
+ (parseInt(value5) * 13500)
- 183600;
Note that originally, v4 = 0 would fail. This may or may not be intended.
To make your code more readable you can separate the numerator and denominator as so
n = parseInt(value1) * parseInt(value2) * parseInt(value3) * 48
document.getElementById('saving').innerHTML = (n/1920) + (v5 * 13500) - 183600;
While this might not answer your question of using 2 input values, this provides a workaround in your situation. You didn't seem to realise this when you posted your question. Perhaps you misplaced a bracket or made an error in your calculations?

Conflict when trying to generate two separate numbers

I have the following script, which is meant to generate 2 different numbers
<script type="text/javascript">
function GenerateRandomNumber2to6No1() {
var min = 2, max = 7;
var random = Math.floor(Math.random() * (max - min + 1)) + min;
return random;
}
var GenerateRandomNumber2to6No1 = GenerateRandomNumber2to6No1();
$('.GenerateRandomNumber2to6No1').html(GenerateRandomNumber2to6No1);
function GenerateRandomNumber2to6No2() {
var min = 2, max = 7;
var random = Math.floor(Math.random() * (max - min + 1)) + min;
return (random !== GenerateRandomNumber2to6No1) ? random: GenerateRandomNumber2to6No2();
}
var GenerateRandomNumber2to6No2 = GenerateRandomNumber2to6No2();
$('.GenerateRandomNumber2to6No2').html(GenerateRandomNumber2to6No2);
</script>
NUMBER 1: <span class = "GenerateRandomNumber2to6No1"></span>
NUMBER 2: <span class = "GenerateRandomNumber2to6No2"></span>
This usually works fine but occasionally the page will load and no numbers will appear. I'm guessing this is when GenerateRandomNumber2to6No2 happens to generate the same number as GenerateRandomNumber2to6No1. I thought that
return (random !== GenerateRandomNumber2to6No1) ? random: GenerateRandomNumber2to6No2(); accounted for this, but perhaps instead of generating another unique number when there's redundancy, it generates no number at all. Is this the case? If so, how can I fix this?
Thanks!
function getRand(){
var array=[2,3,4,5,6,7]
var newArray=[];
for(var i=0;i<2;i++){
var ran=~~(array.length*Math.random());
newArray[i]=array.splice(ran,1)[0]
}
return newArray
}
var ranArray=getRand();
var ran1=ranArray[0];
var ran2=ranArray[1];
console.log(ran1,ran2)
getRand() is a function to give you an array of distinct numbers.Since you only need two,it only loop two times,and give you an array,which you can make use of it.
Back to your code,from what I see,Gno2 should keep running until it got another number,I don't know why.It's the time you try to debug.
First I will try to change the max=2 to max=3,if the code may not work for some number,then you can quickly realize and found out the problem is in these two functions.
Then try to log,console.log(Gno1,Gno2),see what exactly the numbers are,also help you to know where is the problem.
I think this piece of code can help you
var rand1,rand2;
var min = 3;
var max = 6;
do {
rand1 = Math.floor(Math.random() * (max - min)) + min;
rand2 = Math.floor(Math.random() * (max - min)) + min;
}while(rand1 === rand2);
$('.GenerateRandomNumber2to6No1').html(rand1);
$('.GenerateRandomNumber2to6No2').html(rand2);

Categories

Resources