Note that there are some explanatory texts on larger screens.

plurals
  1. POAlgorithm: optimal way to rearrange a list from one order to another?
    primarykey
    data
    text
    <p><b>EDIT:</b> I'm not sure that my original question is clear enough. I need an algorithm that will compute the minimal sequence of moves to rearrange an array from one order to another. It is known that both arrays will contain the same elements (no duplicates) and have the same length. For example:</p> <pre><code>reorder( ['d', 'a', 'c', 'b', 'e'], ['a', 'b', 'c', 'd', 'e'] ) </code></pre> <p>should return something like:</p> <pre><code>[ {move:'d', after:'b'}, {move:'c', after:'b'} ] </code></pre> <p>which indicates that I should first move the element 'd' to after 'b', then move 'c' to after 'b' and the array will be in the desired order.</p> <hr> <p>Background: I'm working on a project (moving most of the functionality in <a href="http://code.google.com/p/rtgui/" rel="nofollow noreferrer">rtgui</a> to the client-side, actually). Right now I'm working on sorting. Basically I have a list of divs that I want sorted in some arbitrary order. I can get the desired order as follows:</p> <pre><code>var hashes = { before: [], after: [], }; var els = $('div.interesting-class').toArray(); var len = els.length; for(var i = 0; i &lt; len; i++) hashes.before.push(els[i].id); els.sort(getSortComparator()); for(var i = 0; i &lt; len; i++) hashes.after.push(els[i].id); </code></pre> <p>Now <code>hashes.before</code> and <code>hashes.after</code> contain the unordered and ordered lists of element IDs. When reordering the list, the most expensive operation, by far, is actually moving the DOM elements around. I had been doing this as follows:</p> <pre><code>var c = $('#container-id'); $(els).each(function() { c.append(this); }); </code></pre> <p>This works, but is slower than necessary, since on average, only 2 or 3 elements really need to be moved. Therefore, <b>I need an algorithm that will compute the minimal sequence of moves to rearrange an array from one order to another</b> (in this case, operating on <code>hashes.before</code> and <code>hashes.after</code>). Can anyone suggest one or give any ideas?</p> <p>I've tried several general-purpose "diff" algorithms so far, but they didn't really give me what I wanted. I think what I need is like that, but more specialized.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload