Skip to content

Commit

Permalink
Fix crafting problem
Browse files Browse the repository at this point in the history
  • Loading branch information
diamondburned committed Mar 12, 2024
1 parent d03d2b9 commit f15615b
Show file tree
Hide file tree
Showing 3 changed files with 1,195 additions and 1,218 deletions.
56 changes: 19 additions & 37 deletions problems/crafting/generate_recipes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ async function main() {
),
);

const outputRecipes: { [key: string]: [string, string] } = {};
const outputRecipes: { [key: string]: string[] } = {};
for (const recipes of wantedRecipes) {
for (const recipe of recipes) {
if (recipe.result in outputRecipes) {
Expand All @@ -31,38 +31,27 @@ async function main() {
}
}

console.log(
"Got a total of",
Object.entries(outputRecipes).length,
"recipes",
);
console.log("Got a total of", Object.entries(outputRecipes).length, "recipes");

// Deduplicate all recipe ingredients.
for (const [result, ingredients] of Object.entries(outputRecipes)) {
outputRecipes[result] = [...new Set(ingredients)];
}

// Get the custom JSON formatting that we want.
let output = "{\n";
for (const [i, recipe] of Object.entries(outputRecipes).entries()) {
const [result, first, second] = [recipe[0], ...recipe[1]]
const lines = [];
for (const recipe of Object.entries(outputRecipes)) {
const [result, ...ingredients] = [recipe[0], ...recipe[1]]
.map((s) => sanitizeName(s))
.map((s) => JSON.stringify(s));

output += ` ${result}: [${first}, ${second}]`;
output += i === Object.keys(outputRecipes).length - 1 ? "\n" : ",\n";
lines.push(` ${result}: [${ingredients.join(", ")}],`);
}
output += "}\n";

console.log("Hash of output:", sha256(output, undefined, "base64"));
lines.sort();
lines.push(lines.pop().slice(0, -1)); // remove trailing comma
const output = "{\n" + lines.join("\n") + "\n}\n";

await Deno.writeTextFile(outputRecipesFile, output);

// outputRecipes.sort();
//
// // Get the custom JSON formatting that we want.
// let output = "[\n";
// for (const recipe of outputRecipes) {
// const [result, first, second] = recipe.map((s) => JSON.stringify(s));
// output += ` [${result}, ${first}, ${second}],\n`;
// }
// output += "]\n";
// await Deno.writeTextFile(outputRecipesFile, output);
console.log("Hash of output:", sha256(output, undefined, "base64"));
}

function sanitizeName(name: string): string {
Expand All @@ -79,10 +68,9 @@ function arrayEquals<T>(a: T[], b: T[]): boolean {
}

async function findRecipesForItem(item: string): Promise<Recipe[]> {
const worker = new Worker(
import.meta.resolve("./generate_recipes_worker.ts"),
{ type: "module" },
);
const worker = new Worker(import.meta.resolve("./generate_recipes_worker.ts"), {
type: "module",
});
const promise = new Promise<Recipe[]>((resolve, reject) => {
worker.onmessage = (event: MessageEvent<WorkerMessage>) => {
if (event.data.ok === true) {
Expand All @@ -98,13 +86,7 @@ async function findRecipesForItem(item: string): Promise<Recipe[]> {
worker.postMessage({ item });
try {
const recipes = await promise;
console.log(
"Got recipes for",
item,
"containing",
recipes.length,
"recipes",
);
console.log("Got recipes for", item, "containing", recipes.length, "recipes");
return recipes;
} finally {
worker.terminate();
Expand Down
22 changes: 12 additions & 10 deletions problems/crafting/problem.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
#!/usr/bin/env python3

from dataclasses import dataclass
import json
import typing
from logging import debug
Expand Down Expand Up @@ -30,7 +29,7 @@ def __init__(self, seed=0) -> None:
self.items.relevant_items = [x.lower() for x in self.items.relevant_items]

with open(RECIPES_JSON, "r") as f:
recipes = json.loads(f.read())
recipes: dict[str, list[str]] = json.loads(f.read())

# Randomly decide whether to collapse a recipe with the next one.
self.recipes = recipes.copy()
Expand All @@ -41,20 +40,23 @@ def __init__(self, seed=0) -> None:
# Remove any ingredients that are within our list of relevant items.
choosing = [x for x in choosing if x not in self.items.relevant_items]

if not choosing:
continue
for ingredient in choosing:
if not self.coin_flip(0.1):
continue

if self.coin_flip(0.1):
which = self.rand.choice(choosing)
index = ingredients.index(which)
debug(f"Collapsing ({which} = {self.recipes[which]}) into {result}")
debug(f"Collapsing {ingredient} = {self.recipes[ingredient]}")

# Replace the ingredient with its recipe.
index = ingredients.index(ingredient)
ingredients = (
ingredients[:index] + self.recipes[which] + ingredients[index + 1 :]
ingredients[:index]
+ self.recipes[ingredient]
+ ingredients[index + 1 :]
)

debug(f" new ingredients: {ingredients}")
self.recipes[result] = ingredients
del self.recipes[which]
del self.recipes[ingredient]

self.wanted = self.rand.sample(self.items.relevant_items, 6)

Expand Down
Loading

0 comments on commit f15615b

Please sign in to comment.