← Back to puzzles

010 Alchemy

You are a medieval alchemist trying to figure out the recipes in a new grimoire. However, the recipes are written in a very convoluted and cryptic way, so it's difficult to figure out in which order to prepare the ingredients. Each recipe in the grimoire lists the ingredients necessary, but an ingredient might need to be crafted from other ingredients first.

Write a program that, given a recipe, outputs the order in which the ingredients need to be prepared. Recipes will be given as a set of ingredients and their prerequisites, in the format:

INGREDIENT: INGREDIENT1, INGREDIENT2, ...

Ingredients that appear only as prerequisites are base ingredients that can be prepared immediately. You can assume the recipe contains no circular dependencies.

Your program should output the order of preparation, with each ingredient separated by a comma. For example, given the recipe:

healing salve: herb paste
herb paste: crushed herbs

The program should output:

crushed herbs, herb paste, healing salve

If it's possible to prepare several ingredients, start with the ones that require the fewest prerequisite steps, e.g. base ingredients should be prepared before ingredients that have one prerequisite, and so on. If two ingredients are tied, prepare them in alphabetical order.

For example, given the recipe:

health potion: phoenix feather, moonwater
moonwater: water, moon dust
phoenix feather: feather, fire essence

The program should output:

feather, fire essence, moon dust, water, moonwater, phoenix feather, health potion

Finally, are you ready to craft the philosopher's stone? Given the recipe:

philosopher's stone: goldite, silverite, enchanted powder
goldite: raw ore, transmutation dust
silverite: raw ore, moonbeam
enchanted powder: fairy dust, transmutation dust

Your program should output:

fairy dust, moonbeam, raw ore, transmutation dust, enchanted powder, goldite, silverite, philosopher's stone

Good luck, and remember-as above, so below!