Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Using a <code>heapq</code>. This is more complex than simply counting followed by sorting, but may be useful if we need a running sorted count.</p> <p>Using the Coffeescript translation of Python <code>heapq</code>, <a href="https://github.com/qiao/heap.js" rel="nofollow">https://github.com/qiao/heap.js</a></p> <pre><code>heap = require './heap' # adapted from # http://docs.python.org/2/library/heapq.html#priority-queue-implementation-notes pq = [] # list of entries arranged in a heap entry_finder = {} # mapping of tasks to entries REMOVED = '&lt;removed-task&gt;' counter = [0] remove_task = (task) -&gt; # Mark an existing task as REMOVED. return null if not found. entry = entry_finder[task] if entry? delete entry_finder[task] entry[entry.length-1] = REMOVED return entry count_task = (task) -&gt; entry = remove_task(task) if entry? [priority, count, _] = entry priority += 1 else counter[0] += 1 count = counter[0] priority = 1 entry = [priority, count, task] entry_finder[task] = entry heap.push(pq, entry) console.log h = ['one','two','one','three','four','two','one'] for task in h count_task(task) console.log entry_finder console.log pq alist = heap.nlargest(pq, 10) for x in alist [priority, count, task] = x if task != REMOVED console.log task, priority, count </code></pre> <p>produces</p> <pre><code>[ 'one', 'two', 'one', 'three', 'four', 'two', 'one' ] { three: [ 1, 3, 'three' ], four: [ 1, 4, 'four' ], two: [ 2, 2, 'two' ], one: [ 3, 1, 'one' ] } [ [ 1, 1, '&lt;removed-task&gt;' ], [ 1, 2, '&lt;removed-task&gt;' ], [ 2, 1, '&lt;removed-task&gt;' ], [ 1, 3, 'three' ], [ 1, 4, 'four' ], [ 2, 2, 'two' ], [ 3, 1, 'one' ] ] one 3 1 two 2 2 four 1 4 three 1 3 </code></pre>
 

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