Similar documents
In the game of Chess a queen can move any number of spaces in any linear direction: horizontally, vertically, or along a diagonal.

Eight Queens Puzzle Solution Using MATLAB EE2013 Project

Homework Assignment #1

MAS336 Computational Problem Solving. Problem 3: Eight Queens

CS 540-2: Introduction to Artificial Intelligence Homework Assignment #2. Assigned: Monday, February 6 Due: Saturday, February 18

Lecture 20: Combinatorial Search (1997) Steven Skiena. skiena

ENGR170 Assignment Problem Solving with Recursion Dr Michael M. Marefat

Structured Programming Using Procedural Languages INSS Spring 2018

More Recursion: NQueens

Homework 7: Subsets Due: 10:00 PM, Oct 24, 2017

CS61B, Fall 2014 Project #2: Jumping Cubes(version 3) P. N. Hilfinger

The 8-queens problem

Assignment 6 Play A Game: Minesweeper or Battleship!!! Due: Sunday, December 3rd, :59pm

ENEE 150: Intermediate Programming Concepts for Engineers Spring 2018 Handout #7. Project #1: Checkers, Due: Feb. 19th, 11:59p.m.

CPSC 217 Assignment 3 Due Date: Friday March 30, 2018 at 11:59pm

After learning the Rules, What should beginners learn next?

Pay attention to how flipping of pieces is determined with each move.

CS/COE 1501

Chained Permutations. Dylan Heuer. North Dakota State University. July 26, 2018

Backtracking. Chapter Introduction

Counting Things Solutions

INTRODUCTION TO COMPUTER SCIENCE I PROJECT 6 Sudoku! Revision 2 [2010-May-04] 1

The Classification of Quadratic Rook Polynomials of a Generalized Three Dimensional Board

You ve seen them played in coffee shops, on planes, and

Spring 06 Assignment 2: Constraint Satisfaction Problems

Spring 06 Assignment 2: Constraint Satisfaction Problems

CS256 Applied Theory of Computation

CMPT 310 Assignment 1

Lecture 2: Sum rule, partition method, difference method, bijection method, product rules

Microchess 2.0 gives you a unique and exciting way to use your Apple II to enjoy the intellectually stimulating game of chess. The complete program lo

A CLASSIFICATION OF QUADRATIC ROOK POLYNOMIALS

Which Rectangular Chessboards Have a Bishop s Tour?

Cardinality. Hebrew alphabet). We write S = ℵ 0 and say that S has cardinality aleph null.

CSE548, AMS542: Analysis of Algorithms, Fall 2016 Date: Sep 25. Homework #1. ( Due: Oct 10 ) Figure 1: The laser game.

CS188: Section Handout 1, Uninformed Search SOLUTIONS

CPSC 217 Assignment 3

1 Modified Othello. Assignment 2. Total marks: 100. Out: February 10 Due: March 5 at 14:30

Counting Things. Tom Davis March 17, 2006

YourTurnMyTurn.com: chess rules. Jan Willem Schoonhoven Copyright 2018 YourTurnMyTurn.com

CSE 573 Problem Set 1. Answers on 10/17/08

2 Textual Input Language. 1.1 Notation. Project #2 2

Lab 1. CS 5233 Fall 2007 assigned August 22, 2007 Tom Bylander, Instructor due midnight, Sept. 26, 2007

Movement of the pieces

Algorithmique appliquée Projet UNO

Twenty-fourth Annual UNC Math Contest Final Round Solutions Jan 2016 [(3!)!] 4

ACTIVITY 6.7 Selecting and Rearranging Things

arxiv: v2 [cs.cc] 20 Nov 2018

MA/CSSE 473 Day 13. Student Questions. Permutation Generation. HW 6 due Monday, HW 7 next Thursday, Tuesday s exam. Permutation generation

Strings. A string is a list of symbols in a particular order.

Eleventh Annual Ohio Wesleyan University Programming Contest April 1, 2017 Rules: 1. There are six questions to be completed in four hours. 2.

Pointers. The Rectangle Game. Robb T. Koether. Hampden-Sydney College. Mon, Jan 21, 2013

Chess Handbook: Course One

MA/CSSE 473 Day 14. Permutations wrap-up. Subset generation. (Horner s method) Permutations wrap up Generating subsets of a set

Lab 1. Due: Friday, September 16th at 9:00 AM

Sample Spaces, Events, Probability

Battlehack: Voyage Official Game Specs

Week 3-4: Permutations and Combinations

In order for metogivebackyour midterms, please form. a line and sort yourselves in alphabetical order, from A

WPF PUZZLE GP 2018 ROUND 2 INSTRUCTION BOOKLET. Host Country: Switzerland. Markus Roth, Roger Kohler, Esther Naef

A1 Problem Statement Unit Pricing

Grade 7/8 Math Circles. Visual Group Theory

N-Queens Problem. Latin Squares Duncan Prince, Tamara Gomez February

AP Computer Science A Practice Test 6 - Picture and Elevens Labs

Taking Sudoku Seriously

Homework Assignment #2

Computer Science COMP-250 Homework #4 v4.0 Due Friday April 1 st, 2016

Prolog - 3. Prolog Nomenclature

A complete set of dominoes containing the numbers 0, 1, 2, 3, 4, 5 and 6, part of which is shown, has a total of 28 dominoes.

Final Practice Problems: Dynamic Programming and Max Flow Problems (I) Dynamic Programming Practice Problems

28,800 Extremely Magic 5 5 Squares Arthur Holshouser. Harold Reiter.

17. Symmetries. Thus, the example above corresponds to the matrix: We shall now look at how permutations relate to trees.

Solving Problems by Searching

a b c d e f g h i j k l m n

Recursive Triangle Puzzle

G53CLP Constraint Logic Programming

Second Annual University of Oregon Programming Contest, 1998

Sudoku Solver Version: 2.5 Due Date: April 5 th 2013

LESSON 2: THE INCLUSION-EXCLUSION PRINCIPLE

Tic-tac-toe. Lars-Henrik Eriksson. Functional Programming 1. Original presentation by Tjark Weber. Lars-Henrik Eriksson (UU) Tic-tac-toe 1 / 23

Canadian Mathematics Competition An activity of The Centre for Education in Mathematics and Computing, University of Waterloo, Waterloo, Ontario

OCTAGON 5 IN 1 GAME SET

Chapter 5 Backtracking. The Backtracking Technique The n-queens Problem The Sum-of-Subsets Problem Graph Coloring The 0-1 Knapsack Problem

12th Bay Area Mathematical Olympiad

Senior Math Circles February 10, 2010 Game Theory II

Unit 12: Artificial Intelligence CS 101, Fall 2018

THE ASSOCIATION OF MATHEMATICS TEACHERS OF NEW JERSEY 2018 ANNUAL WINTER CONFERENCE FOSTERING GROWTH MINDSETS IN EVERY MATH CLASSROOM

DELUXE 3 IN 1 GAME SET

Sets. Definition A set is an unordered collection of objects called elements or members of the set.

Lecture 6: Latin Squares and the n-queens Problem

WPF PUZZLE GP 2018 ROUND 2. COMPETITION BOOKLET Host Country: Switzerland. ScHWeIZ. ScHWeiz. schweiz. SchWEIZ. SchwEiz. SchWEiZ. schweiz.

If a pawn is still on its original square, it can move two squares or one square ahead. Pawn Movement

Junior Circle Games with coins and chessboards

Counting in Algorithms

UKPA Presents. March 12 13, 2011 INSTRUCTION BOOKLET.

Adventures with Rubik s UFO. Bill Higgins Wittenberg University

Sets. Gazihan Alankuş (Based on original slides by Brahim Hnich et al.) August 6, Outline Sets Equality Subset Empty Set Cardinality Power Set

8. You Won t Want To Play Sudoku Again

class TicTacToe: def init (self): # board is a list of 10 strings representing the board(ignore index 0) self.board = [" "]*10 self.

Irish Collegiate Programming Contest Problem Set

Two Parity Puzzles Related to Generalized Space-Filling Peano Curve Constructions and Some Beautiful Silk Scarves

Transcription:

CMPS 12A Introduction to Programming Programming Assignment 5 In this assignment you will write a Java program that finds all solutions to the n-queens problem, for. Begin by reading the Wikipedia article on the Eight Queens puzzle at: 1 n 13 http://en.wikipedia.org/wiki/eight_queens_puzzle In the game of Chess a queen can move any number of spaces in any linear direction: horizontally, vertically, or along a diagonal. The Eight Queens puzzle is to find a placement of 8 queens on an otherwise empty a way that no two queens confront each other. One solution to this problem is pictured below. 8 8 chessboard in such The n-queens problem is the natural generalization of placing n queens on an n n chessboard so that no two queens lie on the same row, column or diagonal. There are many ways of solving this problem. Our approach will be to start with a solution to the n-rooks problem (i.e. place n Rooks on an n n chessboard so that no two rooks attack each other) then check if that arrangement is also a solution to n-queens. The rook move in chess is similar to the queen's move except that it cannot move diagonally. 1

Solutions to the n-rooks problem are easy to find since one need only position the rooks so that no two are on the same row and no two are on the same column. Since there are n rows and n columns to choose from, solutions abound. A natural way to encode solutions to n-rooks is as permutations of the integers {1, 2, 3,, n}. A permutation of a set is an ordered arrangement of the elements in that set. If we number the rows and columns of the chessboard using the integers 1 through n, each square is then labeled by a unique pair of coordinates (i, j) indicating the square in row i and column j. The permutation a, a, a,, a ) n n ( 1 2 3 n corresponds to the placement of a piece on the square with coordinates ( a j, j) for 1 j n. For instance, the permutations ( 2, 7, 8, 5,1, 4, 6, 3) and ( 2, 4, 6, 8, 3,1, 7, 5) correspond to two the 8-Rooks solutions pictured below. 8 R 7 R 6 R 5 R 4 R 3 R 2 R 1 R 1 2 3 4 5 6 7 8 8 R 7 R 6 R 5 R 4 R 3 R 2 R 1 R 1 2 3 4 5 6 7 8 Observe that the solution on the right is also a solution to 8-Queens, while the one on the left is not, since certain pairs of rooks lie on the same diagonal (such as the rooks on (7, 2) and (5, 4).) In fact the solution on the right is the 8-Queens solution pictured on the previous page. In general, any solution to the n-queens problem is also a solution to n-rooks, but the converse is false. Not every solution to n-rooks is a solution to n-queens. Your program will generate all solutions to n-rooks by systematically producing all permutations of the set {1, 2, 3,, n}. It will check each n-rooks solution for diagonal attacks to see if the given permutation 2

also solves n-queens. Whenever an n-queens solution is found, your program will print out the permutation, then move on to the next permutation. Thus when ( 2, 4, 6, 8, 3,1, 7, 5 would be printed while ( 2, 7, 8, 5,1, 4, 6, 3) would not. Two major problems must therefore be solved to complete the project: (1) how can you produce all permutations of the set {1, 2, 3,, n}, and (2) given one such permutation how can you determine if two pieces lie on the same diagonal. 3 n 8, ) Permutations There are to choose the first element in the arrangement, n ways to th choose the third,, 2 ways to choose the ( n 1) element, and finally 1 way to choose the and last element in the ordered arrangement. The number of ways of making all these choices in succession is therefore n( n 1)( n 2) 3 2 1 n!. For instance there are 3! 6 permutations of the set {1, 2, 3}: 123, 132, 213, 231, 312, 321. The permutations of a finite set {1, 2, 3,, n} have a natural ordering called the lexicographic order, or alphabetic order. The permutations of {1, 2, 3, 4} are listed in lexicographic order below. n! permutations of a finite set containing n elements. To see this, observe that there are n ways 1234 1243 1324 1342 1423 1432 2134 2143 2314 2341 2413 2431 3124 3142 3214 3241 3412 3421 4123 4132 4213 4231 4312 4321 4! 24 n 1 ways to choose the second element, 2 As an exercise list the 5! 120 permutations of {1, 2, 3, 4, 5} in lexicographic order. After finishing this long exercise, you will see the need for an algorithm that systematically produces all permutations of a finite set. We will represent a permutation a, a, a,, a ) of the set {1, 2, 3,, n} by an array A [ ] of ( 1 2 3 n length n 1, where A[ j] a j for 1 j n, and the element A [0] is simply not used. Your program will include a function with the following heading. static void nextpermutation(int[] A){...} n th

This method will alter its argument A by advancing ( A[1], A[2], A[3],, A[ n] ) to the next permutation in the lexicographic ordering. If ( A[1], A[2], A[3],, A[ n] ) is already at the end of the sequence, the function will reset A to the initial permutation ( 1, 2, 3,, n) in the lexicographic order. The pseudo-code below gives an outline for the body of nextpermutation(). scan the array from right-to-left if the current element is less than its right-hand neighbor call the current element the pivot stop scanning if the left end was reached without finding a pivot reverse the array (permutation was lexicographically last, so start over) return scan the array from right-to-left again if the current element is larger than the pivot call the current element the successor stop scanning swap the pivot and the successor reverse the portion of the array to the right of where the pivot was found return Run the above procedure by hand on the initial permutation (1, 2, 3, 4) and see that it does indeed produce all 24 permutations of the set {1, 2, 3, 4} in lexicographic order. Also check that (4, 3, 2, 1) which is the final permutation in lexicographic order, is returned to the initial state (1, 2, 3, 4). Finding Diagonal Attacks Your program will also include another function with the following heading. static boolean issolution(int[] A){...} This method will return true if the permutation represented by ( A[1], A[2], A[3],, A[ n] ) places no two queens on the same diagonal, and will return false otherwise. To check if two queens at ( A [ i], i ) and ( A [ j], j ) lie on the same diagonal, it is sufficient to check whether their horizontal distance apart is the same as their vertical distance apart, as illustrated in the diagram below. horizontal distance 6 2 4 8 7 Q 6 5 4 3 Q 2 1 1 2 3 4 5 6 7 8 vertical distance 7 3 4 4

Function issolution() will compare each pair of queens at most once. If a pair is found on the same diagonal, do no further comparisons and return false. If all comparisons are performed without finding a diagonal attack, return true. (Question: why is the number of 2-element subsets of an n element set exactly?) n( n 1) / 2 n( n 1) / 2 Program Operation Your program for this project will be called Queens.java. You will include a Makefile that creates an executable Jar file called Queens, allowing one to run the program by typing Queens at the command line. Your program will read an integer n from the command line indicating the size of the Queens problem to solve. The program will operate in two modes: normal and verbose (which is indicated by the command line option "-v"). In normal mode, the program prints only the number of solutions to n-queens. In verbose mode, all permutations representing solutions to n-queens will be printed in lexicographic order, followed by the number of such solutions. Thus to find the number of solutions to 8-Queens you will type: % Queens 8 To print all 92 unique solutions to 8-Queens type: % Queens v 8 If the user types anything on the command line other than the option v and a number n, the program will print a usage message to stderr and quit. A sample session is included below (remember that % is the unix prompt). % Queens Usage: Queens [-v] number Option: -v verbose output, print all solutions % Queens blah Usage: Queens [-v] number Option: -v verbose output, print all solutions % Queens 5 5-Queens has 10 solutions % Queens -v 5 (1, 3, 5, 2, 4) (1, 4, 2, 5, 3) (2, 4, 1, 3, 5) (2, 5, 3, 1, 4) (3, 1, 4, 2, 5) (3, 5, 2, 4, 1) (4, 1, 3, 5, 2) (4, 2, 5, 3, 1) (5, 2, 4, 1, 3) (5, 3, 1, 4, 2) 5-Queens has 10 solutions % Queens -v 6 (2, 4, 6, 1, 3, 5) (3, 6, 2, 5, 1, 4) (4, 1, 5, 2, 6, 3) (5, 3, 1, 6, 4, 2) 6-Queens has 4 solutions % Queens -v 4 (2, 4, 1, 3) (3, 1, 4, 2) 4-Queens has 2 solutions % Queens -v 3 5

3-Queens has 0 solutions % It is recommended that you write helper functions to perform basic subtasks such as: print the usage message and quit, calculate the factorial of n, print out a formatted array as above, swap two elements in an array, and reverse the elements in a subarray. Some of these methods have already been posted on the website as examples. There are more efficient procedures for solving n-queens that use programming techniques beyond the scope of this course (such as recursion). Even if you know how to use these techniques, you are required to solve the problem as indicated in this project description. Your program should work very quickly on problem sizes up to 11. At size 12, it should still take under a minute, and at size 13, it will probably take between 5 and 10 minutes. Beyond that, expect your program to impractically slow. What to turn in Write a Makefile for this project that creates an executable Jar file called Queens, and that includes a clean target (as in lab4). Submit the files Makefile and Queens.java to the assignment name pa5. As always start early and ask questions of myself, the TAs and on Piazza. 6