r/dailyprogrammer • u/Coder_d00d 1 3 • Oct 13 '14
[10/13/2014] Challenge #184 [Easy] Smart Stack List
Description:
We all know the famous link list. We can use these to hold data in a linear fashion. The link list can be used to implement a stack as well for example.
For this challenge you will need to develop a smart stack list. So what makes this link list so smart? This link list will behave like a stack but also maintain an ascending sorted order of the data as well. So our link list maintains 2 orders (stack and sorted)
In today's world link list data structures are part of many development platforms. For this challenge you will be implementing this and not using already pre-made frameworks/standard link lists code that you call. You have to implement it and all the features.
The Challenge will have 2 steps.
- Implement your smart link list
- Test your smart link list
Data:
The smart link list will hold integer data.
Methods:
The smart link list must support these methods or operations.
- Push - Push a number on top of the stack (our link list is a stack)
- Pop - Pop the number off the top of the stack
- Size - how many numbers are on your stack
- Remove Greater - remove all integers off the stack greater in value then the given number
- Display Stack - shows the stack order of the list (the order they were pushed from recent to oldest)
- Display Ordered - shows the integers sorted from lowest to highest.
Smart list:
One could make a stack and when you do the display ordered do a sort. But our smart list must have a way so that it takes O(n) to display the link list in stack order or ascending order. In other words our link list is always in stack and sorted order. How do you make this work? That is the real challenge.
Test your list:
Develop a quick program that uses your smart stack list.
- Generate a random number between 1-40. Call this number n.
- Generate n random numbers between -1000 to 1000 and push them on your list
- Display stack and sorted order
- Generate a random number between -1000 and 1000 can call it x
- Remove greater X from your list. (all integers greater than x)
- Display stack and sorted order
- pop your list (size of list / 2) times (50% of your list is removed)
- Display stack and sorted order
12
u/skeeto -9 8 Oct 14 '14 edited Oct 14 '14
C, using an advanced trick often found in kernel development: container_of(). It's a macro that finds the containing struct of a struct. It allows C to have generic data structures sort of like C++. Think of it like a primitive form of OOP.
The actual structure of the stack will be two linked listed, one for each kind of ordering. Which linked list we follow depends on which ordering is needed. The same node will belong to multiple lists. To avoid being redundant with linked list code, I isolate the doubly linked list into its own "dlist" modile.
The insert function puts the new node after the given list node. The remove function doesn't need a handle to the outer list, since it's doubly linked.
A linked list is just a struct pointing to the previous and next nodes. There's no value or data associated with the list.
Next define a stack node.
It contains two dlist structs since it will belong to two different linked lists. Now typedef some function signatures for convenience. The stack can operate on any kind of data, not just integers.
We'll need some specific headers too,
And now the top stack structure:
The struct will be initialized statically by the library caller. An important thing to notice is that it doesn't point to any nodes directly. Each list head points to a member within the first node of the list. This is where the container_of() macro becomes essential: it allows me to back out from a pointer to a member of a struct to the struct itself. It's defined like this:
Given a pointer, the pointer's type, and the member name, it finds the containing struct.
Here's the function to push a new value onto the stack. It uses the comparator function to insert it into the sorted list.
Note the use of container_of() to back out of the linked list to get the value for the comparator.
Removing a node is dead simple. Get a hold of the node and remove it from each doubly linked list.
Remove-greater-than is similar, removing multiple nodes according to the comparator.
Finally the two printing functions, which use the visitor pattern to visit a printer to each node. They're identical except for the selection of field (and, therefore, linked list).
Here's what usage looks like with integers. This was my test code. I'm using
intptr_tto safely embed integers inside the pointers.Here's the whole thing put together:
A better version would keep the sorted collection in a heap. It would still use the exact same container_of() trick and a sstack node would belong to both a doubly linked list and a heap at the same time, allowing those two data structures to compose cleanly.
4
u/threeifbywhiskey 0 1 Oct 13 '14
Here's my Ruby solution.
#remove_greateris O(n) on account of#indexstopping once its predicate has returned a true value.3
u/[deleted] Oct 14 '14
Python, it works about half the time. I cannot figure out why I am getting an indexing error on my pop method on almost every other run. It seems that myStack and mySort are coming up as empty when they shouldn't be. Any insights or recommendations are greatly appreciated.
3
u/_flks Oct 15 '14
LiveScript; also, my first comment in this subreddit.
My test program:
Example output of the test program:
2
u/Regimardyl Oct 13 '14 edited Oct 14 '14
My solution in Haskell (I just keep two lists with one being stacked and one being sorted, so I sacrifice space for speed of operations which should all happen in O(n)). I did not include the testing.
EDIT: I guess the most canonical way would be to use Annotated Finger Trees, but I think that's kind of overkill for this challenge and probably also doesn't 100% fulfill it (haven't thought too much about the actual implementation).
2
u/G33kDude 1 1 Oct 13 '14
Done in AutoHotkey to the best of my understanding of the problem. The smart stack class is named "DumbStack"
2
u/nyrol Oct 14 '14
Oh boy this is a long one for some reason. C++. I basically make a double linked list, and a double linked stack.
1
u/dohaqatar7 1 1 Oct 13 '14
Haskell
I didn't implement the testing because I'm honestly not sure how random number work in Haskell.
1
u/jnazario 2 0 Oct 14 '14 edited Oct 14 '14
thanks, this was fun. i hadn't made a proper class in F# before. like some others i maintain two lists ...
and here's a test run
1
u/Godspiral 3 3 Oct 14 '14
In J, without a class.
push =: , NB. appends unlimited items to end. returns new list/stack
pop1 =: }: ; {: NB. returns 2 items: new list, poped item
popmany =: ((#@]- [) {. ]) ; -@[ {. ] NB. pop number in left argument
size =: #
split =: 1 : '(-.@:u # ]) ; u # ]' NB. returns 2 lists in stack order based on condition
sorted =: /:~
test script as one line, including stack and sorted of both the popped (returned) and unpopped (remaining) halves of the list
1
u/pruby Oct 14 '14 edited Oct 14 '14
My implementation in C99, implemented with a linked list and a skip list. Compiled with gcc, options "-Wall -g -O -std=c99".
EDIT: Fixed bug in implementation relating to removing multiple copies of the same number from the sorted list, renamed some structures and variables to be clearer what they are. Made skip lists sparser too.
1
u/KevinTheGray Oct 14 '14
C++ Ugly and long, but it works... I think it does anyway! I did the tests and it seems to work.
1
u/theCodest Oct 14 '14
C#, not sure im doing this right :D
http://paste.ofcode.org/4L7fxRqMbgXtHkVeNENrbC
1
u/[deleted] Oct 14 '14 edited Oct 14 '14
Prolog!
I chose an ugly operator for my implementation of lists...
Any questions or critiques are very welcome!
I used Michael Hendrick's
funcpackage for fun and learning. It supplies some functional syntax (although with the bi-directional twist characteristic of Prolog predicates).An example of running the test:
1
u/squirrel-of-doom Oct 14 '14
C++ (gotta love shooting pointers around). I double-linked the ordered part of the list for greater convenience.
SortedStack.h:
SortedStack.cpp:
Test-Routine (main.cpp):
1
u/frozensunshine 1 0 Oct 14 '14 edited Oct 14 '14
C99. I'd love some feedback, my code is crazy inelegant.
1
u/tiiv Oct 14 '14
C - clang compiler with arguments "-Wall -Werror -pedantic -std=c99"
1
u/[deleted] Oct 14 '14 edited Oct 14 '14
Python 3.X
My tests
And the output
Pushing 1-40 random ints between -1000 and 1000
remove all elements greater than a random int between -1000 and 1000 and print original stack, and sorted
Popping half the length of our stack leaves us with...
There weren't many elements so the results aren't particularly interesting but you can see that it works.
edit: added a better output
1
u/[deleted] Oct 14 '14
C#
I tried this with a weird node class containing pointers to a "next" and "nextOrdered" element, but that proved a pain in the ass. This one maintains two linked lists of elements. The unsorted list keeps track of its tail for popping.
I made use of access to sorted elements to make Contains() and Remove() calls quicker: as soon as the code reaches a value larger than the one you're looking for, it returns FALSE instead of looking through the rest of the pile.
Tragically, having two complete lists with no references to one another means that I do have to scan both lists to complete a Remove() operation. Maybe I couldmodify the node to track a sibling or something.
I know the challenge said to implement RemoveGreaterThan(x) or something, but I went with the generic RemoveAll(func predicate) thing you see on the List(T) class in C#.
Also, this stack is generic--it'll use any type that's both IComparable(T) and IEquatable(T).
P.S. "Lima" and "Golf" are the best property names in history.
Code:
Output:
1
u/Coplate Oct 14 '14 edited Oct 14 '14
Here is my take on it:
C code.
I implemented it as a 2 dimensional linked list, prev and next being the pointers to the stack, greater and lesser being poitners to the ordered list.
Each of those starts at a pointer 'LinearList' and 'AscendingList' respectively.
the helper function 'help_remove' takes care of moving all the pointers around when you are ready to remove a node.
Its set up so you can give it a seed on the command line, and reproduce the values for testing.
1
u/AtlasMeh-ed Oct 14 '14 edited Oct 14 '14
I wanted to make this thing run fast as theoretically possible and I think I did.
I rolled my own heap and implemented generics so you can toss anything Comparable into it! Worrying about duplicates was the only annoying part. I probably should have just wrapped the data objects in something that uses a memory address as hash and forwards compareTo to the data object.
The gists:
SmartStack.java https://gist.github.com/spencercarroll/28187ab8bfd2f1219292
SmartStackTest.java https://gist.github.com/spencercarroll/bdd2cd54719c6f4abf76
1
u/your_distant_cousin Oct 15 '14 edited Oct 15 '14
In Rust, albeit wantonly unsafe, though seemingly that's acceptable for data structure implementations. I'm just trying to learn Rust at the moment, so I would really appreciate any feedback/criticisms. I'm also not sure on how to check for any memory leaks.
And here's the test program:
1
u/YuEnDee14 Oct 15 '14
This is my first time participating in a /r/dailyprogrammer challenge, since I just discovered this sub a couple days ago. I decided to go with the language I know best: C#. This is definitely not the most elegant solution, but I think it works pretty well and fits all of the requirements:
https://gist.github.com/YuEnDee14/c8c6e503efe6b160e99d
1
u/katyne Oct 15 '14 edited Oct 15 '14
Ok here goes nothing. Plain old Java (don't touch that arrow. Resist the urge, you can do it :]) Simple and boring.
Implementation:
Tests:
Output:
Printing stack of size 6:
(-138)(-59)(-860)(-762)(789)(642)
Printing stack sorted:
(-860)(-762)(-138)(-59)(642)(789)
Removing elements larger than 292:
Printing stack of size 4:
(-762)(-860)(-59)(-138)
Printing stack sorted:
(-860)(-762)(-138)(-59)
Removing 2, half of 4 remaining elements:
Pop: -762
Printing stack of size 3:
(-860)(-59)(-138)
Printing stack sorted:
(-860)(-138)(-59)
Pop: -860
Printing stack of size 2:
(-59)(-138)
Printing stack sorted:
(-138)(-59)
1
u/IceDane 0 0 Oct 15 '14
Haskell.
This was an interesting little challenge. This may not fulfill all the requirements, I'm not quite sure. It maintains the stack and the sorted stack, and inserting into the sorted stack is O(n). Determining the size is constant time as I keep track of it in the operations.
Additionally, I chose to use Generalized Algebraic Datatypes which allow me to impose typeclass constraints on the constructor, enabling me to effectively create a parameterized datatype that effectively works for all types that are orderable(that is, we can sort them), instead of just on integers.
I'm not quite happy with having to add the typeclass constraints to every function that uses the datatype as well -- I would like to have the constraints 'embedded' into the datatype. That is, it is implicit that the type parameter needs to be orderable. I'm not sure if this is possible. Maybe TypeFamilies can do it, I don't know. I hardly get them.
1
u/[deleted] Oct 15 '14
My attempt in java.
Tested with Integers but should also work with any class that implements the Comparable interface.
1
u/cdombroski Oct 15 '14
I tried to do this in Clojure, but was stymied by data immutability (it can probably be done, but all the nodes would have to be wrapped in atoms). So here's a implementation in Java instead: https://gist.github.com/cdombroski/022459a9272e48cf1a7c
I ended up doing a double-linked list with a double-linked binary tree superimposed on it. Like the other Java entries, this list is good for any data type that is Comparable. It also provides iterators for stack or sorted iteration, but sadly, it does not implement Iterable for java's foreach notation.
While I was debugging I found this library to be extremely useful for visualizing the tree structure.
The test program is in main() and gives output similar to this:
1
u/Frigguggi 0 1 Oct 17 '14 edited Oct 17 '14
Java. Each node stores references to the next and previous both in stack order and in sorted order. Nodes are sorted into the correct location when they are pushed onto the stack.
Output:
Stack order: -70, -563, -741, 270, -712, 793, 467, -621, -42, -751, 44, -715, -890, -707, -940, -123, 363, -719, 187, -784, -464, 31, -254, 717, 227, 608, 370, 579, -200, -404, -78, 222, 171, -112
Sorted order: -940, -890, -784, -751, -741, -719, -715, -712, -707, -621, -563, -464, -404, -254, -200, -123, -112, -78, -70, -42, 31, 44, 171, 187, 222, 227, 270, 363, 370, 467, 579, 608, 717, 793
Size: 34
Removing values greater than -44.
Stack order: -70, -563, -741, -712, -621, -751, -715, -890, -707, -940, -123, -719, -784, -464, -254, -200, -404, -78, -112
Sorted order: -940, -890, -784, -751, -741, -719, -715, -712, -707, -621, -563, -464, -404, -254, -200, -123, -112, -78, -70
Size: 19
Popping -70
Popping -563
Popping -741
Popping -712
Popping -621
Popping -751
Popping -715
Popping -890
Popping -707
Stack order: -940, -123, -719, -784, -464, -254, -200, -404, -78, -112
Sorted order: -940, -784, -719, -464, -404, -254, -200, -123, -112, -78
Size: 10
1
u/Mifano1337 Oct 17 '14
Here is my solution :) Any feedback? Thanks! PYTHON
1
u/arguenot Oct 20 '14 edited Oct 20 '14
This is late but here's a javascript solution. It's heavily commented in icelandic, sorry about that(I'm practicing my commenting as well as javascript).
1
u/qwesx Oct 20 '14 edited Oct 20 '14
Slowpoke here, Racket solution.
Could have used Typed Racket to force only allowing integers, but whatever, I accept everything and only order the numbers. Close enough, right?
Program:
Tests:
Output:
From a non-significant set of tests it seems that (random 2002) returns values below 1000 a lot of the time which is why there are so many negative numbers. Not sure why it does that.
1
u/CreatureKing Oct 21 '14 edited Oct 21 '14
Done in C++. Orginally split over multiple files. Keeps track of the end of the stack for a quick pop.
1
u/cooper6581 Oct 22 '14 edited Oct 22 '14
Java - Similar to other solutions. Decided to not use a doubly linked list for some reason, which made things fun. If I was to re-write, I would use a doubly linked list (a prev and next for the stack and ordered) :)
1
u/[deleted] Oct 23 '14
I can say this challenge could be implemented either in an easy way or a hard one. At first I thought I should have 2 lists, one with my data, and one with the indexes of the sorted list, but it was a little difficult for me to implement. I implemented a list which just prints the list sorted, not have a sorted list in the program and print it. In Python.
SmartStack.py:
SmartStackTest.py:
1
u/Rusty389 Nov 02 '14
I'm quite late to the party but this is my solution. It's basically just a singly linked list with two pointers, one that points to the item previously put on the stack, and one that points to the next greatest item on the stack.
1
u/sknrn Nov 18 '14
I don't quite understand what you mean by "stack and sorted order". So, implementing a stack using a list I understand, but the trick you are going for seems to be the sorting.
Say I have implemented a stack using a linked list, what exactly is it you are looking for? I am sorry if I am overlooking some detail.
1
u/rmlf1995 Oct 14 '14 edited Oct 14 '14
Python. This is my first post, and I am still learning. I would love some constructive criticism on how this could be improved.
Also, I am having issues with my size and push methods and cannot figure out what is happening. The push method returns "'NoneType' object is not iterable". I've tried everything I can think of at this point, and have spent forever on Google. I'd appreciate the help.
EDIT: Changed self.stack = self.stack.append(num) to self.stack.append(num) in push method, to fix type 'None' error.
1
u/lukz 2 0 Oct 14 '14
BASIC for C64
I have built a simple engine that processes commands. The commands consist of a command string and a number, for example PUSH,100. For commands that don't need a number argument, I use dummy 0, for example POP,0 or PRINT,0.
The program contains hardcoded commands for testing.
I use two arrays to hold the data. Array A1 contains the data in sorted order and array AS contains the data in stack order.
Output:
1
u/MFreemans_Black_Hole Oct 15 '14
My first submission!
In Java:
0
u/[deleted] Oct 17 '14
[deleted] — view deleted comment