RosettaCodeData/Task/Priority-queue/R/priority-queue-1.r

27 lines
629 B
R
Raw Permalink Normal View History

2013-04-10 23:57:08 -07:00
PriorityQueue <- function() {
2015-11-18 06:14:39 +00:00
keys <- values <- NULL
2013-04-10 23:57:08 -07:00
insert <- function(key, value) {
2016-12-05 22:15:40 +01:00
ord <- findInterval(key, keys)
keys <<- append(keys, key, ord)
values <<- append(values, value, ord)
2013-04-10 23:57:08 -07:00
}
pop <- function() {
2016-12-05 22:15:40 +01:00
head <- list(key=keys[1],value=values[[1]])
2013-04-10 23:57:08 -07:00
values <<- values[-1]
keys <<- keys[-1]
return(head)
}
empty <- function() length(keys) == 0
2016-12-05 22:15:40 +01:00
environment()
2013-04-10 23:57:08 -07:00
}
pq <- PriorityQueue()
pq$insert(3, "Clear drains")
pq$insert(4, "Feed cat")
pq$insert(5, "Make tea")
pq$insert(1, "Solve RC tasks")
pq$insert(2, "Tax return")
while(!pq$empty()) {
2016-12-05 22:15:40 +01:00
with(pq$pop(), cat(key,":",value,"\n"))
2013-04-10 23:57:08 -07:00
}