Question

Assignment 2 In this assignment, you will write two short programs to solve problems using recursion....

Assignment 2

In this assignment, you will write two short programs to solve problems using recursion.

1. Initial Setup

  1. Log in to Unix.

  2. Run the setup script for Assignment 2 by typing:

        setup 2
    

2. Towers of Hanoi

Legend has it that in a temple in the Far East, priests are attempting to move a stack of disks from one peg to another. The initial stack had 64 disks threaded onto one peg and arranged from bottom to top by decreasing size. The priests are attempting to move the stack from this peg to a second peg under the constraints that exactly one disk is moved at a time, and at no time may a larger disk be placed above a smaller disk. A third peg is available for temporarily holding the disks. According to the legend, the world will end when the priests complete their task.

Consider three pegs numbered 1 through 3. Let us assume that the priests are attempting to move the 64 disks from peg 1 to peg 2, using peg 3 as a temporary holding peg. The problem is to design an algorithm that that will print the precise sequence of disk peg-to-peg transfers.

If you were to approach this problem with conventional methods, you would rapidly find yourself hopelessly knotted up in managing the disks. Instead, if you attack the problem with recursion in mind, it immediately becomes tractable. If we assume that we have a function that can move n - 1 disks from one peg to another using a third peg as a temporary holding peg, then we can easily formulate an algorithm to move n disks from peg 1 to peg 2 by using the function that moves n - 1 disks as follows:

  1. Move n - 1 disks from peg 1 to peg 3, using peg 2 as a temporary holding peg.

  2. Move the last disk (the largest) from peg 1 to peg 2.

  3. Move the n - 1 disks from peg 3 to peg 2, using peg 1 as a temporary holding disk.

Write a recursive program that solves the Towers of Hanoi problem. Your solution must be recursive to be eligible for any credit.

2.1. Input

Your program must accept a single command line argument, a positive integer. This integer n will represents the number of disks to move. Number the disks from 1 (the smallest disk) to n (the largest disk). You should always start with all the disks on peg 1 with pegs 2 and 3 empty. Your program should then produce the sequence of disk peg-to-peg moves to move all the disks from peg 1 to peg 2.

2.2. Output

Your output should print one move per line. Each move must be in the following format,

1 2->3

which is interpreted as "move disk 1 from peg 2 to peg 3." Assuming that the name of your program is hanoi, below is an example of what an execution of your program should look like:

z123456@turing:~$ ./hanoi 2
1 1->3
2 1->2
1 3->2
z123456@turing:~$

The format of the output must be exactly has shown above. There is another program (described below) that we have written to check the output of your program. It expects exactly this format.

WARNING: The number of moves it takes to transfer the disks from peg 1 to 2 grows exponentially as you increase the number of disks, (for n disks the number of moves is 2n - 1). If each move produces 7 bytes of output, redirecting the 20 disk output to a file will produce a 7MB file. Take care not to do that. It is safe to run your program with as many disks as you want as long as the output goes to the screen. But be careful not to redirect the stdout of your program for large disk counts, e.g., do not do the following,

z123456@turing:~/csci241/Assign2$ ./hanoi 20 > 20.out

If this does happen, don't panic. Simply remove the file using the command

rm 20.out

2.3. File You Must Write

Write the code for this part of the assignment in a single file which must be called hanoi.cpp.

2.4. Files We Give You

If you use the setup command to get ready for this assignment, you will find an executable file called test_hanoi in your ~/csci241/Assign2 directory.

You can use test_hanoi to test the output of your program (rather then checking it by hand). test_hanoi reads the output (in the format described above) of hanoi and prints either "SUCCESS" or "failure". test_hanoi also takes a command line argument that must match the command line argument passed to hanoi that generated the output file.

You can run test_hanoi in one of two ways.

z123456@turing:~/csci241/Assign2$ ./hanoi 5 > 5.out
z123456@turing:~/csci241/Assign2$ ./test_hanoi 5 < 5.out
SUCCESS
z123456@turing:~/csci241/Assign2$

In this method you are storing the output from hanoi in a file called 5.out and then passing that file to test_hanoi. This should only be used for smaller runs, say problems with 10 or fewer disks. You might want to run hanoi this way while debugging; in case test_hanoi reports "failure", you can hand-inspect 5.out to find the error.

z123456@turing:~/csci241/Assign2$ ./hanoi 5 | ./test_hanoi 5
SUCCESS
z123456@turing:~/csci241/Assign2$

In this method you do not create an output file. The output of hanoi is "piped" directly as input to test_hanoi. Running large problems (many disks) with this method does not create large files but may take very long to execute. You're probably safe with disk counts < 20.

2.5. Hints

Consider writing a recursive function

void move(int n_disks, int src_peg, int dest_peg, int temp_peg)

3. Eight Queens

Write a program that places eight queens on a chessboard (8 x 8 board) such that no queen is "attacking" another. Queens in chess can move vertically, horizontally, or diagonally.

How you solve this problem is entirely up to you. You may choose to write a recursive program or an iterative (i.e., non-recursive) program. You will not be penalized/rewarded for choosing one method or another. Do what is easiest for you.

3.1. Output

Below is one solution to the eight queens problem, there may be others. Your program only needs to find one solution, any solution, and print it. Assuming the name of your program is queens, executing your program should look like this:

z123456@turing:~/csci241/Assign2$ ./queens
1 0 0 0 0 0 0 0
0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 1
0 0 0 0 0 1 0 0
0 0 1 0 0 0 0 0
0 0 0 0 0 0 1 0
0 1 0 0 0 0 0 0
0 0 0 1 0 0 0 0
z123456@turing:~/csci241/Assign2$

where a '1'; means a queen is on that square of the board and a '0' means the square is empty.

Note that it is very important that your output be formatted exactly as shown above. In grading your program, its output will be checked by another program (we wrote) that expects as input a solution in that format.

3.2. File You Must Write

Write the code for this assignment in a single file which must be called queens.cpp.

3.3. Hints

You might want to represent the chessboard using a 2-D array of integers or Boolean variables, e.g., int board[8][8] or bool board[8][8]. This array can be declared in your main() function or as a data member of a class that you write. Initialize the board by filling the array with 0s or false.

A general strategy is to solve the problem by starting with the top row of the chessboard and proceed down the chessboard one row at a time. Only place a single queen in each row. This eliminates the need to check for other queens on the same row (i.e., queens that could attack horizontally). Always start processing a row by attempting to place a queen in the leftmost column and moving to the right as necessary. When placing a queen in a particular row remember that it suffices to only check the rows above you. If the queen is safe, then place it on the board there (board[row][col] = 1; or board[row][col] = true;) and proceed to the next row. If it is not safe, then continue to move one column to the right until you find a safe spot or run out of columns.

There are two general ways you can solve the eight queens problem; recursively or iteratively. Below are some more general hints that use the suggestions above, first in a recursive algorithm and then in an iterative algorithm. Although two general algorithms are discussed below, remember that you are only required to write one solution to this problem. Write as many solutions as you would like, but submit only one program for grading. You may elect to use the hints from either section below, or you may decide to ignore all of them and design a solution on your own. Whatever you decide is acceptable.

3.3.1. Recursive Algorithm

You could write a recursive function called place_queens() that returns a Boolean value and accepts two arguments, the chessboard and a row index. If your chessboard is a data member of a class, then this will be a member function of that class and you will only need to pass it the row index.

The way to think about place_queens() is that it attempts to place all the queens from the row you specified and down. If it can place all the queens from that row down, it returns true and leaves the queens on the chessboard. If it couldn't then it returns false and removes all the queens from that row down. This way, after you initialize the chessboard, you may make the single call from your main() routine like this place_queens(board, 0) (for a function) or this q.place_queens(0) (for a member function, assuming q is an instance of the class you defined). Of course, you need to check the return value of the function for success or failure.

place_queens() always starts by attempting to place a queen in the leftmost column of the row it received as an argument and checking that it is safe from all the queens in the rows above it. If it is not safe, then proceed by moving the queen one column to the right and checking that square. If you get to the right end of the board without finding a safe spot, then return false. If you find a safe spot, then place the queen on the board and call place_queens() again (recursively) asking it to place all the queens on the rows below yours (i.e., passing it the same board it received but incrementing the row index by 1).

Test the return value of that recursive call. Recall that place_queens() will attempt to place all the queens in the rows below and return either false or true based its success. If the return value is true, then simply return true yourself and you are done. If it is false, then there was no way to place the other queens on the board. You must try and find another safe column (to the right) in the same row. Move the queen in this row to the right, one column at a time, until you find another square where the queen is safe from all the queens above it. If you find another safe column, place the queen there and make another recursive call to place_queens(). If there are no more safe columns in this row, then remove the queen from this row and return false.

The stopping condition for this recursive algorithm is when you enter place_queens() and the row that you have been passed is greater than 7 (assuming the top row is row 0).

3.3.2. Iterative Algorithm

Start by placing a queen in the leftmost column of the top row. Since there are no rows above the top row, there are no "attacking" queens to check, so proceed to the second row. As you move from the first row to the second row we call this "approaching a row from the top". This is differs from "approaching a row from the bottom" (described below).

When approaching a row from the top there are no queens on that row. Start by attempting to place the queen in the leftmost column and checking all the rows above. If the queen is safe in that column, place it on the board and proceed to the next row. If it is not safe, try the next column to the right and check there. If you get to the end of the row without finding a safe column for the queen, you must back up a row. This requires you to go back to the previous row and move that queen to the right. This is what is meant by "approaching the row from the bottom".

When approaching a row from the bottom, there is already a queen placed on that row and it is already safe from all the queens above it. The problem is that no more queens could be placed on the board in the rows below it. So, this queen must be moved from its safe spot to another safe spot in the same row. All the columns to the left of this queen have already been checked. The only place for this queen to go is to the right. Start by trying one square to the right and checking the rows above. If it is safe, place the queen there and proceed to the row below approaching it from the top. If it is not safe, keep moving the queen to the right. If you run out of columns, then remove the queen from the board and back up to the row above approaching it from the bottom.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Hey there isn't enough information about setup command. So I am writing code only for tower of hanoi moves. Also you could solve the problem with only one recursive function. I am also changing the output format into something simpler and easier to understand. You could easily change it by changing the print systems.

***************************************************************************************

// C++ recursive function to

// solve tower of hanoi puzzle

#include <bits/stdc++.h>

using namespace std;

  

void towerOfHanoi(int n, char from_rod,

                    char to_rod, char aux_rod)

{

    if (n == 1)

    {

        cout << "Move disk 1 from rod " << from_rod <<

                            " to rod " << to_rod<<endl;

        return;

    }

    towerOfHanoi(n - 1, from_rod, aux_rod, to_rod);

    cout << "Move disk " << n << " from rod " << from_rod <<

                                " to rod " << to_rod << endl;

    towerOfHanoi(n - 1, aux_rod, to_rod, from_rod);

}

  

// Driver code

int main()

{

    int n = 4; // Number of disks

    towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods

    return 0;

}

******************************************************************************************************

Add a comment
Know the answer?
Add Answer to:
Assignment 2 In this assignment, you will write two short programs to solve problems using recursion....
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • please explain/ comment 3. Eight Queens Write a program that places eight queens on a chessboard...

    please explain/ comment 3. Eight Queens Write a program that places eight queens on a chessboard (8 x 8 board) such that no queen is "attacking" another. Queens in chess can move vertically, horizontally, or diagonally. How you solve this problem is entirely up to you. You may choose to write a recursive program or an iterative (i.e., non-recursive) program. You will not be penalized/rewarded for choosing one method or another. Do what is easiest for you. 3.1. Output Below...

  • CMPS 12B Introduction to Data Structures Programming Assignment 2 In this project, you will write...

    can i get some help with this program CMPS 12B Introduction to Data Structures Programming Assignment 2 In this project, you will write a Java program that uses recursion to find all solutions to the n-Queens problem, for 1 Sns 15. (Students who took CMPS 12A from me worked on an iterative, non-recursive approach to this same problem. You can see it at https://classes.soe.ucsc.edu/cmps012a/Spring l8/pa5.pdf.) Begin by reading the Wikipcdia article on the Eight Queens puzzle at: http://en.wikipedia.org/wiki/Eight queens_puzzle In...

  • Main objective: Solve the n queens problems. You have to place n queens on an n...

    Main objective: Solve the n queens problems. You have to place n queens on an n × n chessboard such that no two attack each other. Important: the chessboard should be indexed starting from 1, in standard (x, y) coordinates. Thus, (4, 3) refers to the square in the 4th column and 3rd row. We have a slight twist in this assignment. We will take as input the position of one queen, and have to generate a solution with a...

  • Write a program to place eight queens on an 8 x 8 chessboard in such a...

    Write a program to place eight queens on an 8 x 8 chessboard in such a way that one queen is to be in each row. A program will use 2 DIMENIONAL array x[r][c] to do this configuration. If x[r] has value c, then in row r there is a queen in column c. Write a program that asks a user to enter the columns that contain queens in the 8 rows. The program then places the queens in these...

  • in c++ Purpose: This lab will give you experience harnessing an existing backtracking algorithm for the...

    in c++ Purpose: This lab will give you experience harnessing an existing backtracking algorithm for the eight queens problem, and seeing its results displayed on your console window (that is, the location of standard output). Lab A mostly complete version of the eight queens problem has been provided for you to download. This version has the class Queens nearly completed. You are to provide missing logic for the class Queens that will enable it to create a two-dimensional array that...

  • Please help i need a C++ version of this code and keep getting java versions. Please...

    Please help i need a C++ version of this code and keep getting java versions. Please C++ only Purpose: This lab will give you experience harnessing an existing backtracking algorithm for the eight queens problem, and seeing its results displayed on your console window (that is, the location of standard output). Lab A mostly complete version of the eight queens problem has been provided for you to download. This version has the class Queens nearly completed. You are to provide...

  • write in c programming language . question 5.36 Fibonaco for its rets ing terms, a) Write...

    write in c programming language . question 5.36 Fibonaco for its rets ing terms, a) Write a warruse function fibonacci(n) that calculatus 0, 1, 1, 2, 3, 5, 8, 13, 21,... (n) that calculates the n" Fib begins with the terms and 1 and has the property preceding terms. a) Write a cand unsigned long long int for i number. Use unsigned int for the function's paramete her that can be printed on your system. type. b) Determine the largest...

  • Write a Python program that implements the Towers of Hanoi, using the recursive algorithm discussed in...

    Write a Python program that implements the Towers of Hanoi, using the recursive algorithm discussed in class. Use command-line arguments to pass parameters to the program - spring% python towersOfHanoi.py USAGE: towersOfHanoi.py <# rings> <FROM peg> <TO peg> spring% python towersOfHanoi.py 4 1 3 Move disk from peg 1 to peg 2 Move disk from peg 1 to peg 3 Move disk from peg 2 to peg 3 Move disk from peg 1 to peg 2 Move disk from peg...

  • Complete the program that solves the Eight Queens problem. The program’s output should look similar to:...

    Complete the program that solves the Eight Queens problem. The program’s output should look similar to: |1|0|0|0|0|0|0|0| |0|0|0|0|0|0|1|0| |0|0|0|0|1|0|0|0| |0|0|0|0|0|0|0|1| |0|1|0|0|0|0|0|0| |0|0|0|1|0|0|0|0| |0|0|0|0|0|1|0|0| |0|0|1|0|0|0|0|0| Use the Queens class given. In your implementation of the Queens class, complete the body of all methods marked as “To be implemented in Programming Problem 1.” Do not change any of the global variable declarations, constructor or placeQueens methods. Here is what I have so far with notes of what is needed. public class Queens...

  • Part A [50] in c++ A toy that many children play with is a base with...

    Part A [50] in c++ A toy that many children play with is a base with three pegs and five disks of different diameters. The disks begin on one peg, with the largest disk on the bottom and the other four disks added on in order of size. The idea is to move the disks from the peg they are on to another peg by moving only one disk at a time and without ever putting a larger disk on...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT