Stack: The terminlogy and example - stack

For this simple problem, I need to find the value(s) of stack1 and in order, if any. When it comes to the stack, the principle is LIFO (last in, first out) or FILO (first in, last out). And the reason stacks are used is to reverse the data, and displaying it in reverse order.
Stack<Integer> stack1 = new Stack<Integer>();
stack1.push (2);
stack1.push(5);
stack1.push (stack1.pop() - stack1.pop());
stack1.push(8);
The question above made me think, if we were to use the principle, should the answer be this: 8, 3, 5, 2.
8 being the last value being the start, then the next value being 3, from taking 5 and 2 (the "pop" being the deletion at the "head"). Then the next two values being 5 and 2. Would that be the right answer, or did I got the incorrect answer?

The Stack is a LIFO (last in first out). Look at it from the point of view of the first element you put in. You should also check this out what is the basic difference between stack and queue?.
As for the example, the answer is 8 and 3 only because when you calculated the 3 as stack.pop() - stack.pop() you deleted the 5 and the 2 from the stack, so they won´t be there anymore.

Stack stack1 = new Stack(); []
stack1.push (2); [2]
stack1.push(5); [2,5]
stack1.push (stack1.pop() [2] - stack1.pop() [] ); [3]
stack1.push(8); [3,8]

Related

Binomial Min Heap delete issue

Got this problem on a recent CS class quiz that I got wrong. These were the choices:
3,4
10,13
10, 9
10
I put 10 and am pretty sure I am right. Can someone explain why I am not?
It's been a long time, but here's how it should work:
Remove 1 creating new heaps 2->10 and 9 (orders 1 and 0).
Merge these with the rest of the heap.
2->10 stays as-is. There's no other order 1 heap (for now).
Merge 9 and 13 into 9->13.
Now merge 9->13 and 2->10 to get a new order 2 heap.
2->10
-> 9->13
There's no other order 2 heap, so we're done.
So the children of 2 are 9,10.

How do you use reduce(into:) in swift [duplicate]

This question already has answers here:
What is the reduce() function doing, in Swift
(4 answers)
Closed 9 months ago.
I am reading iOS 13 Programming Fundamentals with Swift, got to the part about reduce() and I think I understand it more or less, but then there is reduce(into:) and this piece of code:
let nums = [1,2,3,4,5]
let result = nums.reduce(into: [[],[]]) { temp, i in
temp[i%2].append(i)
}
// result is now [[2,4],[1,3,5]]
So this code takes an array of Int and splits it into 2 arrays, even and odd. The problem is that I have no idea what's happening inside the brackets {}.
In the case of reduce, the first parameter is the first one of the iteration and then the closure is supposed to process all the items one after the other, similar to map() but more powerful (here one loop is enough to get the two arrays but with map() I would need 2 loops, according to the book).
I cannot understand the syntax here anyway, especially what does "temp" stand for and that use of "in". And how is "append()" appending the value to the proper array??
Inside the closure, "temp" is the result format which is [[][]] and "i" is each number. As you said it processes all numbers in a loop. When % is used it returns the division remainder, so for the odd numbers like "1,3,5", it returns "1" and for the even numbers "0", which means that "temp" appends these values to the array in these respective indexes.
So if we debug and replace the variables for constants the results would be:
temp[1].append(1) //1%2 = 1/2 left 1 [[][1]]
temp[0].append(2) //2%2 = 2/2 left 0 [[2][1]]
temp[1].append(3) //3%2 = 3/2 = 1 left 1 [[2][1,3]]
temp[0].append(4) //4%2 = 4/2 left 0 [[2,4][1,3]]
temp[1].append(5) //5%2 = 5/2 = 2 left 1 [[2,4][1,3,5]]
According to the documentation the closure is called sequentially with a mutable accumulating value initialized that when exhausted, is returned to the caller.

Can't modify loop-variable in lua [duplicate]

This question already has answers here:
Lua for loop reduce i? Weird behavior [duplicate]
(3 answers)
Closed 7 years ago.
im trying this in lua:
for i = 1, 10,1 do
print(i)
i = i+2
end
I would expect the following output:
1,4,7,10
However, it seems like i is getting not affected, so it gives me:
1,2,3,4,5,6,7,8,9,10
Can someone tell my a bit about the background concept and what is the right way to modify the counter variable?
As Colonel Thirty Two said, there is no way to modify a loop variable in Lua. Or rather more to the point, the loop counter in Lua is hidden from you. The variable i in your case is merely a copy of the counter's current value. So changing it does nothing; it will be overwritten by the actual hidden counter every time the loop cycles.
When you write a for loop in Lua, it always means exactly what it says. This is good, since it makes it abundantly clear when you're doing looping over a fixed sequence (whether a count or a set of data) and when you're doing something more complicated.
for is for fixed loops; if you want dynamic looping, you must use a while loop. That way, the reader of the code is aware that looping is not fixed; that it's under your control.
When using a Numeric for loop, you can change the increment by the third value, in your example you set it to 1.
To see what I mean:
for i = 1,10,3 do
print(i)
end
However this isn't always a practical solution, because often times you'll only want to modify the loop variable under specific conditions. When you wish to do this, you can use a while loop (or if you want your code to run at least once, a repeat loop):
local i = 1
while i < 10 do
print(i)
i = i + 1
end
Using a while loop you have full control over the condition, and any variables (be they global or upvalues).
All answers / comments so far only suggested while loops; here's two more ways of working around this problem:
If you always have the same step size, which just isn't 1, you can explicitly give the step size as in for i =start,end,stepdo … end, e.g. for i = 1, 10, 3 do … or for i = 10, 1, -1 do …. If you need varying step sizes, that won't work.
A "problem" with while-loops is that you always have to manually increment your counter and forgetting this in a sub-branch easily leads to infinite loops. I've seen the following pattern a few times:
local diff = 0
for i = 1, n do
i = i+diff
if i > n then break end
-- code here
-- and to change i for the next round, do something like
if some_condition then
diff = diff + 1 -- skip 1 forward
end
end
This way, you cannot forget incrementing i, and you still have the adjusted i available in your code. The deltas are also kept in a separate variable, so scanning this for bugs is relatively easy. (i autoincrements so must work, any assignment to i below the loop body's first line is an error, check whether you are/n't assigning diff, check branches, …)

How to pop Nth item in the stack [Befunge-93]

If you have the befunge program 321&,how would you access the first item (3) without throwing out the second two items?
The instruction \ allows one to switch the first two items, but that doesn't get me any closer to the last one...
The current method I'm using is to use the p command to write the entire stack to the program memory in order to get to the last item. For example,
32110p20p.20g10g#
However, I feel that this isn't as elegant as it could be... There's no technique to pop the first item on the stack as N, pop the Nth item from the stack and push it to the top?
(No is a perfectly acceptable answer)
Not really.
Your code could be shortened to
32110p\.10g#
But if you wanted a more general result, something like the following might work. Below, I am using Befunge as it was meant to be used (at least in my opinion): as a functional programming language with each function getting its own set of rows and columns. Pointers are created using directionals and storing 1's and 0's determine where the function was called. One thing I would point out though is that the stack is not meant for storage in nearly any language. Just write the stack to storage. Note that 987 overflows off a stack of length 10.
v >>>>>>>>>>>12p:10p11pv
1 0 v<<<<<<<<<<<<<<<<<<
v >210gp10g1-10p^
>10g|
>14p010pv
v<<<<<<<<<<<<<<<<<<<<<<<<
v >210g1+g10g1+10p^
>10g11g-|
v g21g41<
v _ v
>98765432102^>. 2^>.#
The above code writes up to and including the n-1th item on the stack to 'memory', writes the nth item somewhere else, reads the 'memory', then pushes the nth item onto the stack.
The function is called twice by the bottom line of this program.
I propose a simpler solution:
013p 321 01g #
☺
It "stores" 3 in the program at position ☺ (0, 1) (013p), removing it from the stack, and then puts things on the stack, and gets back ☺ on top of the stack (01g). The # ensures that the programs finishes.

Return stack operations generate "invalid memory address" in Gforth 0.7

I'm learning Forth here, and I've got onto return stack operations.
So using the console on Ubuntu 11.04 x64 I am trying to get the TOS onto the return stack but this happens:
1 2 3 4 5 ok
>r
:36: Invalid memory address
>R>>><<<
Backtrace:
What am I doing wrong here?
>r is itself a word and needs to return to the interpreter. When >r is executed as in the question it adds a new return address, an invalid one.
Instead use >r inside a (new) word. Note that the items added to the return stack must be removed before that word ends - the return stack must be in the same state as when the word started executing.
Loops are actually an example of an application of the return stack inside words (and thus your own use of the return stack must also be balanced within loops just as it must be balanced within a word).
What you are trying to to do doesn't really make much sense. A forth machine executes a series of words, the address of the next word in line to be executed is stored in a special register called NEXT (think of it like the instruction pointer of a CPU).
A return stack is needed because, if a call is made to a word that is itself a threaded list of words, then you would end up scrubbing the original address in NEXT register - to stop this from happening, the current contents of the NEXT register are pushed into the return stack.
If I understand correctly >r pushes the top element of the data stuck onto the return stack; in this case, '5' is not valid, because, there are no instructions at the address '5'.
As someone else has pointed out you don't need to be concerned about the return stack, unless you are implementing new control constructs.
You can use the return stack in Gforth in the command line (that's a non-standard feature), with one limitation: It has to be balanced within one line. At the end of the line, the line interpreter is going to return, and therefore, the return stack must contain the expected return address.
So try something like
1 2 3 4 5 >r + r> .s
which should give you
1 2 7 5

Resources