开发者

Combinatorial puzzler

开发者 https://www.devze.com 2023-03-03 01:15 出处:网络
I\'m wondering what the best way of solving the following problem is: I have at the moment a Map<String, Collection<String>>. Let\'s say its a map of meals with a collection of beverages

I'm wondering what the best way of solving the following problem is:

I have at the moment a Map<String, Collection<String>>. Let's say its a map of meals with a collection of beverages you could serve at that meal. E.g.

Breakfast - Orange Juice Breakfast - Coffee

Lunch - Orange Juice Lunch - Soda Lunch - Beer

Dinner - Soda Dinner - Beer Dinner - Wine

So my collection really is Map<Meal, Collection<Beverage>>

What I need to do is create a List<Map<String,String>>开发者_高级运维; of all the various combinations of beverages over the meals. I will have in this case 18 combinations. E.g.

[

[ Breakfast -> Orange Juice, Lunch -> Orange Juice, Dinner -> Soda ]

[ Breakfast -> Orange Juice, Lunch -> Orange Juice, Dinner -> Beer ]

[ Breakfast -> Orange Juice, Lunch -> Orange Juice, Dinner -> Wine ]

[ Breakfast -> Orange Juice, Lunch -> Soda, Dinner -> Soda, ]

etc... ]

I'm interested in seeing how others would go about creating the final collection.

Also, I'm using java, so nifty functional stuff is off limits.

Thanks

EDIT

Meal types are dynamic. That is, dinner could be removed from the list or brunch added.


If I got it right, there's no magic here, just iterate over 3 collections in a nested loop.

for (String breakfastBev : breakfast) {
  for (String lunchBev : lunch) {
    for (String dinnerBev : dinner) {
      System.out.println(breakfastBev + ", " + lunchBev + ", " + dinnerBev);
    }
  }
}

I'm sure now you can figure out how to do it with your Map and output List. :-)

EDIT: For the changed requirements, one way to do it is recursion:

main() {
    List<Map<String, String>> output = new ArrayList<Map<String, String>>();
    recordBeverages(new HashMap(), beveragesByMeal, output);
}

void recordBeverages(Map visited, Map meals, List<Map> output) {
    if(meals.isEmpty()) {
        output.add(visited);
    }
    String mealType = meals.keySet().iterator().next();
    Map remainingMeals = new HashMap(visited);
    remainingMeals.keySet().remove(mealType);
    for(Beverage bev : meals.get(mealType)) {
        Map newVisited = new HashMap(visited);
        newVisited.put(mealType, bev);    

        recordBeverages(newVisited, remainingMeals, output);
    }
}

Not tested, but you get ths idea.


Use an array of counters with as many counters as there are meals. In a loop increase the first one until it reaches the last beverage for the first meal and then increase the next on (trickling down). When the last beverage of the last meal is reached you are done.

I'll leave the code for that up to you.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号