What would be the optimal solution for the following problem?
I have
original_string = "This is a string that I am trying to sort"
I also have
array_to_sort = ['sort', 'string', 'This is', 'I', 'trying to', 'am', 'a']
I need to sort the array, so that elements are in the same order as in string. The elements are sometimes grouped together, but always in the same way as they are in string (i.e. there can be no ‘is This’ element in the array, only ‘This is’)..
All this is happening within the Rails application, so I was thinking of maybe taking the database approach and saving elements in database and then using some keys to reconstruct the original_string.. but maybe just doing some .sort trick is better.. The result does not necessarily have to be an array, can be anything..
Thanks for any input.
P.S. including an nlp tag, because this is a result of some nlp exercise.
The result is a new array, sorted by the position of the substring in the original string.
If you want to sort in-place (by changing the original array), you can use the
sort_by!method instead.Obviously, it’s too stupid to detect doubles (i.e.
"I am what I am", ["I am", "I am", "what"]will not be sorted as one hopes).EDIT Making it not quite so stupid is not quite so trivial: