简体   繁体   中英

Can't figure out how to iterate through loop

I'm writing a program that acts like a shopping cart. I am to make 5 album objects that inherit from the Album class. The Album class generates a random number for the quantity of the album. I am also supposed to create a Cart class. My initial amount of money is $1,000. I am to write a loop that iterates through my array of albums and purchase each one until I don't have enough money or there is no more of that particular album. As I iterate through the album; if I have enough money and the album is available, then I purchase it, deduct the money, and add it too the cart. I am having a real hard time with my loop. Any suggestions would be appreciated. As it stands now, my loop just iterates through the albums array once, which leaves me with somewhere around $800 left. Obviously, this is not what I want. I tried nesting a loop, but am still lost with the logic. Here is my code...

   /** Program Description: This program simulates purchases using a 
 * loop. The program creates two classes; an album class, and
 * a cart class. The initial amount of money is $1000.00. The program
 * iterates through all the albums and purchases each one, as
 * long as there is money left. Every time an album gets purchased 
 * the initial amount of money is decremented by the purchase
 * price. Each time an item is purchased, it gets added to the cart.
 * The program then displays all the items purchased in the cart.
 * It should show the album name, artist name, quantity purchased,
 * and sub total for each. It then shows the total purchase price,
 * and the amount of money left over  
 * 
 *  Pseudocode:
 *  
 *      Create a constructor for Album object
 *      Create classes that inherit from Album
 *          Store these classes in an array
 *      Create a constructor for Cart object
 *      Create a const variable for initial money
 *      Loop to simulate purchases
 *          Iterate over an array of albums
 *          Purchase each one as long as there is money left
 *          Decrement money by purchase price
 *          Add item to cart
 *      Display info                                                    **/

// Create a constructor for Album class

        function Album(title, artist, price){
            this.title = title;
            this.artist = artist;
            this.price = price;
            this.date = new Date();
            this.quantity = Math.floor((Math.random() * 10) + 1);
        };
        Album.prototype.purchase = function(){
            this.quantity--;
            if (this.quantity > 0){
                return 1;``
            }
            else{
                return -1;
            }
        };
    // Create objects that inherit from Album
        var pimpAButterfly = new Album("To Pimp a Butterfly", "Kendrick Lamar",  29.99);
        pimpAButterfly.tracklisting = ["Wesleys Theory", "For Free", "King Kunta", "Institutionalized", "These Walls"];

        var blameItAll = new Album("Blame It All On My Roots", "Garth Brooks", 29.98);
        blameItAll.tracklisting = ["Blame It All On My Roots", "Neon Moon", "Papa", "Thunder Rolls"];

        var killLights = new Album("Kill the Lights", "Luke Bryan", 20.83);
        killLights.tracklisting = ["Kick the Dust Up", "Kill the Lights", "Strip it Down", "Home Alone Tonight"];

        var platinum = new Album("Platinum", "Miranda Lambert", 20.61);
        platinum.tracklisting = ["Girls", "Platinum", "Little Red Wagon", "Priscilla", "Automatic"];

        var painKiller = new Album("PainKiller", "Little Big Town", 24.99);
        painKiller.tracklisting = ["Quit Breaking Up With Me", "Day Drinking", "Tumble and Fall", "Painkiller"];

    // Store these objects in an array
        var albums = [pimpAButterfly, blameItAll, killLights, platinum, painKiller];
    // Create a constructor for Cart class
        function Cart(val){
            this.items = [];
        };

        Cart.prototype.add = function(val){
            this.items.push(val);
        };

        Cart.prototype.remove = function(val){
            this.items.splice(albums.indexOf(val), 1);
        };

    //Create a constant variable for initial money
        var INITIAL_MONEY = 1000.00;

    // Create an instance of the Cart object
        var cart = new Cart();

    // Loop to simulate purchases
        var i = 0;
        while(INITIAL_MONEY > 0){
i = 0;


while(i < albums.length){
        //Purchase each one as long as there is money left
        if (INITIAL_MONEY >= albums[i].price){
            albums[i].purchase();
            //Decrement money by purchase price
            INITIAL_MONEY = INITIAL_MONEY - albums[i].price;
            //Add item to cart
            cart.add(albums[i]);
        }
        i++;
    };
};

console.log(INITIAL_MONEY);

        console.log(INITIAL_MONEY);
    //console.log("Album Name\tArtist Name\tQuantity\tSubtotal");

Like you described in your problem, you need to keep filling your cart with albums uniformly. Like this, until your money is officially gone, you'll add albums one by one (in the order you added them to the album list).

    while(INITIAL_MONEY > 0)
    {
        //don't forget to reset your counter!
        i = 0;
        while(i < albums.length)
        {
            //Purchase each one as long as there is money left
            if (INITIAL_MONEY >= albums[i].price){
                albums[i].purchase();
                //Decrement money by purchase price
                INITIAL_MONEY = INITIAL_MONEY - albums[i].price;
                //Add item to cart
                cart.add(albums[i]);
            }
            i++;
        }
    };

I see someone else already beat me to it in a comment though.

EDIT: Your problem description states that there is a certain amount of albums available for each album, so you'll probably have to add that if-statement in the inner while-loop, and deal with substracting the amount of albums whenever you put one in your cart.

EDIT2: The outer while-loop will forever keep executing unless by coicidence the last album you buy turns your last dollar into air. We must change the predicate in the outer while-loop to while (INITIAL_MONEY > cheapest_album_price). We need to find the lowest price first though, which is done by this lil script.

var cheapest_album_price = 999999; //is there something like int.MaxValue in javascript? Probably not.
for(var j = 0; j < albums.length; j++)
{
    if(cheapest_album_price > albums[j].price)
        cheapest_album_price = albums[j].price;
}

Now cheapest_album_price will contain the lowest price guarenteed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM