1 CS 410 Mastery in Programming Chapter 10 Hints for Simple Sudoku Herbert G. Mayer, PSU CS Status 7/29/2013.

Slides:



Advertisements
Similar presentations
Unions The storage referenced by a union variable can hold data of different types subject to the restriction that at any one time, the storage holds data.
Advertisements

Playing Fair at Sudoku Joshua Cooper USC Department of Mathematics.
1 CS 162 Introduction to Computer Science Chapter 8 Pointers Herbert G. Mayer, PSU Status 11/20/2014.
Graphs Graphs are the most general data structures we will study in this course. A graph is a more general version of connected nodes than the tree. Both.
Stacks CS 3358 – Data Structures. What is a stack? It is an ordered group of homogeneous items of elements. Elements are added to and removed from the.
Announcements Assignment #4 is due tonight. Last lab program is going to be assigned this Wednesday. ◦ A backtracking problem.
ECE 103 Engineering Programming Chapter 11 One Minute Synopsis Herbert G. Mayer, PSU CS Status 7/1/2014.
Loops (Part 1) Computer Science Erwin High School Fall 2014.
Backtracking COP Backtracking  Backtracking is a technique used to solve problems with a large search space, by systematically trying and eliminating.
Backtracking What is backtracking?
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 4 – C Program Control Outline 4.1Introduction.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
CS 206 Introduction to Computer Science II 11 / 05 / 2008 Instructor: Michael Eckmann.
Unit 171 Algorithms and Problem Solving - II Algorithm Efficiency Primality Testing Improved Primality Testing Sieve of Eratosthenes Primality Testing.
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
1 Applications of Recursion (Walls & Mirrors - Chapter 5)
CS194 Project: Sudoku Difficulty Kha Chu Advisor: Professor Sahai.
1 CS 162 Introduction to Computer Science Chapter 5 ASCII to Integer Conversion Herbert G. Mayer, PSU Status 11/9/2014.
1 CS 162 Introduction to Computer Science Chapter 4 Function Calls Herbert G. Mayer, PSU Status 11/9/2014.
Recursion Chapter 7. Chapter Objectives  To understand how to think recursively  To learn how to trace a recursive method  To learn how to write recursive.
SOLVING SUDOKU WITH MATLAB Raluca Marinescu, Andrea Garcia, Ivan Castro, Eduard Enoiu Mälardalen University, Västerås,
Angie Rangel Jose De Jesus Melendez Carlos Aguilar Drake Jain DISCRETE MATHEMATICS MATH 170 PROJECT PART II.
Lecturer: Dr. AJ Bieszczad Chapter 11 COMP 150: Introduction to Object-Oriented Programming 11-1 l Basics of Recursion l Programming with Recursion Recursion.
1 Chapter 13 Recursion. 2 Chapter 13 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions l Writing Recursive.
Constraint Satisfaction Problems (CSPs) CPSC 322 – CSP 1 Poole & Mackworth textbook: Sections § Lecturer: Alan Mackworth September 28, 2012.
HISTORY The problem was originally proposed in 1848 by the chess player Max Bezzel, and over the years, many mathematicians, including Gauss have worked.
Lists. Container Classes Many applications in Computer Science require the storage of information for collections of entities e.g. a student registration.
Stacks  Introduction  Applications  Implementations  Complex Applications.
1 CS 163 Data Structures Chapter 9 Building, Printing Binary Trees Herbert G. Mayer, PSU Status 5/21/2015.
Announcements This Wednesday, Class and Labs are cancelled! The last lab is due this Wednesday … how many people are planning on doing it? Finally posted.
Data Structures Using C++ 2E1 Recursion and Backtracking: DFS Depth first search (a way to traverse a tree or graph) Backtracking can be regarded as a.
HKOI2006 Analysis and Solution Junior Q3 – Sudoku HKOI Training Team
Sudoku Jordi Cortadella Department of Computer Science.
CSC 211 Data Structures Lecture 13
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
CS101 Computer Programming I Chapter 4 Extra Examples.
Data Structures & Algorithms
1 Data Structures CSCI 132, Spring 2014 Lecture 17 Backtracking.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
1 Searching and Sorting Searching algorithms with simple arrays Sorting algorithms with simple arrays –Selection Sort –Insertion Sort –Bubble Sort –Quick.
CS 100Lecture 171 CS100A Lecture 17 n Previous Lecture –Programming concepts n Two-dimensional arrays –Java Constructs n Constructors for two-dimensional.
Introduction to Arrays. Objectives Distinguish between a simple variable and a subscripted variable. Input, output, and manipulate values stored in a.
1 Recursive algorithms Recursive solution: solve a smaller version of the problem and combine the smaller solutions. Example: to find the largest element.
Analysis & Design of Algorithms (CSCE 321)
N- Queens Solution with Genetic Algorithm By Mohammad A. Ismael.
Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 4: Introduction to C: Control Flow.
CompSci Problem Solving: Sudoku  Rules of the Game Sudoku is played with a 9 by 9 "board" consisting of nine 3 by 3 sub-boards. The symbols 1 -
CS 171: Intro to AI Discussion Week 2 Jan 15 th 2016.
1 ECE 102 Engineering Computation Chapter 3 Math Review 3: Cramer’s Rule Dr. Herbert G. Mayer, PSU Status 10/11/2015 For use at CCUT Fall 2015.
1 ECE 221 Electric Circuit Analysis I Chapter 6 Cramer’s Rule Herbert G. Mayer, PSU Status 11/14/2014 For use at Changchun University of Technology CCUT.
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
BINARY SEARCH CS16: Introduction to Data Structures & Algorithms Thursday February 12,
CSE 143 read: 12.5 Lecture 18: recursive backtracking.
1 Tirgul 11: Recursion & Backtracking. 2 Elements of a recursive solution (Reminder) A base case that is so simple we need no computation to solve it.
CSG3F3/ Desain dan Analisis Algoritma
Herbert G. Mayer, PSU CS status 7/29/2013
A CIS 5603 Course Project By: Qizhong Mao, Baiyi Tao, Arif Aziz
CSCI 104 Backtracking Search
Data Structures and Algorithms
Sit-In Lab 1 Ob-CHESS-ion
Stack Data Structure, Reverse Polish Notation, Homework 7
Some Basics for Problem Analysis and Solutions
Some Basics for Problem Analysis
Example Fill in the grid so that every row, column and box contains each of the numbers 1 to 9:
Analysis and design of algorithm
Jordi Cortadella Department of Computer Science
Announcements Assignment #4 is due tonight. Last lab program is going to be assigned this Wednesday. ◦ A backtracking problem.
Presentation transcript:

1 CS 410 Mastery in Programming Chapter 10 Hints for Simple Sudoku Herbert G. Mayer, PSU CS Status 7/29/2013

2 Syllabus Requirements Requirements Level 0 Level 0 Level 0 Algorithm Level 0 Algorithm Data Structure Data Structure Check Row, Columns Check Row, Columns Check Subsquares Check Subsquares L0 Sudoku L0 Sudoku Sample Sample References References

3 Requirements  The Sudoku game has a starting board S start  S start must be solvable, leading to a fully populated Sudoku board S end  The situation must be uniquely solvable; i.e. S start may not be open-ended so that multiple solutions S end will be possible; that would be interesting too, but is ambiguous  S end must be reachable without backtracking. I.e. it will not be necessary to discard an intermediate situation S inter since it fails to produce a solution, and then to continue where S inter has left off; backtracking is an option to pursue, but is not required for our assumed unique, deterministic situations  If a violating S start is encountered, the game cannot be solved with the programs proposed here; program aborts

4 Level 0 Implement a simple Sudoku solution that uses solely the requirements for all rows, all columns, and all subsquares. Sometimes this leads to a solution, which we name level 0 Sudoku Other solvable situation are of higher level Initially we solely focus on level 0 start situations S start

5 Level 0 Algorithm Precondition: Have an initial Sudoku board that is: Incomplete, i.e. not all fields are populated But has some fields filled in, but in a way to let the game be uniquely and deterministically solvable Without contradictions, i.e.: No row holds the same number more than once No column holds the same number more than once No sub-square holds the same number more than once Initial Steps: For each empty field, i.e. that has no defined number: Set all possible candidate numbers in some data structure The list of all candidate numbers for a 3*3 by 3*3 Sudoku is: 1, 2, 3, 4, 5, 6, 7, 8, 9

6 Level 0 Algorithm Step1: Set “changes” to 0 Step2: For every undefined sudoku[row][col] field, i.e. that has candidates in subset of { 1, 2, 3, 4, 5, 6, 7, 8, 9 } For any number n found on same “row”, remove n from the candidate list This is reminiscent of “Sieve if Eratosthenes” For any number n found on same “column”, remove n from the candidate list, if not already gone For any number n found in the same “sub-square”, remove n from the candidate list, if not already gone if the candidate list of sudoku[row][col] is down to 1, then changes++ Set the field sudoku[row][col] to the sole remaining number that is left Step 3: go to step 1 until “changes” is 0 i.e. we go though all fields sudoku[row][col] repeatedly, as long as we see changes Step 4: If all 3*3 by 3*3 fields are set: print success and output the whole board; else the initial field is not a level 0 solvable situation

7 Data Structure 1 #define BIG_N ( SMALL_N * SMALL_N ) #define EOL '\n' #define EMPTY 0 #define NO_CHAR ' ' #define FALSE 0 #define TRUE 1 #define P_BARprintf( "|" ) #define P_LINEprintf( "-" ) #define P_PLUSprintf( "+" ) #define P_EOL printf( "\n" ) #define P_TABprintf( "\t" ) #define P_BLANKprintf( " " )

8 Data Structure 2 // each element of an n*n X n*n sudoku board has the following structure: // "field" has any of the values 0..n*n, with 0 meaning that it is empty. // "option_count" states: how many of n*n numbers could be options. // "can_be[]" is array of n*n+1 bools. Says whether element "i" is option // if can_be[i] is false, number "i" cannot be option any longer. // if option_count ever reaches 1, then we "know" the field value // General data structure layout // // // | NAT | | NAT | | DC | | | |... | | | // // field option_count can_be[ BIG_N + 1 ] // int int bool

9 Data Structure 3 // specific layout for empty field // // // | 0 | | 9 | | DC | T | T | T |... | T | T | // // field option_count can_be[ BIG_N + 1 ] // // Specific layout for occupied field 3 // // // | 3 | | 0 | | DC | F | F | T |... | F | F | // // field option_count can_be[ BIG_N + 1 ] // typedef struct board_tp { unsignedfield;// 0 if empty, else one of 1..n*n unsignedoption_count; // initially, all n*n are options unsignedcan_be[ BIG_N + 1 ];// if false, number "i" impossible } struct_board_tp;

10 Data Structure 4 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////// //////////// //////////// G l o b a l O j e c t s //////////// //////////// //////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // this is the complete sudoku board, n*n by n*n = BIG_N * BIG_N fields struct_board_tp sudoku[ BIG_N ][ BIG_N ];

11 Check Rows, Columns // check all horizontal and vertical lines for empty spaces. // each empty space initially has BIG_N options // but for each existing value in that row or col, decrease the option. // if per chance the options end up just 1, then we can plug in a number. // return the number of fields changed from empty to a new value unsigned horiz_vert( row_col_anal_tp row_or_col ) { // horiz_vert unsigned changes = 0; unsigned options = 0; unsigned field = 0;// remember the next number to be excluded for ( int row = 0; row < BIG_N; row++ ) { for ( int col = 0; col < BIG_N; col++ ) { if ( SRC.field ) {// there is a number ASSERT( ( SRC.option_count == 0 ), "has # + option?" ); }else{ // field is EMPTY. Goal to count down options to 1 ASSERT( ( SRC.option_count ), "0 field must have opt" ); // go thru each field. For # found, exclude # from can_be[] for ( int i = 0; i < BIG_N; i++ ) { // continued on next page...

12 Check Rows, Columns //... continued from previous page // go thru each field. For # found, exclude # from can_be[] for ( int i = 0; i < BIG_N; i++ ) { if ( row_or_col == row_analysis ) { field = sudoku[ row ][ i ].field; }else{ // column analysis field = sudoku[ i ][ col ].field; } //end if if ( field ) { // we found a field SRC.can_be[ field ] = FALSE; } //end if SRC.option_count = options = count_fields( row, col ); if ( options == 1 ) { // plug in only 1 of BIG_N numbers // and set option_count to 0 field = find_1_field( row, col ); FILL(); } //end if } //end for i } //end if } //end if } //end for col } //end for col } //end for row return changes; } //end horiz_vert

13 Check Subsquare // check all horizontal and vertical lines for empty spaces. // each empty space initially has BIG_N options // But for each field value in subsquare, decrease options. // if per chance the options end up just 1, then we can plug in a number. // return the number of fields changed from empty to a new value unsigned subsquare( ) { // subsquare unsigned changes = 0; unsigned options = 0; unsigned field = 0;// remember the next number to be excluded for ( int row = 0; row < BIG_N; row++ ) { for ( int col = 0; col < BIG_N; col++ ) { if ( SRC.field ) {// there is a number ASSERT( ( SRC.option_count == 0 ), "has # + option?" ); }else{ // field is EMPTY. Goal to count down options to 1 ASSERT( ( SRC.option_count ), "subsquare must have opt" ); // analyze all fields in subsquare, exclude from can_be[] for ( int i = f( row ); i < ( f( row ) + SMALL_N ); i++ ) { ASSERT( ( i <= row+SMALL_N ), "wrong i_row in [][]" ); // continue on next page

14 Check Subsquare // continued from previous page... for ( int i = f( row ); i < ( f( row ) + SMALL_N ); i++ ) { ASSERT( ( i <= row+SMALL_N ), "wrong i_row in [][]" ); for ( int j = f( col ); j < ( f( col ) + SMALL_N ); j++ ) { ASSERT( j <= col+SMALL_N, "wrong j_col in [][]" ); field = sudoku[ i ][ j ].field; if ( field ) { // we found a non-zero field SRC.can_be[ field ] = FALSE; } //end if SRC.option_count = options = count_fields( row, col ); if ( options == 1 ) { // plug in only 1 of BIG_N numbers // and set option_count to 0 field = find_1_field( row, col ); FILL(); } //end if } //end for j } //end for i } //end if } //end if } //end for col } //end for col } //end for row return changes; } //end subsquare

15 L0 Sudoku // simplest sudoku strategy by eliminating options for a field // that would conflict with existing numbers in row, column, subsquare unsigned sudoku_level0() { //sudoku_level0 unsigned changes;// count fields filled in unsigned iterations = 0;// count times we go around unsigned errors = 0;// do final sanity check do { changes = 0; changes = horiz_vert( row_analysis ); changes += horiz_vert( col_analysis ); changes += subsquare(); ++iterations; } while ( changes ); try_single_option(); #ifdef DEBUG printf( "Iterated level0 %d times.\n", iterations ); errors = sanity_check(); #endif // DEBUG return changes; } //end sudoku_level0

16 Sample Input After setting initial fields sudoku board | 4 1| 5| 2 | 0 | 6 7| 3 | 8 5 | 1 | 5 3| 7 | 1 | | 8 | 2 4 3| | 3 | | 9| 1| 4 | 4| 8 | 2| | 3 | 6| 9 | 6 | | 2 | 5 8| 7 | 7 | 9 | 6| Statistics initially: Total # of fields: 81 Fields filled: 31 empty fields: 50

17 Sample Output Sudoku level 0 sudoku board | 4 9 1| 6 8 5| 2 7 3| 0 | 6 2 7| 3 9 1| 8 5 4| 1 | 8 5 3| 4 7 2| 6 1 9| | 1 8 9| 2 4 3| 7 6 5| 3 | 7 3 2| 5 6 9| 4 8 1| 4 | 5 6 4| 8 1 7| 3 9 2| | 3 4 8| 1 5 6| 9 2 7| 6 | 9 1 6| 7 2 4| 5 3 8| 7 | 2 7 5| 9 3 8| 1 4 6| Statistics Sudoku level 0 Total # of fields: 81 Fields filled: 81 empty fields: 0 Field was solvable with level 0

18 References  Here you may play:  The rules:  History: sudoku  C Solution: development/cpp/threads/48788