Applications

Published on February 2017 | Categories: Documents | Downloads: 38 | Comments: 0 | Views: 299
of 6
Download PDF   Embed   Report

Comments

Content

 

Applications Towers of Hanoi 

Towers of Hanoi One of the most interesting applications of stacks can be found in solving a puzzle called Tower of Hanoi. According to an ol d Brahmin story, the existence of the universe is calculated in terms of the time taken by a number of monks, who are working all the time, to move 64 disks from one pole to another. But there are some rules about how this should be done, which are: 1.  2.  3. 

You can move only one disk at a time. For temporary storage, a third pole may be used. You cannot place a disk of larger diameter on a disk of smaller diameter. diameter. [5] 

For algorithm of this puzzle see  see  Tower of Hanoi. Hanoi. The C++ code for this solution can be implemented in two ways. [edit edit]] First Implementation (Without using Stacks) Here we assume that A is first tower, B is second tower & C is third tower. void TowersofHanoi(int n, int a, int b, int c) { //Move top n disks from tower a to tower b, use tower c for intermediate storage. if(n > 0) { TowersofHanoi(n-1, TowersofHanoi(n -1, a, b, c); //recursion cout << " Move top disk from tower " << a << " to tower " << b << endl ; TowersofHanoi(n-1, TowersofHanoi(n -1, a, b, c); //recursion } }

Output : (when there are 4 disks) disks)  

Move disk

From peg

To peg

1

A

B

2

A

C

1

B

C

3

A

B

1

C

A

2

C

B

1

A

B

4

A

C

1

B

C

2

B

A

1

C

A

3

B

C

1

A

B

2

A

C

1

B

C

 

 

Second Implementation (Using Stacks) // Global variable , tower [1:3] are three towers arrayStack<int> tower[4]; void TowerofHanoi(int n) {

// Preprocessor for moveAndShow. for (int d = n; d > 0; d--) tower[1].push(d); moveAndShow(n, 1, 2, 3);

//initialize //add disk d to tower 1 /*move n disks from tower 1 to tower 3 using tower 2 as intermediate tower*/

} void moveAndShow(int n, int a, int b, int c) { // Move the top n disks from tower a to tower b showing states. // Use tower c for intermediate storage. if(n > 0) { moveAndShow(n-1, a, c, b); //recursion int d = tower[x].top(); //move a disc from top of tower x to top of tower[x].pop(); //tower y tower[y].push(d); showState(); //show state of 3 towers moveAndShow(n-1, c, b, a); //recursion } }

However  Complexity  However Complexity  for above written implementations is O(2^n). So it's obvious that problem can only be solved for small values of n (generally n <= 30). In case of the monks, the number of turns taken to transfer 64 disks, by following the above rules, will be 18,446,744,073,709,551,615; which will surely take a lot of time!!

 Applications Three applications of stacks are presented here. These examples are central to many activities that a computer must do and deserve time spent with them. 1.  2.  3. 

Expression evaluation Backtracking (game playing, finding paths, exhaustive searching) Memory management, run-time environment for nested language features.

Expression evaluation In particular we will consider arithmetic expressions. expressions. Understand that there are boolean and logical expressions that can be evaluated in the same way. Control structures can also be treated similarly in a compiler. This study of arithmetic expression evaluation is an e xample of problem solving where you solve a si mpler problem and then transform the actual problem to the simpler one. Aside: The NP-Complete problem. There are a set of apparently intractable problems: finding the shortest ro ute in a graph (Traveling Salesman Problem), bin packing, linear programming, etc. that are similar enough that if a polynomial solution is ever found (exponential solutions abound) for one of these problems, then the solution can be applied to all problems.

Infix, Prefix and Postfix Notation We are a ccustomed to write arithmetic expressions with the operation between the two operands: a+b or c/d. c/d. If we write a+b*c a+b*c,, however, we have to apply precedence rules to avoid the ambiguous evaluation (add first or multiply first?).

 

There's no real reason to put the operation between between the variables or values. They can just as well precede or follow the operands. operands. You should note the advantage of prefix and postfix: the need for precedence rules and parentheses are eliminated.

Infix

Prefix

Postfix

a+b

+ab

ab+

a+b*c

+a*bc

abc*+

(a + b) * (c - d)

*+ab-cd

ab+cd-*

b*b-4*a*c 40 - 3 * 5 + 1

Postfix expressions are easily evaluated with the aid of a stack.

Postfix Evaluation Algorithm Assume we have a string of operands and operators, an informal, by hand process is 1.  2.  3.  4.  5. 

Scan the expression left to right Skip values or variables (operands) (operands) When an operator is found, apply the operation to the preceding two operands Replace the two operands and operator with the calculated value (three symbols are replaced with one operand) Continue scanning until only a value remains--the result of the expression

The time complexity is O(n) because each operand is scanned once, and each operation is performed once. A more formal algorithm: create a new stack while(input stream is not empty){ token = getNextToken(); getNextToken(); if(token instanceof operand){ push(token); } else if (token instance of operator) op2 = pop(); op1 = pop(); result = calc(token, op1, op2); push(result); } } return pop();

Demonstration with 2 3 4 + * 5 -

Infix transformation to Postfix This process uses a stack as well. We have to hold information that's expressed inside parentheses while scanning to find the closing ')'. We also have to hold information information on operations that are of low lower er precedence on the stack. The algorithm is: 1.  2.  3.  4. 

 

5.  6.

Create an empty stack and an empty postfix output string/stream Scan the infix input string/stream left to right If the current input token is an operand, simply append it to the output string (note the examples above that the operands remain in the same order) If the current input token is an operator, pop off all operators that have equal or higher precedence and append them to the output string; push the operator onto the stack. The order of popping is the order in the output. If the the current current input input token token is is ')', '(', pop pushoff it onto the stack and append them to the output string until a '(' is popped; discard the '('. If all operators

 

7. 

If the end of the input string is found, pop all operators and append them to the output string.

This algorithm doesn't handle errors in the input, although careful analysis of parenthesis or lack of parenthesis could point to such error determination. Apply the algorithm to the above expressions.

Backtracking Backtracking is used in algorithms in which there are steps along some path (state) from some starting point to some goal.

     



Find your way through a maze.



Find a path from one point in a graph (roadmap) to another point.



Play a game in which there are moves to be made (checkers, chess).

In all of these cases, there are choices to be made among a number of options. options. We need some way to remember these decision points iin n case we want/need to come back and try the alternative Consider the maze. At a point where a choice is made, we may discover that the choi choice ce leads to a dead-end. We want to retrace back to that decision point and then try the other (next) alternative. Again, stacks can be used as part of the solution. Recursion is another, typically more favored, solutio solution, n, which is actually implemented by a stack. 

Memory Management Any modern computer environment uses a stack as the primary memory management model for a running program. Whether it's native code (x86, Sun, VAX) or JVM, a stack is at the center of the run-time environment for Java, C++, Ada, FORTRAN, etc. The discussion of JVM in the text is consistent with NT, Solaris, VMS, Unix runtime environments. Each program that is running in a computer system has its own memory allocation containing the typical layout as shown below.

 

Call and return process When a method/function is called 1.  2.  3.  4.  5. 

An activation record is created; its size depends on the number and size of the local variables and pa rameters. The Base Pointer value is saved in the special location reserved for it The Program Counter value is saved in the Return Address location The Base Pointer is now reset to the new base (top of the call stack prior to the creation of the AR) The Program Counter is set to the location of the first bytecode of the method being called

6. 7.  

Copies the calling parameters into the Parameter region Initializes local variables in the local variable region

While the method executes, the local variables and parameters are simply found by adding a constant associated with each variable/parameter to the Base Pointer. When a method returns 1.  2.  3. 

Get the program counter from the activation record and replace what's in the PC Get the base pointer value from the AR and replace what's in the BP Pop the AR entirely from the stack.

Application areas for stack computers, like those for computers in general, are only limited by the imagination. Some of the applications that seem well suited for stack machines include: Image Processing: Processing: Object recognition, including optical character recognition, thumb print recognition and handwriting recognition as well as image enhancement require extremely powerful processors, but have wide application. Many commercially interesting applicatio applications ns require that the processor be small, inexpensive and portable. microcontroller ler for each joint plus a Robotics controllers: controllers: Robot arms have 5 or 6 joints (degrees of freedom). A typical strategy is to have a microcontrol more powerful processor for centralized control. With powerful microcontrollers, each joint can p erform complex positional calculations in real time. In a mobile system, small size and low power consumption are vital. Digital Filters: Filters: Filters require high speed multiplications to keep up with high data flow rates. Stack processors have the room on -chip for hardware multipliers and algorithm specific hardware to quickly perform digital filter calculations. Process Control: Control: More powerful processors can go beyond simple process control techniques to apply expert system technology to real time process monitoring and control. Stack machines are particularly well suited for rule-based systems. Computer Graphics: Graphics: While there are several special purpose graphics accelerator chips on the market, these tend to concentrate on the primitives of drawing lines and moving blocks of bits. The exciting opportunity here is in the area of interpreting high level graphics command languages for both laser printers and device independent screen display languages. One of the predominant languages, Postscript, is similar to Forth. Other Computer Peripherals: Peripherals : The low system cost of a stack machine makes it well suited for controlling computer peripher peripherals als such as disk  drives and c ommunication links. Telecommunications : High speed controllers can provide the capability for data compression and therefore lower transmission costs for telefax and modem applications. They can also monitor the performance of transmission equipment. Automotive Control: Control: The automotive market forces very severe restrictions on cost and environmental requirements. In this business a minute difference in cost per component can add up to large profits or losses. A high level of system integration is mandatory. Computers can improve car performance and sa fety even while reducing system cost in applications such as computerized ignition, brakin braking, g, fuel distribution, anti-theft devices, collision alert systems, and dash display systems. Consumer Electronics: Electronics: Consumer electronics are, if anything, more sensitive to pricing and system integration level than are automotive products. Anyone who has taken apart an inexpensive calculator or digital watch knows knows the miracles that can be accomplished with a few pieces of plastic and a single chip. Opportunities for the use of high speed, portable, inexpensive stack processors abound in music synthesis (such as MIDI compatible devices), compact laser disk sound and video playback devices, digital tape devices, slow scan television via telephone lines, interactive cable TV services, and video games.

 

Military and Spaceborne Control Applications: Applications : While spaceborne applications may be used for commercial purposes, they have the same reliability and environmental requirements requirements as many military applications. Stack processors are well suited to high speed control a pplications involving missiles and aircraft. In addition, there are applications in a coustic and electronic signal processing, image enhancement, communications, fire control, and battlefield management. Parallel processing: processing: Preliminary research shows that stack machines can execute functional programming languages very efficiently. efficiently. Programs written in these languages have a great deal of inherent parallelism, which may be exploited by a multiprocessor stack machine system.  

Sponsor Documents

Or use your account on DocShare.tips

Hide

Forgot your password?

Or register your new account on DocShare.tips

Hide

Lost your password? Please enter your email address. You will receive a link to create a new password.

Back to log-in

Close