以下问题的最佳解决方案是什么?
我有
original_string = "This is a string that I am trying to sort"
我也有
array_to_sort = ['sort', 'string', 'This is', 'I', 'trying to', 'am', 'a']
我需要对数组进行排序,以便元素的顺序与字符串的顺序相同元素有时被组合在一起,但总是以与字符串中相同的方式(即数组中不能有“is This”元素,只能有“This is”)。。
所有这些都是在Rails应用程序中发生的,所以我考虑采用数据库方法,将元素保存在数据库中,然后使用一些键来重建原始的字符串但也许只是做点什么。分类技巧更好结果不一定非得是数组,可以是任何…
谢谢你的意见。
包括nlp标签,因为这是一些nlp练习的结果。
最佳答案
array_to_sort.sort_by { |substr| original_string.index(substr) }
结果是一个新数组,按子字符串在原始字符串中的位置排序。
如果要就地排序(通过更改原始数组),可以改用
sort_by!
方法。很明显,检测到双打太愚蠢了(即
"I am what I am", ["I am", "I am", "what"]
不会像人们希望的那样被分类)。编辑使它不那么愚蠢并不那么微不足道:
def get_all_positions(str, substr)
pattern = Regexp.new('\b' + Regexp::escape(substr) + '\b')
result = []
pos = -1
while match = pattern.match(str, pos + 1)
pos = match.offset(0)[0] + 1
result << pos
end
result
end
def sort_array_according_to_string(arr, str, i=0, positions=nil)
positions ||= Hash.new
if i < arr.count
current = arr[i]
current_positions = get_all_positions(str, current)
result = []
current_positions.each do |pos|
if !positions[pos]
positions[pos] = [pos, i, current]
result += sort_array_according_to_string(arr, str, i + 1, positions)
positions.delete(pos)
end
end
else
sorted = positions
.values
.sort_by { |position, i| position }
.map { |position, i| arr[i] }
result = [sorted]
end
if i == 0
result.uniq!
end
result
end
original_string = 'this is what this is not'
example_array = ['this', 'is', 'is not', 'what', 'this']
solution = sort_array_according_to_string(example_array, original_string)
puts solution.inspect