I am a beginner of Javascript and trying to solve a problem in Javascript https://onlinejudge.org/external/116/11689.pdf How can I sum the remainder in for loop?
Here is the code that I came to so far...
function pant(e, f, c) {
let t=2;
for(let i=0;i<t;i++){
let pant=e+f;
let buy=pant/c;
let buy2=buy/c;
//total bottles
let total=buy+buy2;
let rem=total%c;
console.log(rem);
return total;
}}
This answer by uingtea is very accurate and uses the while loop. The same may be achieved by using recursion as shown below.
Code Snippet
// given "curr" number of caps and "cost" of each soda
// return number of sodas that can be purchased
const recurseCalc = (curr, cost) => {
// number of sodas is "curr" / "cost" (rounded to lower integer)
const numOfSodas = Math.floor(curr/cost);
// remaining caps is "curr" less caps paid to obtain "numOfSodas"
const remainingCaps = curr - (numOfSodas * cost);
// console-log to help understand each recursion
console.log(
'curr: ', curr,
'cost: ', cost,
'num: ', numOfSodas,
'rem: ', remainingCaps,
'curr >= cost: ', curr >= cost ? 'yes' : 'no'
);
// if "curr" caps is more than "cost" of a soda
// then, recursively calculate number of sodas
// else, zero sodas can be purchased (since "curr" is lower than "cost")
return (
curr >= cost
? numOfSodas + recurseCalc(
numOfSodas + remainingCaps,
cost
)
: 0
);
};
// use recursively calculate number of sodas
// for total caps (ie, "e" + "f")
const howManySodas = (e, f, c) => recurseCalc(e + f, c);
console.log('result\t---->| e: 9, f: 0, c: 3, sodas: ', howManySodas(9, 0, 3), ' |<---');
console.log('result\t---->| e: 5, f: 5, c: 2, sodas: ', howManySodas(5, 5, 2), ' |<---');
console.log('result\t---->| e: 7, f: 3, c: 3, sodas: ', howManySodas(7, 3, 3), ' |<---');
.as-console-wrapper { max-height: 100% !important; top: 0 }
Explanation
Inline comments added in the snippet above.
you need while loop and parseInt
function pant(e, f, c) {
let testNumber = `${e} ${f} ${c}`,
result = 0
e += f;
while (e >= c) {
result += parseInt(e / c)
e = e % c + parseInt(e / c)
}
console.log(`result for ${testNumber}: ${result}`)
}
pant(9, 0, 3)
pant(5, 5, 2)