Recently got into this part of the code to remember. And I decided to write it down if it would be useful or interesting to anyone.
Algorithm
The easiest way to compare a recipe to the crafting window is to search by templates. Since we need to search for those cells that are required for crafting to be filled and for the rest of the cells to be empty.
Templates simulate the location of crafting within the specified position in the crafting window. For example, if the crafting window is 2x2 and the crafting size is 1x1 (oak logs (1) -> oak planks (2)):
Incoming crafting window 2x2: [0, 0, 0, 1], recipe: [1]
Template 1 (position 0;0) = [1, 0, 0, 0] = does not match
Template 2 (position 0;1) = [0, 1, 0, 0] = does not match
Template 3 (position 1;0) = [0, 0, 1, 0] = does not match
Template 4 (position 1;1) = [0, 0, 0, 1] = matches, recipe is executed
Considering that the templates are filled in automatically, the recipe can be compared by the crafting window with any size, as long as the craft itself is smaller than the crafting window.
Optimization
Checking each recipe directly is quite expensive. For optimization, just before the crafting check, the sum check was used - the IDs of the items in the crafting window (2x2, 3x3, etc.) are added up, when loading recipes, the IDs within the recipe is also added up. When searching for a craft, two sum numbers are simply compared and only then the recipe test begins.
The sum is verified as follows (let's say that 1 - boards, 2 - sticks):
Crafting window 2x2 (0, 1, 0, 1) = sum will be 2
Crafting window 2x2 (1, 0, 1, 0) = sum will be 2
Recipe for sticks 1x2 (1, 1) = sum also 2
Workbench recipe 2x2 (1, 1, 1, 1) = sum 4
Directly during the execution of the template algorithm, when a template is compared, the first non-matching element naturally interrupts the testing of the template and proceeds to create the next template. If testing of the template shows a match, the comparison stops and informs the system of a complete match with the craft.
p.s: ResCraft J2ME did not create templates dynamically because it did not have a flexible comparison algorithm. Pre-coded methods created templates manually for 2x2 and 3x3 crafting windows. To some extent, it was even faster than the modern algorithm.