Cengiz Gonen Cengiz Gonen - 11 days ago 8
Javascript Question

How to make loop buy max amount?

I'm trying to my make my code buy the Max amount of Phones and Accessories. One Phone costs 99.99 and an Accessory costs 9.99. I have 1000 on my bank account. How do i make my code buy the max amount? My code buys currently 9 phones and 9 accessories. It should buy 9 phones and 10 accessories instead 9.



const ACCESSORY = 9.99;
const PHONE = 99.99;

var balance = 1000;
var total = 0;

var phones_total = 0;
var accessories_total = 0;

while (((total + PHONE) || (total + ACCESSORY)) < balance) {
total = total + PHONE;
phones_total = phones_total + 1;
if ((total + ACCESSORY) < balance) {
total = total + ACCESSORY;
accessories_total = accessories_total + 1;
}
}

console.log("total = " + total);
console.log("phones = " + phones_total);
console.log("accessories = " + accessories_total);




Answer

This line is wrong:

while (((total + PHONE) || (total + ACCESSORY)) < balance) {

This doesn't test whether either sum is less than balance. The value of (total + PHONE) || (total + ACCESSORY) is always total + PHONE unless that's 0, then it's total + ACCESSORY. And since total + PHONE is never 0, this is effectively equivalent to:

while ((total + PHONE) < balance) {

and it never tests whether there's available balance for just an accessory. The correct way to do this test is:

while ((total + PHONE) < balance || (total + ACCESSORY) < balance) {

You also should be using <= rather than <, to allow for using all your money exactly.

But then inside the loop, you still add PHONE to total, even if there was only enough balance left for an accessory. You need to check first.

const ACCESSORY = 9.99;
const PHONE = 99.99;

var balance = 1000;
var total = 0;

var phones_total = 0;
var accessories_total = 0;

while ((total + PHONE) <= balance || (total + ACCESSORY) <= balance) {
   if ((total + PHONE) <= balance) {
     total = total + PHONE;
     phones_total = phones_total + 1;
   }
   if ((total + ACCESSORY) <= balance) {
     total = total + ACCESSORY;
     accessories_total = accessories_total + 1;
   }
 }

console.log(phones_total, accessories_total);

A simpler way to do it is with arithmetic instead of a loop. Divide the balance by the cost of a phone + accessory, to find out the number of pairs you can afford. Then find out how many more accessories you can buy with what's left after that.

const ACCESSORY = 9.99;
const PHONE = 99.99;

var balance = 1000;

var phones_total = Math.floor(balance/(PHONE + ACCESSORY));
var remainder = balance - phones_total*(PHONE+ACCESSORY)
var accessories_total = phones_total + Math.floor(remainder/ACCESSORY);

console.log(phones_total, accessories_total);

Comments