r/dailyprogrammer • u/Elite6809 1 1 • Feb 11 '15
[2015-02-11] Challenge #201 [Practical Exercise] Get Your Priorities Right!
(Practical Exercise): Get Your Priorities Right!
A priority queue is a data structure similar to a standard queue, except that entries in the queue have a priority associated with them - such that, when removing items from the queue, the entry with the highest priority will be removed before ones with lower priority. This is similar to a hospital triage system: patients with more severe wounds get treated quicker, even if they arrived later than a patient with a smaller injury. Let's say I have a priority queue containing strings, where the priority value is a real number. I add these 3 objects to my priority queue, in no particular order:
| Patient | Priority |
|---|---|
"David Whatsit" | 3.06 |
"Joan Smith" | 4.33 |
"Bob Testing" | 0.39 |
"Samuel Sample" | 1.63 |
Here, if I was to dequeue four strings from the priority queue, the strings "Joan Smith", "David Whatsit", "Samuel Sample" and "Bob Testing" would come out, in that order.
But what if we could assign two priorities to each object? Imagine a hospital (to keep with the theme), that needs to keep a list of equipment supplies and their costs. It also needs to keep track of how long it will take to receive that item.
| Item | Cost | Shipping Time |
|---|---|---|
| Hyperion Hypodermic Needle | £1.99 | 3 days |
| SuperSaver Syringe | £0.89 | 7 days |
| InjectXpress Platinum Plated Needle | £2.49 | 2 days |
Here, when the hospital is at normal running conditions with good supply stock, it would want to buy the cheapest product possible - shipping time is of little concern. Thus, dequeueing by the Lowest Cost priority would give us the SuperSaver syringe. However, in a crisis (where supply may be strained) we want supplies as fast as possible, and thus dequeueing an item with the Lowest Shipping Time priority would give us the InjectXpress needle. This example isn't the best, but it gives an example of a priority queue that utilizes two priority values for each entry.
Your task today for the (non-extension) challenge will be to implement a two-priority priority queue for strings, where the priority is represented by a real number (eg. a floating-point value). The priority queue must be able to hold an unbounded number of strings (ie. no software limit). If your language of choice already supports priority queues with 1 priority, it might not be applicable to this challenge - read the specification carefully.
Specification
Core
Your priority queue must implement at least these methods:
Enqueue. This method accepts three parameters - a string, priority value A, and priority value B, where the priority values are real numbers (see above). The string is inserted into the priority queue with the given priority values A and B (how you store the queue in memory is up to you!)DequeueA. This method removes and returns the string from the priority queue with the highest priority A value. If two entries have the same A priority, return whichever was enqueued first.DequeueB. This method removes and returns the string from the priority queue with the highest priority B value. If two entries have the same B priority, return whichever was enqueued first.Count. This method returns the number of strings in the queue.Clear. This removes all entries from the priority queue.
Additional
If you can, implement this method, too:
DequeueFirst. This removes and returns the string from the priority queue that was enqueued first, ignoring priority.
Depending on how you implemented your priority queue, this may not be feasible, so don't get too hung up on this one.
Extension
Rather than making your priority queue only accept strings, make a generic priority queue, instead. A generic object is compatible with many types. In C++, this will involve the use of templates. More reading resources here. For example, in C#, your class name might look like DualPriorityQueue<TEntry>. Some dynamic languages such as Ruby or Python do not have static typing, so this will not be necessary.
Notes
Making Use of your Language
The main challenge of this exercise is knowing your language and its features, and adapting your solution to them. For example, in .NET-based languages, Count would be a property rather than a method, as that is more idiomatic in those languages. Similarly, in some languages such as Ruby, F# or other functional language, overloading operators may be more idiomatic than the usage of verbose Enqueue and Dequeue functions. How you do the specifics is up to you.
You should also be writing clean, legible code. Follow the style guide for your language, and use the correct naming/capitalisation conventions, which differ from language to language. Consider writing unit tests for your code, as an exercise in good practice!
Tips and Reading Material
If you are planning on using something like a heap for the priority queue, consider interleaving each item into two heaps to store both priorities. How you will handle the dequeueing is part of the fun! If the concept of a priority queue is new to you, here is some reading material.
Here's some more stuff on unit testing.
Finally...
I wonder what this data structure would be called? A double priority queue?
Got a good idea for a challenge? Head on over to /r/DailyProgrammer_Ideas and tell us!
9
u/G33kDude 1 1 Feb 11 '15
Isn't that three parameters?
12
u/metaconcept Feb 11 '15
Well, if it's a hospital, I'd just use SQL and be done in a jiffy.
To insert an item, just do an insert.
To remove the item, do this in a transaction which locks the table:
And ditto for shipping time.
5
u/Godspiral 3 3 Feb 11 '15 edited Feb 12 '15
In J,
everything other than dequeue is built in. (, is enque, # is count)
so with a item cost shipping time,
dequeue as a verb that just passes field to minimize, and operates annonymously:
to make assignments: (q updated, and head is first item)
as an adverb that takes a name of queue as y argument, and destructively updates it, returning only the item. Also takes a function argument to select item order:
adverb version that lets caller decide on side effects, by returning item and queue separately. Uses a function that generates a boolean list with the only 1 the item to be retrieved. This version does not affect the queue/list sorting.
5
u/marseg Feb 11 '15 edited Feb 12 '15
Quick implementation with ruby:
Usage:
4
u/eruonna Feb 12 '15
Haskell, using fingertrees, basically parallel to the single Priority Queue implementation using fingertrees. Inserts are constant time and searches and unions are logarithmic.
Essentially the same code would work for even more keys. It is not clear to me if there is a nice generalization to that case that still preserves the priority queue-ness and doesn't jump to just finger trees.
This code tags each subtree with its size in order to implement count. That is not the most efficient way, but we could use this to get logarithmic access to the kth element in FIFO order though I didn't actually implement that.
1
u/vzaardan Feb 12 '15
Ruby:
I'm not too happy with the tests - I'm used to using RSpec, and this was my first time with MiniTest. Kind of felt hard to organise (which probably means I'm doing it wrong).
1
u/robertmeta Feb 12 '15 edited Feb 12 '15
Golang -- quick first pass:
Output (note: slices are unordered, so printing doesn't have them in order as added / removed):
1
u/jkudria Feb 12 '15
While I understand that the spec says that
DequeueAandDequeueBare to take no params (I'm taking the lack of parameter mentioning to mean that there should be no input), I'd much rather have something like this:A
Dequeuefunction that takes 2 parameters - a priority value and which element by priority (i.e. I want the 2nd most prioritized), with a default value of 1. Wouldn't that be more flexible and convenient in case another priority value needs to be added?1
u/lewisj489 0 1 Feb 15 '15
C#
Done it with some new relatively new methods in C#. There was a thread about my sillyness and realisation [in this thread.] I didn't approach this project like most, but it still works and isn't sloppy.(https://www.reddit.com/r/csharp/comments/2vt9ta/can_someone_help_with_a_rdailyprogrammer_exercise/) I also wrote some unit tests, which I felt was quite important for this kind of class.
Here's my solution:
EDIT: Spelling.
1
u/jubi_life Feb 15 '15
[Javascript] Is this any good? Feedback would be appreciated. 'use strict';
1
u/VikingofRock Feb 16 '15
A little late to the party, but I finished this in C++11. The reason it took me so long was because I wanted to do it right. So I:
Here's the code:
Here's some code I used to test it:
And of course, the results:
1
u/deuterium64 Feb 18 '15 edited Feb 19 '15
Python 3
Unit tests and git history can be found here
EDIT 1: Fixed a bug with the internal priority queues not being built by priority. The original submission can be found here.
EDIT 2: Replaced redundant
countmember with call tolen(self.queue). No more edits, I swear...3
u/Regimardyl Feb 11 '15 edited Feb 12 '15
Quickly done in Haskell, based on Lists. I thought about making one based on functions, but I guess that would result in mostly unreadable code without really adding anything to it.
3
u/cadadar Feb 11 '15 edited Feb 13 '15
Here's my naive implementation in Common Lisp - it only maintains a single list internally. Implementing this approach felt really natural (It's LISt Processing, after all) I skipped the implementation of COUNT since... well we have LENGTH for that ;-)
I also wrote some tests along the way, they're in the repo at https://github.com/flpa/reddit-daily/tree/master/201-get-your-priorities-right
So here's the code:
Update
I rewrote DEQUEUE to handle an empty queue, and it only uses a single run of reduce now. Also extracted code to two local functions.
Update2 Fixed parameter order for defstruct.
An example session at the REPL looks like this:
Explanation:
2
u/jnazario 2 0 Feb 11 '15 edited Feb 11 '15
quickly done in scala, complete with DequeueLast
2
u/Reverse_Skydiver 1 0 Feb 11 '15
Here's my solution in Java. Uses an ArrayList to store everything.
2
u/ChiefSnoopy Feb 11 '15 edited Feb 13 '15
My C implementation... I tried to be efficient with this, both memory wise and time complexity wise, but if you want to critique, you're very much welcome to.
EDIT: Formatting
EDIT: Revised clear and count due to naive infinite loop and to remove recursive functionality to make them both iterative. A bit of a messy fix, but a fix that works. Planning to investigate /u/cadadar's comments as soon as I'm able to run it.
2
u/mrepper Feb 11 '15 edited Feb 21 '17
[deleted]
0.6832
2
u/marchelzo Feb 12 '15
Here's my attempt in C++. I hope it is straightforward.
2
u/[deleted] Feb 12 '15 edited Feb 12 '15
o.O;
Because I hate myself, I wrote this entirely in C using a doubly linked list.
I'd love some feedback on my pointer logic, and whether or not I'd have a memory leak.
Output:
2
u/Yopu Feb 12 '15
Kotlin
2
u/inbz Feb 12 '15
PHP (5.4+)
The implementation of the double priority queue is a fairly straight forward task, and everyone here seems to have a good handle on it. It's a good opportunity to show off some of the features of your chosen language, so I will take this chance to show how many in the PHP community are unit testing their classes.
There are many good testing frameworks in PHP, and in this example I have chosen PHPUnit. To install PHPUnit and to handle class autoloading, I am using the extremely popular Composer dependency manager.
The files:
composer.json https://gist.github.com/anonymous/b40e344fdccc0647242d
src/Daily/PriorityQueue.php https://gist.github.com/anonymous/c75ec091c7bb11a1fa7b
tests/PriorityQueueTest.php https://gist.github.com/anonymous/a8ccdf72febb6c550e1d
The first step is to install composer, which is described here.
Next, use composer to install PHPUnit, as such:
Finally, to run the unit tests:
If all goes well, you should see the following output:
2
u/mikevdg Feb 12 '15
VisualWorks Smalltalk.
http://codepaste.net/gr872j
It's quite big. It's a proper implementation of a binary heap. To implement the challenge, I
Usage example:
Smalltalk collections always were generic, so the "extension" challenge is met. Yay. The priority queue can have a block (i.e. an anonymous function) passed to it to determine how priorities are evaluated.
Yea, VisualWorks uses a weird XML format to 'export' code. This is why the code is unreadable. Once it's back in a VisualWorks IDE you can browse it easily.
2
u/skippydahobo Feb 12 '15
JavaScript implementation I just threw together.
First time doing something like this so comments and critiques are welcome.
Sample usage/output:
2
u/woppr Mar 03 '15
I wanted to refresh some Linked-List.
So I did that in C#: http://pastebin.com/HaanE33Q
Output:
1
u/G33kDude 1 1 Feb 11 '15 edited Feb 11 '15
A relatively generic multi-queue class written in AutoHotkey. It relies on the fact that AHK sorts its dictionaries automatically, smallest to largest and then alphabetically. Technically, this would allow you to use strings as priority values, but that's more of a feature than a bug.
1
u/adrian17 1 4 Feb 11 '15
C++ with templated value and number of priorities. Far from optimal, but that's the only way I could figure it out.
Usage:
1
u/hutsboR 3 0 Feb 11 '15 edited Feb 12 '15
Elixir: First challenge with this language, picked it up a few days ago. Pretty neat, the |> operator is great. EDIT, Oops! Forgot to remove the structs from the queue, fixed.
Usage:
Output:
1
u/krismaz 0 1 Feb 12 '15
I went ahead and ported my old C++ Fibonacci Heap into Python3. Using this heap, I constructed the multi-priority queue by combining three heaps.
It isn't pretty, and and still looks somewhat C++-like, but I'm not sure how Python handles custom data structures. It's all part of my master plan of making a huge pile of data structures for Python.
It should run in normal queue times.
The long-winded code can be found here.
1
u/chunes 1 2 Feb 12 '15
Java with all extensions:
And an example of use:
Output:
1
u/Pritilender Feb 12 '15
Ok, this is my first time posting here. I've tried doing it in C++, and it worked for me. Also, it's my first time using STL, so I don't know if it's the correct use of STL vector class. I'm just posting template class here. Oh, and I'd be glad to here some critics on my code (positive or negative, whatever :) ).
1
u/[deleted] Feb 12 '15 edited Feb 12 '15
Really enjoyed this challenge. Would have been done a lot faster in C#, but--hey--I'm learning new things.
Umm... Cargo has this nice thing where it just makes you a git repo, and--also--I'm talking to some headhunters right now about a new job, so this is totally just going up on GitHub:
https://github.com/archer884/DualPriorityQueue
I think this pretty much covers the bases. I skipped
count()andclear(), partly because I'm miffed that count isn't a property in Rust (ha-ha) and partly because if you're curious you can just ask the vector how many items it has and then, if the number bugs you, you can just tell it to clear itself. Problem solved, right?Edit: Oh, I forgot! You can actually make the priority of your item any damn thing you want as long as it implements the right traits. Also I went ahead and changed
dequeue()todequeue_by()and exported it.1
u/stintose Feb 12 '15
JavaScript, can't think of medical supply's, thought of nuts instead.
1
u/[deleted] Feb 12 '15 edited Dec 22 '18
deleted 0.7591 What is ^^^this?
1
u/beforan Feb 12 '15
Lua 5.2
Output:
Re: Extension - Lua's dynamically typed, so the
itempassed toenqueuecan already be of any type, (as can the two priority values, but the program would come a cropper if different uncomparable types were mixed and matched!)1
u/handspe Feb 12 '15 edited Feb 13 '15
C
1
u/Seigu Feb 12 '15
Java. Feel free to comment.
1
u/OmegaWalker Feb 12 '15
Java using
streamsfor good measure1
u/streukante Feb 12 '15
quickly done in scala in a functional matter
1
u/OlorinTheGray Feb 12 '15
My solution with Java (and I should totally do something about the lazy implementation of "count"...). There is a small test in main():
Firstly the queues elements:
Secondly the queue itself:
1
u/oxidezx Feb 12 '15 edited Feb 12 '15
Generic double priority queue written in Go / Golang:
1
u/dailyochai Feb 13 '15
A far from perfect solution in C, the creation of the Data variables is problematic. On the other hand valgrind shows no memory leaks, so there is that.
1
u/Antinode_ Feb 13 '15
Im late, but heres some Java. I didnt implement any randomized system to fill the queue and I didnt implement anything to gather input from a user on what they want to access from the queue. Also, this doesnt behave like a queue, it just will search the queue for the desired parameter and return that and remove it from the list
Output
1
u/fb39ca4 Feb 14 '15
Wow, this is just what I need for chunk generation in my voxel engine.
1
u/Isitar Feb 14 '15
My solution, C#
1
u/Farami Feb 14 '15
Written in C#. I hope I didn't miss anything.
1
u/XDtsFsoVZV Feb 14 '15
My first ever semi-useful programme, written in Python 2.7. I call it Douchequeue; I was going to just call Doublequeue but I started accidentally writing Douche instead of Double for some reason (it happened just now; for some reason it's only if I write the whole word, not just writing double), and I thought "lol so random" and called it Douchequeue.
I have it as two files:
.....
I hope I did everything correctly. It seems to do everything it's supposed to do. It was a lot easier than it seemed at first.
1
u/Gronner Feb 14 '15 edited Feb 14 '15
Here is my Python 2.7 solution:
I built in an additional function to change the priorities after the items have been added. I'd love to get some feedback.
1
u/bbartek Feb 17 '15 edited Feb 17 '15
Scala, modified a little because I wanted to omit mutable variables. So each dequeue and enqueue returns new object instead of modifing actual.
1
u/ittybittykittyloaf Feb 17 '15
Yet another Python solution:
1
u/datgohan Feb 19 '15
My attempt in Python. Feedback very welcome as I'm sure there's a better or more efficient way to do this. I'm always looping over the whole queue but I think there must be a better way something akin to a Hashmap but I couldn't think how to do that without storing two versions of the queue because of the double priority. Includes the additional function.
1
u/fuklief Feb 21 '15
Why use unit tests when you can just prove that your shit really does what it says it does ? My submission in Coq.
https://gist.github.com/anonymous/048e9e842f2bd60df7ad
I haven't proven that if two entries have the same priority then the first enqueued one is returned, but my implementation actually does it, I'm just too lazy to prove it ~~
1
u/EngineSlug420 Feb 23 '15
C#, about 10 days late. I am new to C#, here is mine.
Output:
1
u/MLZ_SATX Feb 26 '15
Adding my C# implementation here because I didn't see anyone else making use of Func to reuse a single Dequeuing function for the three types of dequeuing listed.
1
u/peterentwistle Feb 27 '15 edited Feb 27 '15
I made a quick implementation in Java. Feedback is welcome. Github repo.
Test
Output
1
u/NotoriousArab Apr 05 '15
A month late but I've been busy with school.
My Python3 implementation on GitHub.
1
u/[deleted] Apr 17 '15 edited Apr 17 '15
Python 3. First time using namedtuple.
0
u/[deleted] Feb 11 '15
[deleted] — view deleted comment