Reputation: 143
Imagine you have 3 items: a pen, a box and a car. You can have up to 9 pens, up to 5 boxes and up to 2 cars. How do you calculate the total value of every combination of items you could have?
Here's the code I currently have:
int maxPens = 9;
int maxBoxes = 5;
int maxCars = 2;
Double penPrice = 1.5;
Double boxPrice = 50.0;
Double carPrice = 150.0;
int penCount = 0;
int boxCount = 0;
int carCount = 0;
int totalCount = 1;
while (penCount <= maxPens) {
boxCount = 0;
while (boxCount <= maxBoxes) {
carCount = 0;
while (carCount <= maxCars) {
Double totalPrice = (penCount * penPrice) + (boxCount * boxPrice) + (carCount * carPrice);
System.out.println(totalCount + " = " + totalPrice);
totalCount++;
carCount++;
}
boxCount++;
}
penCount++;
}
This works and gives the output as the count of the combination, plus the total price, but feels really messy and if I then want to add another item I have to add more repeating into the method. Is it possible, for example, to do this using Maps where you might have:
Map<String, Integer> maxCountMap = new HashMap<String, Integer>();
Map<String, Double> priceMap = new HashMap<String, Integer>();
and iterate through these?
Upvotes: 1
Views: 46
Reputation: 3484
You can iterate through Map, but in my opinion the cleanest solution is to create a new class Item:
public class Item {
String name;
int max;
double price;
Item(String name, int max, double price) {
this.name = name;
this.max = max
this.price = price;
}
}
This class should contain getters and setters.
And use for loop instead of while:
Item pen = new Item(Pen, 5, 1.5)
Item box = new Item(Box, 5, 50.0)
Item car = new Item(Car, 2, 150.0)
for (int i; i<=pen.getMax; i++){
for (int j; j<=box.getMax; j++){
for (int k; k<=car.getMax; k++){
Double totalPrice = (i * pen.getPrice()) + (j * box.getPrice()) + (k * car.getPrice());
int total = i+j+k;
System.out.println(total + " = " + totalPrice);
}
}
}
Upvotes: 1