# Robson » Little Red Book » Best buy

## Chapter 4 - Question 3

Many products are sold in a bewildering variety of pack size - 'large' is really small while 'giant' is a medium pack, and so on. Also, the quantity in each pack of a product range is rarely in a simple ratio, making the determination of which size is the most economical to purchase far from simple.

Design a program to deal with a three-pack range. The price per pack and the pack sizes are input as three pairs of numbers representing the pack price and contents in ascending order of pack size. The program determines the"best buy" and outputs the appropriate pack

### Solution 1

I wanted to expand the idea a little bit further, so my C++ solution will accept any number of comparisons. Example usage:

`C:\code>bestbuy 3 4 6 10 9 17Product 1: 0.75 per itemProduct 2: 0.6 per itemProduct 3: 0.529412 per itemBest value: Product 3C:\code>`
`#include <stdio.h>`
`#include <stdlib.h>`
` `
`using namespace std;`
` `
`int main(int argc, char *argv[])`
`{`
`    // if the user only enters one product or no products`
`    if (argc < 5)`
`       // show them how to use the program`
`       printf("Usage: bestbuy [price1] [quantity1] [price2] [quantity2] ...");`
`    else`
`    {   `
`        int iBest;`
`        // 5 = 1 / 7 = 2 / 9 = 3 / 11 = 4 etc`
`        float fPricePerItem[(argc-3)/2];`
`        // loop through each product`
`        for (int n = 0; n <= (argc-3)/2; n++)`
`        {`
`            // divide the price by the quantity`
`            fPricePerItem[n] = atof(argv[(n*2)+1]) / atof(argv[(n*2)+2]);`
`            // show the ratio`
`            printf("Product %d: %g per item\n", n+1, fPricePerItem[n]);`
`            // check if this is the first or the ratio is lower than the current best`
`            if (n == 0 || fPricePerItem[n] < fPricePerItem[iBest])`
`               // store as the current best buy`
`               iBest = n;`
`        }`
`        // show the best buy to the user`
`        printf("Best value: Product %d", iBest+1);`
`    }        `
`}`

## Log

• May 9, 2005 - Added solution 1.
© 2004-19 robson | cc unless stated