作者:bj韩式尕伙 | 来源:互联网 | 2023-09-12 13:28
sort_by_this_array[4,2,1,3]<--Thisisarrayofattributegoal_id.sort_by_this_array[4,2,1
sort_by_this_array = [4,2,1,3] <-- This is array of attribute goal_id.
sort_by_this_array =[4,2,1,3] <——这是属性目标的数组。
& then I have my
然后是我的。
[, , , , , , ]
Result should be: id: 40, 12,13,7, 6,30, 25
结果应该是:id: 40、12、13、7、6、30、25
I'm thinking about 2 loops & it's definitely not the best way.
我在考虑两个循环,这绝对不是最好的方法。
3 个解决方案
1
You may want to use variation of sorting by selection where swapping would occur each time you find a 'todo' element for which its 'goal_id' attribute is equal to 'goal_id' from your array.
您可能希望通过选择使用排序的变化,在每次找到一个'todo'元素时,在这个元素的'goal_id'属性等于数组中的'goal_id'。
Todo = Struct.new(:id, :goal_id)
todos = [Todo.new(12,2), Todo.new(13,2),Todo.new(6,1), Todo.new(7,2), Todo.new(25,3), Todo.new(30,1), Todo.new(40,4)]
sort_by_this_array = [4,2,1,3]
j = 0
sort_by_this_array.each do |goal_id|
todos.each_with_index do |todo,i|
if todo.goal_id == goal_id
todos[i],todos[j] = todos[j],todos[i]
j += 1
end
end
end
I would reccommend reading some sources on the web about sorting by selection. As this is a simple variation of it http://www.sorting-algorithms.com/selection-sort
我会推荐在网上阅读一些关于选择排序的资料。因为这是它的一个简单变体http://www.sorting-algorithms.com/selection-sort
Unfortunately this solution will not preserve order of elements inside initial todos array, as each swapping changes the position on which todo element is located. So they will be sorted, but it will be not stable.
不幸的是,这个解决方案不会保留初始todos数组中元素的顺序,因为每次交换都会改变todo元素所在的位置。所以它们是有序的,但是不稳定。
Below stable solution with additional memory.
下面是稳定的解决方案和额外的内存。
j = 0
results = []
sort_by_this_array.each do |goal_id|
while idx = todos.index {|e| e.goal_id == goal_id}
results <