What are the first and the last elements in stack data structure? - data-structures

I've studied stacks as data structures and I know that they work according to the LIFO ( Last-In-First-Out) Rule. I've encountered a problem that asks me to retrieve the first elements, as well as the last ones of the stack. Since I would rather have my knowledge double-checked by more experienced users, I am curios to know which elements of the stack are acknowledged to be the first and the last ones?
As an example, let us push in stack in this order 1,2,3,4,5,6. Which are the first two elements of the stack and which are the last two ones?

It helps to think of a stack from top to bottom like a real-life stack of books. If you push book 1 on the stack, followed by books 2-6, your stack looks like:
6
5
4
3
2
1
So 1 and 2 are your first two elements (books), and 6, 5 are your last and second-to-last. Since book 6 was last, it's the first to come off the stack (pop in programming parlance), otherwise your stack of books will fall!

On this question, people might have different opinions. What best can be done is understand the requirement of the problem in hand. Like if you are solving problems of stack on online judges then you can get the clarification from the problem statements/examples or if you are solving the problem in your professional work you can get the clarification from requirement analysis. At the end, if you could solve the problem you are supposed to, it doesn't matter you call top element as first or bottom element as first.

Related

Sequence to insert an elements in stacks and queues

Does the sequence to insert an element really matters in stacks or queues,i mean to push or to enqueue the data either at start or at the end given we are popping from top in a stack and dequeue from the head in a queue.........Forgive me if this has been already asked.
I hope the question is clear.Thanks in advance.
Check this picture
A stack is a basic data structure that can be logically thought as linear structure represented by a real physical stack or pile, a structure where insertion and deletion of items takes place at one end called top of the stack. The basic concept can be illustrated by thinking of your data set as a stack of plates or books where you can only take the top item off the stack in order to remove things from it. So yeah this is a data structures not a open source project, sequence matters.
Same goes for Queue

What is Youtube comment system sorting / ranking algorithm? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 4 years ago.
Improve this question
Youtube provides two sorting options: Newest first and Top comments. The "Newest first" is pretty simple that we just sort the comments by their post date. But the "Top comments" seems to be a lot more complex than just sorting by "thumb up"s.
After a short research, I found out that the order of comments depends on those things:
Number of "thumb up"s and "thumb down"s
Post date
Number of replies to that comment
But I don't know how Youtube uses this information to decide the order, like what information is more important and what is less important.
Is there any article about this topic that I could refer to?
Thanks!
I have the answer to your question.
After searching the internet for the answer to this, I never found precisely what I was looking for. So, my colleagues and I decided to experiment using the system with the Youtube comments.
First of all, we sorted what we believed to be popular videos into one section, average videos into another, and less popular into the last. There were 200 videos in each section, and after days of examining we started to notice a pattern. We found that you were right about the three things required, but we also dove a little deeper and found an additional variable.
The Youtube comment system depends on four things:
1) Time it was posted,
2) Like/dislike ratio of a comment,
3) Number of replies,
4) And, believe it or not, WHO posted it.
The average like/dislike ratio of every public comment you've ever posted builds into it, as (what we predicted) they believe that those with low like/dislike ratios would post comments that many people do not like or simply disagree with.
There is an algorithm to it, and it is quite simpler than you might think. Basically there are these things that we called "module points," and you get a certain one based on these four factors. First, here's the things you need to know about module point conversion with TWO of the factors:
For the like/dislike ratio on the comment, multiply that number by ten.
For the amount of replies (NOT from the original poster) that the comment has, there are two module points.
These are the two basic factors that tell the amount of module points the comment has.
For example, if a comment had 27 likes and 8 dislikes, then the ratio would be 3.375. Multiplying by 10, you would then have 33.75 module points. Using the next factor, amount of replies, let's say this comment has 4 direct replies to it. Multiplying 2 by 4, we get 8. This is the part where you add 8 onto the accumulative module points, giving you a total of 41.75 module points.
But we're not done here; this is where it gets tricky.
Using the average like/dislike ratio of a person's total comments that they've ever posted publicly, we found that the formula added onto the accumulative module points is this:
C = MP(R/3) + (MP/10)
where C = Comment Position Variable; MP = Module Points; R = Person's total like/dislike ratio
Trust me, we spend DAYS just on this part, which was probably the most frustrating. Even though the 3 and the 10 within this equation seem random and unnecessary, so far all of the comments we tested this equation on passed the test, but did not pass the test when those two variables were removed. After this equation is done, it gives you a number that we named to be the Position Variable.
However, we are not even done yet, we still haven't talked about time.
I was actually quite surprised that this part didn't take as long as I expected, but it sure was a pain doing this equation every single time for every comment we tested. At first, when testing it, we figured that the time was just there to break the barrier if 2 comments had equal Position Variables.
In fact, I almost called it a wrap on the experiment when this happened, but upon further inspection, we found out there was more to do. We found that some of the comments outranked each other that had the same Position Variable, but the timing seemed to be random! After a few days of inspection, here is where the final result comes in:
There is yet ANOTHER equation that we must find before applying the 4th variable. Using another separate equation, here's what our algebraic deductions came down to:
X = 1/3(S/10 + A) x [absolute value of](A - 3S)
where X = Timing Variable; S = How long ago the video was posted in minutes; A = How long ago the comment was posted in minutes
I wish I was making this up, but unfortunately this is how complicated the system is. There are mathematical reasons behind the other variables, but they are far too complex to explain, it will probably take up atleast three paragraphs worth of explaining. We tested this equation on more than 150 comments, all of them checked out to be true.
Once you find X, which is what we called the Timing Variable, all you have to do from here is apply it to this equation:
N = X(C/4 + 1)
where X = Timing Variable; C = Positioning Variable
N is the answer to all your problems.
This is the final equation, the final answer. The simple conclusion: the higher N, the higher up the comment is.
Note: Special thanks to my colleagues: David Mattison, Josh Williams, Diego Mendieta, Steven Orsette, and Kyle Shropshire. I could have never found out this without them and the work they put into this.

Unique Queue Overflow Condition (having less elements than its size)

Got this competitive question:
Which of the following data structure may give overflow error, even though the current number of elements in it is less than its size?
a. Stack
b. Circular queue
c. Simple queue
d. None of the above
I tried to Google the answer for a proper explanation however several sources marked (c) and (b) as answers which confused me even more. What's the explanation and the proper answer?
Thanks.
This question seems somewhat strange because if you implement any of these structures correctly, there will be no such premature overflow.
With that in mind, Circular queue does seem like the most sensible answer. Here's why:
Note: In my explanation, the queue adds to back and removes from front
After certain number of insertions/deletions, the pointers to front and back in the circular queue (implemented as an array) may be on either side of each other.
This means that when adding elements to this queue, on top of standard checks, we also have to be aware of the relative position of the front and back pointers.
In the second picture above we have to realize that adding to back has to add to the beginning of the array now, since back is at the end of the array. In other words, adding elements has to "circle around". If we don't implement this check properly, we would end up with an overflow even though there's still room in the queue.
Ans is (c)simple queue.we are assuming that elements can be inserted using rear and can be deleted using front pointer..And also assume that maximum size of queue is 10(eg.) ....Now if the rear is point at index no 9...Means there are total 10 elements in queue. And the position of front is 0 index .Now if we remove elements from other end then the value of front become 1 .........here, actually queue is not full bcz index 0 is empty... But due to the condition of the rear pointer which is max-1 the output shows that queue is full....And the sol of that is implemented in circular queue.

When is a loop in a linked list useful?

Determining whether a singly-linked list has a loop is a common interview question. But why would a linked list exist with a loop? When would a linked list with a loop be useful?
Circularly linked lists can be useful if you want to iterate through the entire list starting from a random iterator or inserting in any position. They simplify the algorithms for those operations as you don't have to account for the beginning or end of the list.
It doesn't matter then, which of the elements you pass to the function as a parameter, for example. When using sentinel pattern, you will iterate over each elements all the same.
Apache uses circularly linked lists to store all its filters.
For some reason they gave it a fancy marketing name ("Bucket Brigades") and call it "a major innovation" - lol.
To use circularly linked lists, you can think about structures that are circular by nature. Such as pool of buffers that are used and released in FIFO order, or a set of processes that should be time-shared in round-robin order, or saving the nodes coordinates of a polygon in their specific order.
Many answers given here consider Completely looped Linked List.
The interview question is a bit different. We've to detect loop (can be partial) somewhere in the link
Eg: (sorry for poor graphics)
1 -> 2 -> 3 -> 4 -> 5
        ^ v
        7 <----- 6
Answer to how it can happen: Link corruption.
a) People trying to crack in through UGC (User Generated Content). Bad data can come up.
b) Design flaws in early stages.
This loop detection is also part of testing we do on LinkedLists to look for suspected bugs.
You've not asked for solutions, but I'll put a few here in brief:
Keep pushing nodes to List (Arraylist in java). The time you find duplicate: Loop detected
Turtle & Hare approach. Turtle jumps one node at a time. Rabbit, two at a time. They meet if it's a loop
store boolean flag *visited* as you traverse. Any encounter of *true* is loop.

Need help psuedocoding a dice game and dont know where to even start [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I am a beginner IT student and doing a project for my programming logic and design class. I need to create a psuedocode for a dice game that allows you 2 rolls with 5 dice. On the first roll you get to pick 1 die to keep. The computer then rolls the other 4 dice and calculates you're score based on what you rolled. There are 3 rolls per game and the total score is displayed. Rolling nothing takes points away. The scoring is: 2 of a kind=50 points, 3 of a kind=75 points, 4 of a kind=100 points and nothing subtracts 50 points.
The whole problem I have is I dont even know where to start. I think I need this to repeat 3 times, but what variables do set? Please someone help me, I cant really ask my instructor because he is outside smoking the whole class and everything I have learned about this class mostly came from the internet and reading the book. I dont want to fail this class...someone please help me through this???
First of all don't panic. What you are about to do is break the task down into small steps.
Pseudo-code is not really code - you can't use it directly as a language, but instead it is just plain english to describe what it is you are doing and the flow of events.
So what are the initial steps to get you started?
Ask yourself what are the facts, what do you know exist in advance. These are the "declarations" that you make.
You have five dice. Each is a seperate object so each gets it's own variable declaration
dice_1
dice_2
dice_3
dice_4
dice_5
Next decide if each die has an initial value
dice_1 initial value = 0
etc...
Next you know that you have to throw the dice a number of times. Throwing is a variable with an initial value
turns initial value = 2
turns_counter initial value = 2
You should be getting the idea now. Are there other things you should declare in advance? I think so!
Next you have to decide what it is you are doing step by step. Is it just a sequence of events or is it repeating? If it's repeating how do you get it to stop?
While turns_counter is less than 2
Repeat the following:
turns_counter = turns_counter + 1
if turns_counter = 2
Throw. Collect_result. Sum_result.
else
Throw. Collect_result. Sum_result. Remove_a_dice.
endif.
perhaps you have to tell the reusable code which objects they are going to be working with? These are parameters that you pass to the reusable code Throw(dice_1) perhaps also you need to update some variables that you created? do it in the reusable code with or without passing them as parameters.
This is by no means complete or perfect, but you should get the idea about what's going on and how to break it down. It could take quite a while to do.
Most languages provide a pseudo-random number generator function that returns a random number within a certain range. I would start by figuring out which language you'll use and which function it provides.
Once you have that, you will need to call it for each roll of each dice. If you are rolling 5 dice, you would call it 5 times. And you would call it 5 more times for a second roll.
That's a start anyway.
You have already almost answered the question by simply writing it down here. There is no strict definition of what pseudocode is. Why don't you start by re-writing what you've described here as a sequence of steps. Then, for each step simply refine that step further until you think you've made it as fine-grain as you like.
You could start with something like this:
Roll 5 dice.
Pick 1 die to keep.
Rolls the other 4 dice
Calculate the score.
// etc...
Quite weird to think that it's easier to ask SO than your instructor! :)
The easiest way to get started on this is to not rigorously bind yourself to the constraint of a specific language, or even to pseudocode. Simply, in natural English, write out how you would do this. Imagine that YOU are the computer, and somebody wants to play the game with you. Just imagine, in very specific detail, what you would do at each potential step, i.e.
Give the user 5 dice
Ask the user to roll them
From that roll, allow the user to pick one die to keep
...etc. Once you have done this, and you are sure it is correct, start transforming it into pseudo code by thinking about what a computer would need to do to solve this problem. For instance, you'll need a variable keeping track of how many points the user as, as well as how many total rolls have occurred. If you were very specific in your English description of the problem, this should mean you basically only need to plug pseudo code into a few sentences you already have - in other words, you're just substituting one type of pseudo code for another.
I'd like to help, but straight-up providing the pseudo code wouldn't be very helpful to you. One of the hardest steps in beginning programming is learning to break a problem down into its constituent elements. That type of granular thinking is unintuitive at first, but gets easier the more time you spend on it.
Well, pseudo-code, in my experience, is best drawn up when you pretend you're writing up the work for someone else to do:
THINGS WE NEED
Dice
Players
Score
THINGS WE TRACK
Dice rolls
Player score
THINGS WE KNOW
(These are also called constants)
Nothing (-50)
2 of a kind (+50)
3 of a kind (+75)
4 of a kind (+100)
All of these are vital tools to getting started. And...well, asking questions on stackoverflow.
Next, define your "actions" (things we do), which utilizes the above known things that we will need.
I would start the same place I always do: creating our things.
def player():
"""Create a new player"""
def dice():
"""Creates 4 new, 6 sided dice"""
def welcome():
"""Welcome player by name, give option to quit"""
def game():
"""Initialize number of turns (start at 0)"""
def humanturn():
"""Roll dice, display, ask which one they'll keep"""
def compturn():
"""Roll four dice"""
def check():
"""Check for any matches in the dice"""
def score():
"""Tally up the score for any matches"""
def endturn():
"""Update turn(s), update total score"""
def gameover():
"""Display name, total score, ask for retry"""
def quit():
"""Quit the game"""
Those are your components, all fleshed out in a very procedural manner. There are many other ways to do this that are much better, but for now you're just writing the skeleton of an idea. You may be tempted to combine many of these methods together when you're ready to start coding, but it's a good idea to separate everything until you're confident you won't get lost chasing down a bug.
Good luck!

Resources