Stack and Queue Methods - stack

This is an excerpt from a book called "Professional Javascript for Web Developers".
It says :
"One of the interesting things about ECMAScript arrays is that they provide a method to make an array behave like other data structures. An array object can act just like a stack, which is one of a group of data structures that restrict the insertion and removal of items. A stack is referred to as a last-in-first-out (LIFO) structure, meaning that the most recently added item is the first one removed.
I am confused here. Is a stack a restricted method for insertion and removal or items, or not? It says "a group of data structures that restrict the insertion and removal of items." --> That "restricts". And then it says just the opposite : "A stack is referred to as a last-in-first-out (LIFO) structure, meaning that the most recently added item is the first one removed."
And then, it occurs the same about Queue Methods:
Just as stacks restrict access in a LIFO data structure, queues restrict access in a first-in-first-out (FIFO) data structure. A queue adds items to the end of a list and retrieves items from the front of the list
Again, it says it restricts access, and then it says that is "adds and retrieves" items..
I am crazy, or this is absolutely contradictory?

A stack is a last-in-first-out (LIFO) structure while a queue is a first-in-first-out (FIFO) structure. Both of them are restricted in the order of insertion and removal of items. By that it means that for stack, you can only remove the item you pushed last; while for queue, you can only remove the items in the order you pushed them. If you insert 1, 2, 3 in a stack, they can only be removed in opposite order - 3, 2, 1. Think of this as stacking plates on top of each other. Next for queue, if you insert 1, 2, 3, you can only remove them in the order 1, 2, 3. You can think of queues as the waiting 'queue' in offices, bus stops and other place, people get into and get out of the queue in same order.

Related

Are ETS bulk operations atomic?

Specifically, :ets.tab2list and :ets.file2tab. Does these functions "snapshot" the table state, or can other operations interleave reads and writes while these functions complete?
Based on the documentation here:
Functions that internally traverse over a table, like select and match, give the same guarantee as safe_fixtable.
Where
[...] function safe_fixtable can be used to guarantee that a sequence of first/1 and next/2 calls traverse the table without errors and that each existing object in the table is visited exactly once, even if another (or the same) process simultaneously deletes or inserts objects into the table.
And specifically related to your question:
Nothing else is guaranteed; in particular objects that are inserted or deleted during such a traversal can be visited once or not at all.
EDIT
ets:tab2list/1 calls ets:match_object/2 which is a built-in function (BIF) implemented in C. The implementation here is using the BIF ets_select2, which is the implementation for ets:select/2.
ets:file2tab ends up calling load_table/3 which simply uses ets:insert/2.
The code for ets:tab2file/3 in ets.erl, uses ets:select/3 to get the first chunk and then ets:select/1 to get the rest of the chunks in the table.

How to order moves, inserts, deletes, and updates in a UICollectionView performBatchUpdates block?

In my UICollectionView, I use a simple array of custom objects to produce and display cells. Occasionally that data changes and I'd like to animate the changes all at once. I've chosen to do this by tracking all the changes in a second array, diff'ing the two, and producing a set of move, insert, delete, and update operations inside of a performBatchUpdates block. I now realize it's pretty tricky to do all of these inside the same block because you have to worry about orders of operations with indexes. In fact, the accepted answer to this issue is wrong (but corrected in the comments).
The documentation seems pretty lacking, but it covers one case:
Deletes are processed before inserts in batch operations. This means
the indexes for the deletions are processed relative to the indexes of
the collection view’s state before the batch operation, and the
indexes for the insertions are processed relative to the indexes of
the state after all the deletions in the batch operation.
However, the document doesn't talk about when moves are processed. If I call moveItemAtIndexPath and deleteItemsAtIndexPaths in the same performBatchUpdates, should the move indexes be relative to the pre- or post-deleted order? How about insertItemsAtIndexPaths?
Finally, I'm facing issues calling reloadItemsAtIndexPaths and moveItemAtIndexPath in the same operation:
Fatal Exception: NSInternalInconsistencyException attempt to delete
and reload the same index path
Is there a way to do all the operations I want in the same performBatchUpdates? If so, what order do the updates get processed relative to the others? If not, what do people usually do? Reload the data after doing all other operations? Before? I'd much prefer if all the animations happened in a single stage.
Mark's answer is right. I'd recommend watching WWDC's 2018 Session 225 "A Tour of UICollectionView" to get the full explanation from an Apple engineer.
You can skip to the 33'36" mark for the interesting bit.
Summary of the video
2 lists: "original items" (before any changes) and "final items" (after all changes);
Original indexes → indexes in original items
Final indexes → indexes in final items
Operations order in PerformBatchUpdates
Deletes → Always use original indexes (will be used in descending order)
Inserts → Always use final indexes (will be used in ascending order)
Moves → From = original index; To = final index
Reload → Under the hood, it deletes then inserts. Index = original index. You can't reload an item that is moved.
To reload an item that is moved, call all reloads in a separate PerformBatchUpdates, inside a PerformWithoutAnimation (as reloads are never animated).
For the move operations, the from indexPath is pre-delete indices, and the to indexPath is post-delete indices. Reloads should only be specified for indexPaths that have not been inserted, deleted, or moved. This is probably why you're seeing the NSInternalInconsistencyException.
A handy way to verify the operations are set up correctly: the set of reload, insert and move-to indexPaths should not have any duplicates, and the set of reload, delete, and move-from indexPaths should not have any duplicates.
UPDATE:
It appears that items that you move are not also updated, but only moved. So, if you need to update and move an item, you can perform the reload before or after the batch update (depending on the state of your data source).

When would I use a linked List vs a Stack in C++

I know that in a linked list you dont need preallocated memory and the insertion and deletion method is really easy to do and the only thing I really know about stack is the push and pop method.
Linked lists are good for inserting and removing elements at random positions. In a stack, we only append to or remove from the end.
Linked List vs Array(Stack)
Both Arrays and Linked List can be used to store linear data of similar types, but they both have some advantages and disadvantages over each other.
Following are the points in favour of Linked Lists.
(1) The size of the arrays is fixed: So we must know the upper limit on the number of elements in advance. Also, generally, the allocated memory is equal to the upper limit irrespective of the usage, and in practical uses, upper limit is rarely reached.
(2) Inserting a new element in an array of elements is expensive, because room has to be created for the new elements and to create room existing elements have to shifted.
For example, suppose we maintain a sorted list of IDs in an array id[].
id[] = [1000, 1010, 1050, 2000, 2040, …..].
And if we want to insert a new ID 1005, then to maintain the sorted order, we have to move all the elements after 1000 (excluding 1000).
Deletion is also expensive with arrays until unless some special techniques are used. For example, to delete 1010 in id[], everything after 1010 has to be moved.
So Linked list provides following two advantages over arrays
1) Dynamic size
2) Ease of insertion/deletion
Linked lists have following drawbacks:
1) Random access is not allowed. We have to access elements sequentially starting from the first node. So we cannot do binary search with linked lists.
2) Extra memory space for a pointer is required with each element of the list.
3) Arrays have better cache locality that can make a pretty big difference in performance.

what is the basic difference between stack and queue?

What is the basic difference between stack and queue??
Please help me i am unable to find the difference.
How do you differentiate a stack and a queue?
I searched for the answer in various links and found this answer..
In high level programming,
a stack is defined as a list or sequence of elements that is lengthened by placing new elements "on top" of existing elements and shortened by removing elements from the top of existing elements. It is an ADT[Abstract Data Type] with math operations of "push" and "pop".
A queue is a sequence of elements that is added to by placing the new element at the rear of existing and shortened by removing elements in front of queue. It is an ADT[Abstract Data Type]. There is more to these terms understood in programming of Java, C++, Python and so on.
Can i have an answer which is more detailed? Please help me.
Stack is a LIFO (last in first out) data structure. The associated link to wikipedia contains detailed description and examples.
Queue is a FIFO (first in first out) data structure. The associated link to wikipedia contains detailed description and examples.
Imagine a stack of paper. The last piece put into the stack is on the top, so it is the first one to come out. This is LIFO. Adding a piece of paper is called "pushing", and removing a piece of paper is called "popping".
Imagine a queue at the store. The first person in line is the first person to get out of line. This is FIFO. A person getting into line is "enqueued", and a person getting out of line is "dequeued".
A Visual Model
Pancake Stack (LIFO)
The only way to add one and/or remove one is from the top.
Line Queue (FIFO)
When one arrives they arrive at the end of the queue and when one leaves they leave from the front of the queue.
Fun fact: the British refer to lines of people as a Queue
You can think of both as an ordered list of things (ordered by the time at which they were added to the list). The main difference between the two is how new elements enter the list and old elements leave the list.
For a stack, if I have a list a, b, c, and I add d, it gets tacked on the end, so I end up with a,b,c,d. If I want to pop an element of the list, I remove the last element I added, which is d. After a pop, my list is now a,b,c again
For a queue, I add new elements in the same way. a,b,c becomes a,b,c,d after adding d. But, now when I pop, I have to take an element from the front of the list, so it becomes b,c,d.
It's very simple!
Queue
Queue is a ordered collection of items.
Items are deleted at one end called ‘front’ end of the queue.
Items are inserted at other end called ‘rear’ of the queue.
The first item inserted is the first to be removed (FIFO).
Stack
Stack is a collection of items.
It allows access to only one data item: the last item inserted.
Items are inserted & deleted at one end called ‘Top of the stack’.
It is a dynamic & constantly changing object.
All the data items are put on top of the stack and taken off the top
This structure of accessing is known as Last in First out structure (LIFO)
STACK:
Stack is defined as a list of element in which we can insert or delete elements only at the top of the stack.
The behaviour of a stack is like a Last-In First-Out(LIFO) system.
Stack is used to pass parameters between function. On a call to a function, the parameters and local variables are stored on a stack.
High-level programming languages such as Pascal, c, etc. that provide support for recursion use the stack for bookkeeping. Remember in each recursive call, there is a need to save the current value of parameters, local variables, and the return address (the address to which the control has to return after the call).
QUEUE:
Queue is a collection of the same type of element. It is a linear list in which insertions can take place at one end of the list,called rear of the list, and deletions can take place only at other end, called the front of the list
The behaviour of a queue is like a First-In-First-Out (FIFO) system.
A stack is a collection of elements, which can be stored and retrieved one at a time. Elements are retrieved in reverse order of their time of storage, i.e. the latest element stored is the next element to be retrieved. A stack is sometimes referred to as a Last-In-First-Out (LIFO) or First-In-Last-Out (FILO) structure. Elements previously stored cannot be retrieved until the latest element (usually referred to as the 'top' element) has been retrieved.
A queue is a collection of elements, which can be stored and retrieved one at a time. Elements are retrieved in order of their time of storage, i.e. the first element stored is the next element to be retrieved. A queue is sometimes referred to as a First-In-First-Out (FIFO) or Last-In-Last-Out (LILO) structure. Elements subsequently stored cannot be retrieved until the first element (usually referred to as the 'front' element) has been retrieved.
STACK:
Stack is defined as a list of element in which we can insert or delete elements only at the top of the stack
Stack is used to pass parameters between function. On a call to a function, the parameters and local variables are stored on a stack.
A stack is a collection of elements, which can be stored and retrieved one at a time. Elements are retrieved in reverse order of their time of storage, i.e. the latest element stored is the next element to be retrieved. A stack is sometimes referred to as a Last-In-First-Out (LIFO) or First-In-Last-Out (FILO) structure. Elements previously stored cannot be retrieved until the latest element (usually referred to as the 'top' element) has been retrieved.
QUEUE:
Queue is a collection of the same type of element. It is a linear list in which insertions can take place at one end of the list,called rear of the list, and deletions can take place only at other end, called the front of the list
A queue is a collection of elements, which can be stored and retrieved one at a time. Elements are retrieved in order of their time of storage, i.e. the first element stored is the next element to be retrieved. A queue is sometimes referred to as a First-In-First-Out (FIFO) or Last-In-Last-Out (LILO) structure. Elements subsequently stored cannot be retrieved until the first element (usually referred to as the 'front' element) has been retrieved.
To try and over-simplify the description of a stack and a queue,
They are both dynamic chains of information elements that can be accessed from one end of the chain and the only real difference between them is the fact that:
when working with a stack
you insert elements at one end of the chain and
you retrieve and/or remove elements from the same end of the chain
while with a queue
you insert elements at one end of the chain and
you retrieve/remove them from the other end
NOTE:
I am using the abstract wording of retrieve/remove in this context because there are instances when you just retrieve the element from the chain or in a sense just read it or access its value, but there also instances when you remove the element from the chain and finally there are instances when you do both actions with the same call.
Also the word element is purposely used in order to abstract the imaginary chain as much as possible and decouple it from specific programming language
terms. This abstract information entity called element could be anything, from a pointer, a value, a string or characters, an object,... depending on the language.
In most cases, though it is actually either a value or a memory location (i.e. a pointer). And the rest are just hiding this fact behind the language jargon<
A queue can be helpful when the order of the elements is important and needs to be exactly the same as when the elements first came into your program. For instance when you process an audio stream or when you buffer network data. Or when you do any type of store and forward processing. In all of these cases you need the sequence of the elements to be output in the same order as they came into your program, otherwise the information may stop making sense. So, you could break your program in a part that reads data from some input, does some processing and writes them in a queue and a part that retrieves data from the queue processes them and stores them in another queue for further processing or transmitting the data.
A stack can be helpful when you need to temporarily store an element that is going to be used in the immediate step(s) of your program. For instance, programming languages usually use a stack structure to pass variables to functions. What they actually do is store (or push) the function arguments in the stack and then jump to the function where they remove and retrieve (or pop) the same number of elements from the stack. That way the size of the stack is dependent of the number of nested calls of functions. Additionally, after a function has been called and finished what it was doing, it leaves the stack in the exact same condition as before it has being called! That way any function can operate with the stack ignoring how other functions operate with it.
Lastly, you should know that there are other terms used out-there for the same of similar concepts. For instance a stack could be called a heap. There are also hybrid versions of these concepts, for instance a double-ended queue can behave at the same time as a stack and as a queue, because it can be accessed by both ends simultaneously. Additionally, the fact that a data structure is provided to you as a stack or as a queue it does not necessarily mean that it is implemented as such, there are instances in which a data structure can be implemented as anything and be provided as a specific data structure simply because it can be made to behave like such. In other words, if you provide a push and pop method to any data structure, they magically become stacks!
STACK is a LIFO (last in, first out) list. means suppose 3 elements are inserted in stack i.e 10,20,30.
10 is inserted first & 30 is inserted last so 30 is first deleted from stack & 10 is last
deleted from stack.this is an LIFO list(Last In First Out).
QUEUE is FIFO list(First In First Out).means one element is inserted first which is to be
deleted first.e.g queue of peoples.
Stacks a considered a vertical collection. First understand that a collection is an OBJECT that gathers and organizes other smaller OBJECTS. These smaller OBJECTS are commonly referred to as Elements. These elements are "Pushed" on the stack in an A B C order where A is first and C is last. vertically it would look like this:
3rd element added) C
2nd element added) B
1st element added) A
Notice that the "A" which was first added to the stack is on the bottom.
If you want to remove the "A" from the stack you first have to remove "C", then "B", and then finally your target element "A". The stack requires a LIFO approach while dealing with the complexities of a stack.(Last In First Out) When removing an element from a stack, the correct syntax is pop. we don't remove an element off a stack we "pop" it off.
Recall that "A" was the first element pushed on to the stack and "C" was the last item Pushed on the stack. Should you decide that you would like to see what is on bottom the stack, being the 3 elements are on the stack ordered A being the first B being the second and C being the third element, the top would have to be popped off then the second element added in order to view the bottom of the stack.
Simply put, a stack is a data structure that retrieves data in opposite order that it was stored in. Meaning that Insertion and Deletion both follow the LIFO (Last In First Out) system. You only ever have access to the top of the stack.
With a queue, it retrieves data in the same order which it was sorted. You have access to the front of the queue when removing, and the back when adding. This follows the FIFO (First In First Out) system.
Stacks use push, pop, peek, size, and clear. Queues use Enqueue, dequeue, peek, size and clear.

Queue management in Rails

I am planning to have something like this for a website that is on Ruby on Rails. User comes and enters a bunch of names in a text field, and a queue gets created from all the names. From there the website keeps asking more details for each one from the queue until the queue finishes.
Is there any queue management gem available in Ruby or I have to just create an array and keep incrementing the index in session variable to emulate a queue behaviour?
The easiest thing is probably to use the push and shift methods of ruby arrays.
Push sticks things on the end of the array, shift will return and remove the first element.
As you receive data about each of the names, you could construct a second list of the names - a done array. Or if you're not concerned about that and just want to save and more on with them, just store the array in the session (assuming it's not going to be massive) and move on.
If your array is massive, consider storing the names to be added in temporary rows in a table then removing them when necessary. If this is the route you take, be sure to have a regularly running cleanup routine that removes entries that were never filled out.
References
http://apidock.com/ruby/Array/push
http://apidock.com/ruby/Array/shift
Try modeling a Queue with ActiveRecord
Queue.has_many :tasks
attributes: name, id, timestamps
Task.belongs_to :queue
attributes: name, id, position, timestamps, completed
Use timestamps to set initial position. Once a task is completed, set position to [highest position]+1 (assuming the lower the position number, the higher up on the queue). Completed tasks will sink to the bottom of the queue and a new task will rise to the top.
Hope this helps!

Resources