REBOL [ Title: "Cheasy (Cheap-n-Easy) Priority Queue" ] pq-insert: func [ list [any-block!] "The queue" item priority [integer!] ][ sort/skip/reverse append list reduce [priority item] 2 ] pq-remove: func [ "Remove an item from the priority queue" list [any-block!] "The queue" /index "Remove a specific item" idx [integer!] "The specific item to remove" ][ remove/part either index [at list (idx * 2 - 1)][head list] 2 ] pq-first: func [ list [any-block!] "The queue" ][ ; skip over the priority value and return the actual value ; that was inserted in the queue. first next head list ] priority-queue: make object! [ data: copy [] insert: func [item priority] [pq-insert data item priority] remove: func [/index idx] [ either index [pq-remove/index data idx][pq-remove data] ] first: does [pq-first data] ] pq: copy [] print pq-insert pq "A" 1 print pq-insert pq "B" 10 print pq-insert pq "C" 100 print pq-insert pq "D" 1000 print pq-remove/index pq 3 print pq-remove pq print mold pq print pq-insert pq "CC" 100 print pq-insert pq "CCC" 100 print pq-insert pq "D" 1000 print pq-insert pq "CCCC" 100 print pq-insert pq "CCCCC" 100 print pq-remove pq print pq-insert pq "CCCCCC" 100 print pq-insert pq "CCCCCCC" 100 print "" pq: make priority-queue [] print pq/insert"A" 1 print pq/insert"B" 10 print pq/insert"C" 100 print pq/insert"D" 1000 print pq/remove/index 3 print pq/remove ;pq print mold pq/data print pq/insert"CC" 100 print pq/insert"CCC" 100 print pq/insert"D" 1000 print pq/insert"CCCC" 100 print pq/insert"CCCCC" 100 print pq/remove ;pq/data print pq/insert"CCCCCC" 100 print pq/insert"CCCCCCC" 100 halt
You need to create an account or log in to post comments to this site.