Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does R have a priority queue like Java's PriorityQueue?

I am looking for a general purpose priority queue in R. Does R has any general purpose priority queue implementation (package) like Java PriorityQueue class or Python heapq?

like image 926
user1484380 Avatar asked Aug 03 '12 03:08

user1484380


2 Answers

I went ahead and implemented a basic queue as an R Reference Class. The details can be found here. It's been extended to handle a priority queue, as documented here.

The basic and priority queue implementations are now available as the liqueueR package on CRAN, with a development version on GitHub.

like image 50
datawookie Avatar answered Sep 28 '22 06:09

datawookie


You can use the following implementation from Rosetta Code, but beware that insertion takes O(n log n)

PriorityQueue <- function() {
  keys <<- values <<- NULL
  insert <- function(key, value) {
    temp <- c(keys, key)
    ord <- order(temp)
    keys <<- temp[ord]
    values <<- c(values, list(value))[ord]
  }
  pop <- function() {
    head <- values[[1]]
    values <<- values[-1]
    keys <<- keys[-1]
    return(head)
  }
  empty <- function() length(keys) == 0
  list(insert = insert, pop = pop, empty = empty)
}
like image 39
jbochi Avatar answered Sep 28 '22 06:09

jbochi