Question:
The user enters the number of emails and receives the total cost of the mailing. There is an array of number of post
letters and an array of prices for sending one letter from these prescurant
ranges
var post = [1000, 3000, 5000, 10000, 20000];
var prescurant = [0, 0.08, 0.07, 0.06, 0.05, 0.04];
- for the first 1000 letters, the user will give 0 rubles each;
- for letters from 1001 to 3000, he will give 0.08 rubles. for the letter;
- from 3001 to 5000 – 0.07 rubles each;
- etc.
- each letter over 20,000 costs 0.04 rubles.
How to calculate the total cost when the unit price changes in steps and these thresholds are set?
Tried like this:
var val=2000//введеные пользователем кол-во писем
for(i=0;i<post.length;i++){
for(j=0;j<prescurant.length;j++){
otv=(post[i]-post[i+1])*prescurant[j]
}
}
$("#otv").html(otv)
Answer:
Here's how to answer such questions.
var post=[1000,3000,5000,10000,20000],prescurant=[0,0.08,0.07,0.06,0.05,0.04],val=5001;
for(var i=0,otv=0;val>0;otv+=prescurant[i]*(val>(i?(post[i]-post[i-1]):post[i])?i?(post[i]-post[i-1]):post[i]:val),val-=i?(post[i]-post[i-1]):post[i],i++);
console.log(otv);