While Loop Giving Wrong Output

While Loop Giving Wrong Output
0

#1

I am working on a challenge from codefights.com. Here is the description:

Some phone usage rate may be described as follows:

first minute of a call costs min1 cents,
each minute from the 2nd up to 10th (inclusive) costs min2_10 cents
each minute after 10th costs min11 cents.
You have s cents on your account before the call. What is the duration of the longest call (in minutes rounded down to the nearest integer) you can have?

Example

For min1 = 3, min2_10 = 1, min11 = 2 and s = 20, the output should be
phoneCall(min1, min2_10, min11, s) = 14.

Here’s why:

the first minute costs 3 cents, which leaves you with 20 - 3 = 17 cents;
the total cost of minutes 2 through 10 is 1 * 9 = 9, so you can talk 9 more minutes and still have 17 - 9 = 8 cents;
each next minute costs 2 cents, which means that you can talk 8 / 2 = 4 more minutes.
Thus, the longest call you can make is 1 + 9 + 4 = 14 minutes long.

Here is my code:

function phoneCall(min1, min2_10, min11, s) {
  let cents = s - min1;
  let minutes = 1;
  
  while (cents > 1) {
    minutes++;
    if (minutes <= 10) {
      cents -= min2_10;  
    }
    if (minutes > 10) {
      cents -= min11; 
    }
  }
  return minutes;
}

console.log(phoneCall(2,2,1,24));

My code outputs 13 when it should output 14. Where have I gone wrong?

Here are some of the tests:

phoneCall(3,1,2,20); phoneCall(10,1,2,22); phoneCall(1,2,1,6);

Thank you.


#2

I think maybe just

while (cents > 0)

?


#3

Just tried it, and it didn’t work


#4

I fail this test if I do that: phoneCall(10,1,2,22);


#5

What about
while (cents >= 1) ?


#6

I fail the same test, and phoneCall(1,2,1,6);


#7

I think the problem is that if you end on 0 cents, you get to keep the minute you just paid for but if you end on a negative number, you should give it back.

  if (cents == 0) return minutes;
  return minutes - 1;

try that


#8

I got it with this:

function phoneCall(min1, min2_10, min11, s) {
  let minutes = 1;
  let cents = s < min1 ? minutes = 0 : s - min1;
  
  while (cents > 0) {
    minutes++;
    if (minutes <= 10 && cents >= min2_10) cents -= min2_10;  
    if (minutes > 10 && cents >= min11) cents -= min11;
    if (minutes <= 10 && cents < min2_10 || minutes > 10 && cents < min11) cents = 0;
  }
  return minutes;
}