Just another update

This commit is contained in:
Ingy döt Net 2015-02-20 00:35:01 -05:00
parent a25938f123
commit 00a190b0a6
6591 changed files with 94363 additions and 23227 deletions

View file

@ -1,6 +1,7 @@
{{Data structure}}
[[File:Fifo.gif|frame|right|Illustration of FIFO behavior]]
Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion.
Implement a FIFO queue.
Elements are added at one side and popped from the other in the order of insertion.
Operations:
* push (aka ''enqueue'') - add element

View file

@ -0,0 +1,10 @@
( queue
= (list=)
(enqueue=.(.!arg) !(its.list):?(its.list))
( dequeue
= x
. !(its.list):?(its.list) (.?x)
& !x
)
(empty=.!(its.list):)
)

View file

@ -5,10 +5,8 @@
(swap! q conj x))
(defn dequeue [q]
(if (seq @q)
(let [x (first @q)]
(swap! q subvec 1)
x)
(if-let [[f & r] (seq @q)]
(do (reset! q r) f)
(throw (IllegalStateException. "Can't pop an empty queue."))))
(defn queue-empty? [q]

View file

@ -0,0 +1,38 @@
# Implement a fifo as an array of arrays, to
# greatly amortize dequeue costs, at some expense of
# memory overhead and insertion time. The speedup
# depends on the underlying JS implementation, but
# it's significant on node.js.
Fifo = ->
max_chunk = 512
arr = [] # array of arrays
count = 0
self =
enqueue: (elem) ->
if count == 0 or arr[arr.length-1].length >= max_chunk
arr.push []
count += 1
arr[arr.length-1].push elem
dequeue: (elem) ->
throw Error("queue is empty") if count == 0
val = arr[0].shift()
count -= 1
if arr[0].length == 0
arr.shift()
val
is_empty: (elem) ->
count == 0
# test
do ->
max = 5000000
q = Fifo()
for i in [1..max]
q.enqueue
number: i
console.log q.dequeue()
while !q.is_empty()
v = q.dequeue()
console.log v

View file

@ -0,0 +1,25 @@
queue_push() {
typeset -n q=$1
shift
q+=("$@")
}
queue_pop() {
if queue_empty $1; then
print -u2 "queue $1 is empty"
return 1
fi
typeset -n q=$1
print "${q[0]}" # emit the value of the popped element
q=( "${q[@]:1}" ) # and remove the first element from the queue
}
queue_empty() {
typeset -n q=$1
(( ${#q[@]} == 0 ))
}
queue_peek() {
typeset -n q=$1
print "${q[0]}"
}

View file

@ -0,0 +1,14 @@
# any valid variable name can be used as a queue without initialization
queue_empty foo && echo foo is empty || echo foo is not empty
queue_push foo bar
queue_push foo baz
queue_push foo "element with spaces"
queue_empty foo && echo foo is empty || echo foo is not empty
print "peek: $(queue_peek foo)"; queue_pop foo
print "peek: $(queue_peek foo)"; queue_pop foo
print "peek: $(queue_peek foo)"; queue_pop foo
print "peek: $(queue_peek foo)"; queue_pop foo