The stack is implemented as a class containing an array of items, a data member
ID: 3680217 • Letter: T
Question
The stack is implemented as a class containing an array of items, a data member indicating the index of the last item put on the stack (top), and two Boolean data members underFlow and overFlow. Show the result of the operation on the stack. Indicate what goes in the spaces marked (a)? through (j)?. Choose "T" or "F" for True or False in the Boolean data members. If there should be no entry in the space, choose "no entry." Some answer choices may be selcted more than once, or not at all.
stack.Pop(letter);
Letter
Z
Letter
(a)?
stack.top
4
stack.top
(b)?
.overFlow
.overFlow
(c)?
.underFlow
.underFlow
(d)?
.items
A
B
X
Y
Z
.items
(e)?
(f)?
(g)?
(h)?
(i)?
[0]
[1]
[2]
[3]
[4]
[0]
[1]
[2]
[3]
[4]
(a)? would be "Z" for example
Letter
Z
Letter
(a)?
stack.top
4
stack.top
(b)?
.overFlow
.overFlow
(c)?
.underFlow
.underFlow
(d)?
.items
A
B
X
Y
Z
.items
(e)?
(f)?
(g)?
(h)?
(i)?
[0]
[1]
[2]
[3]
[4]
[0]
[1]
[2]
[3]
[4]
Explanation / Answer
given three boolean variables, a, b, and c, return true if at least two out of the three are true.
My solution follows:
Rather than writing:
Write:
As for the expression itself, something like this:
(or)
It tests a and b exactly once, and c at most once.
First and second iterations:
Later iterations:
and running them through the decompiler (javap -c X > results.txt):
You can see that the ?: ones are slightly better then the fixed up version of your original. The one that is the best is the one that avoids branching altogether. That is good from the point of view of fewer instructions (in most cases) and better for branch prediction parts of the CPU, since a wrong guess in the branch prediction can cause CPU stalling.
I'd say the most efficient one is the one from moonshadow overall. It uses the fewest instructions on average and reduces the chance for pipeline stalls in the CPU.
To be 100% sure you would need to find out the cost (in CPU cycles) for each instruction, which, unfortunately isn't readily available (you would have to look at the source for hotspot and then the CPU vendors specs for the time taken for each generated instruction).
Here's another implementation using map/reduce. This scales well to billions of booleans© in a distributed environment. Using MongoDB:
Creating a database values of booleans:
Creating the map, reduce functions:
Running map/reduce:
More general :
More scalable :
Consider also its disassembled version as given by "javap -c":
Here's another implementation using map/reduce. This scales well to billions of booleans© in a distributed environment. Using MongoDB:
Creating a database values of booleans:
db.values.insert({value: true}); db.values.insert({value: false}); db.values.insert({value: true}); Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.