I recently wrote a similar question, but removed it because the question itself was not clear and sufficiently descriptive. So here goes:
I’m trying to rearrange a list of items in an array based on different patterns. For example, let’s say we have an array that looks like this:
var Items = ['l','w','m','m','w','h','l','w','m','m','w','h','l','w','h'];
Now, I would like to rearrange the items to map any of these patterns:
var Patterns = ['l', 'ww', 'hh' , 'wmm', 'mmw', 'hmm', 'mmh', 'mmmm'];
I don’t want to pick the items randomly, I would like to keep the chronological hierarchy of the items as close as possible, reading from left to right. Also, the pattern array is prioritized reading from left to right. ('l' is more important than 'ww' and so on.)
I’ll try to describe the process, step by step:
If we use the above Items array, we would like to check the first item: Items[0] and compare it to the Patterns array.
So:
Step 1. Items[0] (l) matches Patterns[0] (l) perfectly, so stop searching for more pattern combination and save this and continue from here.
Output: l, …
Step 2. Items[1] (w) matches Patterns[1] (w w) and Patterns[3] (w mm), continue searching since all pattern combinations that starts with or includes a 'w' is combined with another character.
Step 3 (continuing from Step 2). Items[1] (w) + Items[2] (m) matches Patterns[3] (wm m). Continue since Patterns[3] includes 3 characters (wmm)
Step 4 (continuing from Step 3). Items[1] (w) + Items[2] (m) + Items[3] (m) matches Patterns[3] (wmm). Close and save since it's a perfect match.
Output: l, w, m, m, …
Step 5. Items[4] (w) matches Patterns[1] (w w) and Patterns[3] (w mm), continue searching since all pattern combinations that starts with or includes a 'w' is combined with another character.
Step 6. (continuing from Step 5). Items[5] (h) does not match any pattern combinations starting with 'w' (previous step) so: grab and move the nearest 'w' which in this case is Items[7] and combine with Items[4] (previous step) since it's a match of Patterns[1] (ww) and Patterns[1] is more important (prioritized) than Patterns[3] because we read the array from left to right.
Output: l, w, m, m, w, w, …
Continue...
There might be impossible to combine the last or the two characters from the Items array, not sure. Here is the complete output (if my counting is correct) of the above Items array after steping thru all combinations:
Output: l, w, m, m, w, w, h, h, l, m, m, w, l, w, h
Do anyone know how this might be done using Javascript?