SlideShare a Scribd company logo
1 of 148
Groovy: Efficiency Oriented Programming
Lecture 8
Master Proteomics & Bioinformatics - University of Geneva
Alexandre Masselot - summer 2011
Contents

‣ Eclipse tips
‣ 8 queens on a chess board
‣ Genetic algorithm
‣ Abstract class (a little bit more about inheritance)
Eclipse tips

‣ Outline view in the right column
  - get a list of your field and method of the current class
Eclipse tips

‣ Outline view in the right column
  - get a list of your field and method of the current class

‣ Help > Key assist
  - get a list of all the possible shortcuts
Eclipse tips

‣ Outline view in the right column
  - get a list of your field and method of the current class

‣ Help > Key assist
  - get a list of all the possible shortcuts
8 queens puzzle




‣ Problem
  - put 8 queens on a chess board,
  - none is able to capture another (columns, rows and diagonal)
8 queens puzzle: history

‣ Chess player Max Bezzel proposed the problem in 1848
8 queens puzzle: history

‣ Chess player Max Bezzel proposed the problem in 1848
‣ Mathematicians (including Gauss) worked on the problem
  (and generalization to n-queens)
8 queens puzzle: history

‣ Chess player Max Bezzel proposed the problem in 1848
‣ Mathematicians (including Gauss) worked on the problem
  (and generalization to n-queens)
‣ Franz Nauck proposed the first solutions (1850)
8 queens puzzle: history

‣ Chess player Max Bezzel proposed the problem in 1848
‣ Mathematicians (including Gauss) worked on the problem
  (and generalization to n-queens)
‣ Franz Nauck proposed the first solutions (1850)
‣ Computer scientists joined the party: Edsger Dijkstra (1972)
  used the problem to illustrate depth-first backtracking
  algorithm
As usually, sexy problems diverge
n-queens, n×n chessboard with kings, knights...




                                                  6
8 queens on a 8×8 chessboard:
    how many solutions?




                                7
8
8
8 queens: some combinatorial considerations

‣ Number of possible positions of 8 queens on a 8x8 chess board (no
  constraints):
  - 64 choose 8=          = 4,426,165,368
8 queens: some combinatorial considerations

‣ Number of possible positions of 8 queens on a 8x8 chess board (no
  constraints):
  - 64 choose 8=          = 4,426,165,368
‣ Number of solution to the 8 queens puzzle:
  - 92, and reducing symmetries: 12 distinct
8 queens: some combinatorial considerations

‣ Number of possible positions of 8 queens on a 8x8 chess board (no
  constraints):
  - 64 choose 8=          = 4,426,165,368
‣ Number of solution to the 8 queens puzzle:
  - 92, and reducing symmetries: 12 distinct
‣ extend to any n queens, on a n x n board
8 queens: some combinatorial considerations

‣ Number of possible positions of 8 queens on a 8x8 chess board (no
  constraints):
  - 64 choose 8=          = 4,426,165,368
‣ Number of solution to the 8 queens puzzle:
  - 92, and reducing symmetries: 12 distinct
‣ extend to any n queens, on a n x n board


     n        1     2     3     4     5        6        7        8         9         10

 distinct     1     0     0     2     2        1        6       12        46         92

  unique      1     0     0     1     10       4       40       92       352        724
                                             http://en.wikipedia.org/wiki/Eight_queens_puzzle
Goals for today



        ‣ Write code to find solutions
Goals for today



        ‣ Write code to find solutions
        ‣ Brute force
Goals for today



        ‣ Write code to find solutions
        ‣ Brute force
        ‣ Genetic programming (evolving random
          approach)
Goals for today



        ‣ Write code to find solutions
        ‣ Brute force
        ‣ Genetic programming (evolving random
          approach)
        ‣ generalize the problem to kings
Goals for today



        ‣ Write code to find solutions
        ‣ Brute force
        ‣ Genetic programming (evolving random
          approach)
        ‣ generalize the problem to kings
        ‣ code in tp8-solutions @ dokeos
An algorithm for solutions
An algorithm for solutions
An algorithm for solutions
An algorithm for solutions
An algorithm for solutions
An algorithm for solutions
An algorithm for solutions
An algorithm for solutions
An algorithm for solutions
An algorithm for solutions
An algorithm for solutions
An algorithm for solutions
An algorithm for solutions
An algorithm for solutions
An algorithm for solutions
An algorithm for solutions
An algorithm for solutions
An algorithm for solutions
An algorithm for solutions
An algorithm for solutions
An algorithm for solutions
A solution finder code:


‣ A chessboard structure:
  - size & max number of pieces
  - add/remove pieces
  - count how many pieces are on the board
  - check if two pieces are conflicting
A solution finder code:


‣ A chessboard structure:
  - size & max number of pieces
  - add/remove pieces
  - count how many pieces are on the board
  - check if two pieces are conflicting

‣ A mechanism to explore one by one all solutions
  - mimic the brute force previous example
A code synopsis: board fields
A code synopsis: board fields

‣ ChessBoard.groovy/ChessBoardWithQueens.groovy

 /// number of rows and column for the board

 int size=8
A code synopsis: board fields

‣ ChessBoard.groovy/ChessBoardWithQueens.groovy

 /// number of rows and column for the board

 int size=8


 /// maximum number of pieces on the board

 int maxPieces=0
A code synopsis: board fields

‣ ChessBoard.groovy/ChessBoardWithQueens.groovy

 /// number of rows and column for the board

 int size=8


 /// maximum number of pieces on the board

 int maxPieces=0


 /** list of list of 2 integers
      each of them representing a piece on the board
      (between 0 and (size-1))
  */

 List piecesPositions = []
A code synopsis: board fields

‣ ChessBoard.groovy/ChessBoardWithQueens.groovy

 /// number of rows and column for the board

 int size=8


 /// maximum number of pieces on the board

 int maxPieces=0


 /** list of list of 2 integers
      each of them representing a piece on the board
      (between 0 and (size-1))
  */

 List piecesPositions = []
A code synopsis: board methods
A code synopsis: board methods


 /// how many pieces on the board

 int countPieces(){...}
A code synopsis: board methods


 /// how many pieces on the board

 int countPieces(){...}

 
/// synopsis: board << [0, 3]

 void leftShift(List<Integer> pos){...}
A code synopsis: board methods


 /// how many pieces on the board

 int countPieces(){...}

 
/// synopsis: board << [0, 3]

 void leftShift(List<Integer> pos){...}

  /// remove last introduced piece

 List<Integer> removeLastPiece(){...}
A code synopsis: board methods


 /// how many pieces on the board

 int countPieces(){...}

 
/// synopsis: board << [0, 3]

 void leftShift(List<Integer> pos){...}

  /// remove last introduced piece

 List<Integer> removeLastPiece(){...}

  /// are two pieces positions in conflict?

 boolean isPieceConflict(List<Integer> pA, List<Integer>   pB){...}
A code synopsis: a recursive algorithm
A code synopsis: a recursive algorithm

‣ Exploring means
  - placing a new piece at the next non-conflicting position
  - if all pieces are on the board, flag as a solution
  - exploring deeper
A code synopsis: a recursive algorithm

‣ Exploring means
  - placing a new piece at the next non-conflicting position
  - if all pieces are on the board, flag as a solution
  - exploring deeper

‣ The recursion means calling the same explore method deeper
  until and end is reached (e.g. all pieces are on the board)
A code synopsis: a recursive algorithm

‣ Implementing the displayed algorithm
 explore:
   if (all pieces are on the board){
     !! one solution !!
     return
   }
   pos ← next position after last piece
   while (pos is on the board){
     add a piece on the board at pos
     if (no conflict){
       explore()
     }
     remove last piece
     pos ← next position
   }
A code synopsis: a recursive algorithm

‣ Implementing the displayed algorithm
 explore:
   if (all pieces are on the board){
     !! one solution !!
     return
   }
   pos ← next position after last piece
   while (pos is on the board){
     add a piece on the board at pos
     if (no conflict){
       explore()
     }
     remove last piece
     pos ← next position
   }
A code synopsis: a recursive algorithm

‣ Implementing the displayed algorithm
 explore:
   if (all pieces are on the board){
     !! one solution !!
     return
   }
   pos ← next position after last piece
   while (pos is on the board){
     add a piece on the board at pos
     if (no conflict){
       explore()
     }
     remove last piece
     pos ← next position
   }
A code synopsis: a recursive algorithm

‣ Implementing the displayed algorithm
  Implementing the displayed algorithm
 explore:
   if (all pieces are on the board){
     !! one solution !!
     return
   }
   pos ← next position after last piece
   while (pos is on the board){
     add a piece on the board at pos
     if (no conflict){
       explore()
     }
     remove last piece
     pos ← next position
   }
A code synopsis: a recursive algorithm

‣ Implementing the displayed algorithm
  Implementing the displayed algorithm
 explore:
   if (all pieces are on the board){
     !! one solution !!
     return
   }
   pos ← next position after last piece
   while (pos is on the board){
     add a piece on the board at pos
     if (no conflict){
       explore()
     }
     remove last piece
     pos ← next position
   }
A codesynopsis: a a recursive algorithm
A code synopsis: recursive algorithm

‣ Implementing the displayed algorithm
  Implementing the displayed algorithm
 explore:
   if (all pieces are on the board){
     !! one solution !!
     return
   }
   pos ← next position after last piece
   while (pos is on the board){
     add a piece on the board at pos
     if (no conflict){
       explore()
     }
     remove last piece
     pos ← next position
   }
So we only need to code two functionalities
    a) increment position; b) explore




                                              17
A code synopsis: incrementing a position

‣ Incrementing a piece position means
A code synopsis: incrementing a position

‣ Incrementing a piece position means
  - Incrementing the column
A code synopsis: incrementing a position

‣ Incrementing a piece position means
  - Incrementing the column
  - If end of line is reached: increment row and goto first column
A code synopsis: incrementing a position

‣ Incrementing a piece position means
  - Incrementing the column
  - If end of line is reached: increment row and goto first column
  - Return null is end of the board is reached
A code synopsis: incrementing a position

‣ Incrementing a piece position means
  - Incrementing the column
  - If end of line is reached: increment row and goto first column
  - Return null is end of the board is reached
  - Return [0,0] if starting position is null
A code synopsis: incrementing a position
A code synopsis: incrementing a position

‣ Groovy code:
A code synopsis: incrementing a position

‣ Groovy code:
 /*
    a position is a List of 2 integer in [0, boardSize[
A code synopsis: incrementing a position

‣ Groovy code:
 /*
    a position is a List of 2 integer in [0, boardSize[
    increment second coordinates if possible
A code synopsis: incrementing a position

‣ Groovy code:
 /*
    a position is a List of 2 integer in [0, boardSize[
    increment second coordinates if possible
    then the first (and second is set to 0)
A code synopsis: incrementing a position

‣ Groovy code:
 /*
    a position is a List of 2 integer in [0, boardSize[
    increment second coordinates if possible
    then the first (and second is set to 0)
    returns null if end of board is reached
A code synopsis: incrementing a position

‣ Groovy code:
 /*
    a position is a List of 2 integer in [0, boardSize[
    increment second coordinates if possible
    then the first (and second is set to 0)
    returns null if end of board is reached
    returns [0,0] if a null position is to be incremented
 */
A code synopsis: incrementing a position

‣ Groovy code:
 /*
    a position is a List of 2 integer in [0, boardSize[
    increment second coordinates if possible
    then the first (and second is set to 0)
    returns null if end of board is reached
    returns [0,0] if a null position is to be incremented
 */
 List<Integer> incrementPiecePosition(int boardSize,
                                      List<Integer> p){




 
 return [p[0], p[1]+1]
 }
A code synopsis: incrementing a position

‣ Groovy code:
 /*
    a position is a List of 2 integer in [0, boardSize[
    increment second coordinates if possible
    then the first (and second is set to 0)
    returns null if end of board is reached
    returns [0,0] if a null position is to be incremented
 */
 List<Integer> incrementPiecePosition(int boardSize,
                                      List<Integer> p){



 
 if(p[1] == (boardSize - 1) ){


 
 
 return [p[0]+1, 0]
 
 }
 
 return [p[0], p[1]+1]
 }
A code synopsis: incrementing a position

‣ Groovy code:
 /*
     a position is a List of 2 integer in [0, boardSize[
     increment second coordinates if possible
     then the first (and second is set to 0)
     returns null if end of board is reached
     returns [0,0] if a null position is to be incremented
 */
 List<Integer> incrementPiecePosition(int boardSize,
                                      List<Integer> p){



 
    if(p[1] == (boardSize - 1) ){
 
    
 if(p[0] == (boardSize -1) )
 
    
 
 return null
 
    
 return [p[0]+1, 0]
 
    }
 
    return [p[0], p[1]+1]
 }
A code synopsis: incrementing a position

‣ Groovy code:
 /*
     a position is a List of 2 integer in [0, boardSize[
     increment second coordinates if possible
     then the first (and second is set to 0)
     returns null if end of board is reached
     returns [0,0] if a null position is to be incremented
 */
 List<Integer> incrementPiecePosition(int boardSize,
                                      List<Integer> p){
 
 if(p==null)
 
 
 return [0,0]
 
    if(p[1] == (boardSize - 1) ){
 
    
 if(p[0] == (boardSize -1) )
 
    
 
 return null
 
    
 return [p[0]+1, 0]
 
    }
 
    return [p[0], p[1]+1]
 }
8 queens: a recursive algorithm                                   (cont’d)
def explore(board){






 //walk through all possible position until it is not possible anymore to
increment

 while(p = incrementPiecePosition(board.size, p)){

 
    //put the current piece on the board to give it a try

 
    board<<p

 





   
   //remove the piece before training another position

   
   board.removeLastPiece()

   }
}
8 queens: a recursive algorithm                                   (cont’d)
def explore(board){






 //walk through all possible position until it is not possible anymore to
increment

 while(p = incrementPiecePosition(board.size, p)){

 
    //put the current piece on the board to give it a try

 
    board<<p

 
    if(!board.countConflicts()){
         // if it can be added without conflict try exploration deeper
         // (with one nore piece)
       
 explore(board)
       }

 
    //remove the piece before training another position

 
    board.removeLastPiece()

 }
}
8 queens: a recursive algorithm                                   (cont’d)
def explore(board){




   //let's take the last piece as starting point or null if the board is empty
   def p=board.countPieces()?board.piecesPositions[-1]:null

 //walk through all possible position until it is not possible anymore to
increment

 while(p = incrementPiecePosition(board.size, p)){

 
    //put the current piece on the board to give it a try

 
    board<<p

 
    if(!board.countConflicts()){
         // if it can be added without conflict try exploration deeper
         // (with one nore piece)
       
 explore(board)
       }

 
    //remove the piece before training another position

 
    board.removeLastPiece()

 }
}
8 queens: a recursive algorithm                                    (cont’d)
def explore(board){

   if((! board.countConflicts()) && (board.countPieces() == board.maxPieces)){
    
 println "A working setup :n$board"
    
 return
    }
   //let's take the last piece as starting point or null if the board is empty
   def p=board.countPieces()?board.piecesPositions[-1]:null

 //walk through all possible position until it is not possible anymore to
increment

 while(p = incrementPiecePosition(board.size, p)){

 
    //put the current piece on the board to give it a try

 
    board<<p

 
    if(!board.countConflicts()){
         // if it can be added without conflict try exploration deeper
         // (with one nore piece)
       
 explore(board)
       }

 
    //remove the piece before training another position

 
    board.removeLastPiece()

 }
}
A recursive function calls itself




                                    21
8 queens: a recursive algorithm                                   (cont’d)

‣ Initialization contains:
   - defining a empty board with correct size
   - launching the first call to the recursive explore function
ChessBoard board=[size:8, maxPieces:8]

explore(board)
8 queens: a recursive algorithm                                   (cont’d)

‣ Initialization contains:
   - defining a empty board with correct size
   - launching the first call to the recursive explore function
ChessBoard board=[size:8, maxPieces:8]

explore(board)


‣ See scripts/recursiveChessExploration.groovy
8 queens: a recursive algorithm                                   (cont’d)

‣ Initialization contains:
   - defining a empty board with correct size
   - launching the first call to the recursive explore function
ChessBoard board=[size:8, maxPieces:8]

explore(board)


‣ See scripts/recursiveChessExploration.groovy
8 queens: a recursive algorithm                                   (cont’d)

‣ Initialization contains:
   - defining a empty board with correct size
   - launching the first call to the recursive explore function
ChessBoard board=[size:8, maxPieces:8]

explore(board)


‣ See scripts/recursiveChessExploration.groovy
8 queens: a recursive algorithm                                   (cont’d)

‣ Initialization contains:
   - defining a empty board with correct size
   - launching the first call to the recursive explore function
ChessBoard board=[size:8, maxPieces:8]

explore(board)


‣ See scripts/recursiveChessExploration.groovy
Recursion: the limits
Recursion: the limits

‣ Recursive method is concise
Recursion: the limits

‣ Recursive method is concise
‣ But it requires
  - time (method call)
  - memory (deep tree!)
Recursion: the limits

‣ Recursive method is concise
‣ But it requires
  - time (method call)
  - memory (deep tree!)

‣ In practice, faster methods exist
  - walking through solution staying at the same stack level
Recursion: the limits

‣ Recursive method is concise
‣ But it requires
  - time (method call)
  - memory (deep tree!)

‣ In practice, faster methods exist
  - walking through solution staying at the same stack level

‣ Dedicated solutions if often better
  - In the case of the queens problems, knowing the pieces move can greatly help to
    write a dedicated algorithm (one per row, one per column...)
Creationism or Darwinism?




                            24
Genetic Algorithm: an introduction

‣ A problem ⇒ a fitness function
Genetic Algorithm: an introduction

‣ A problem ⇒ a fitness function
‣ A candidate solution ⇒ a score given by the fitness function
Genetic Algorithm: an introduction

‣ A problem ⇒ a fitness function
‣ A candidate solution ⇒ a score given by the fitness function
‣ The higher the fit, the fittest the candidate
Genetic Algorithm: an introduction                    (cont’d)

‣ Searching for a solution simulating a natural selection
Genetic Algorithm: an introduction                    (cont’d)

‣ Searching for a solution simulating a natural selection
‣ One candidate solution ⇔ one gene
Genetic Algorithm: an introduction                    (cont’d)

‣ Searching for a solution simulating a natural selection
‣ One candidate solution ⇔ one gene
‣ population ⇔ set of genes
Genetic Algorithm: an introduction                    (cont’d)

‣ Searching for a solution simulating a natural selection
‣ One candidate solution ⇔ one gene
‣ population ⇔ set of genes
‣ Start : initialize a random population
Genetic Algorithm: an introduction                    (cont’d)

‣ Searching for a solution simulating a natural selection
‣ One candidate solution ⇔ one gene
‣ population ⇔ set of genes
‣ Start : initialize a random population
‣ One generation
  - fittest genes are selected
  - cross-over between those genes
  - random mutation
GA for the 8 queens problem
GA for the 8 queens problem

‣ Gene ⇔ 8 positions
GA for the 8 queens problem

‣ Gene ⇔ 8 positions
‣ Fitness ⇔ -board.countConflicts()
GA for the 8 queens problem

‣ Gene ⇔ 8 positions
‣ Fitness ⇔ -board.countConflicts()
‣ Cross-over ⇔ mixing pieces of two boards
GA for the 8 queens problem

‣ Gene ⇔ 8 positions
‣ Fitness ⇔ -board.countConflicts()
‣ Cross-over ⇔ mixing pieces of two boards
‣ Mutation ⇔ moving randomly one piece
A GA in practice (Evolution.groovy)
class Evolution {

 int nbGenes=200

 double mutationRate = 0.1

 int nbKeepBest = 50

 int nbAddRandom = 10


 Random randomGenerator = new Random()


 def geneFactory

 List genePool

...
}
A GA in practice (Evolution.groovy)

   def   nextGeneration(){

   
      //select a subset of the best gene + mutate them according to a rate

   
      List reproPool=selectBest().toList().unique{it}

   

   
     //keep the repro pool in the best

   
     genePool=reproPool



   





   





   }
A GA in practice (Evolution.groovy)

   def   nextGeneration(){

   
      //select a subset of the best gene + mutate them according to a rate

   
      List reproPool=selectBest().toList().unique{it}

   

   
     //keep the repro pool in the best

   
     genePool=reproPool



   





   

   
     //finally mutate genes with the given rate

   
     genePool.each {gene ->

   
     
    if(randomGenerator.nextDouble() < mutationRate)

   
     
    
    gene.mutate()

   
     }

   }
A GA in practice (Evolution.groovy)

   def   nextGeneration(){

   
      //select a subset of the best gene + mutate them according to a rate

   
      List reproPool=selectBest().toList().unique{it}

   

   
     //keep the repro pool in the best

   
     genePool=reproPool



   

   
     //from the 'fittest' reproPool, rebuild the total population by crossover

   
     (1..<((nbGenes-genePool.size())/2) ).each{

   
     
    def geneA = reproPool[randomGenerator.nextInt(nbKeepBest)].clone()

   
     
    def geneB = reproPool[randomGenerator.nextInt(nbKeepBest)].clone()

   
     
    geneA.crossOver(geneB)

   
     
    genePool << geneA

   
     
    genePool << geneB

   
     }

   

   
     //finally mutate genes with the given rate

   
     genePool.each {gene ->

   
     
    if(randomGenerator.nextDouble() < mutationRate)

   
     
    
    gene.mutate()

   
     }

   }
A GA in practice (Evolution.groovy)

   def   nextGeneration(){

   
      //select a subset of the best gene + mutate them according to a rate

   
      List reproPool=selectBest().toList().unique{it}

   

   
     //keep the repro pool in the best

   
     genePool=reproPool

   
     //add a few random to the pool

   
     buildRandom(nbAddRandom).each{ genePool << it }

   

   
     //from the 'fittest' reproPool, rebuild the total population by crossover

   
     (1..<((nbGenes-genePool.size())/2) ).each{

   
     
    def geneA = reproPool[randomGenerator.nextInt(nbKeepBest)].clone()

   
     
    def geneB = reproPool[randomGenerator.nextInt(nbKeepBest)].clone()

   
     
    geneA.crossOver(geneB)

   
     
    genePool << geneA

   
     
    genePool << geneB

   
     }

   

   
     //finally mutate genes with the given rate

   
     genePool.each {gene ->

   
     
    if(randomGenerator.nextDouble() < mutationRate)

   
     
    
    gene.mutate()

   
     }

   }
Evolution.groovy = problem agnostic




                                      30
31
GA: more evolution
GA: more evolution

‣ Mutation rate can be time dependent (decrease over time...)
GA: more evolution

‣ Mutation rate can be time dependent (decrease over time...)
‣ Different population pools (different parameters), long term
  cross-over
GA: more evolution

‣ Mutation rate can be time dependent (decrease over time...)
‣ Different population pools (different parameters), long term
  cross-over
‣ Regular introduction of new random genes
Genetic algorithm: a solution for everything?
Genetic algorithm: a solution for everything?

‣ GA looks like a magic solution to any optimization process
Genetic algorithm: a solution for everything?

‣ GA looks like a magic solution to any optimization process
‣ In practice, hard to tune evolution strategy & parameters
Genetic algorithm: a solution for everything?

‣ GA looks like a magic solution to any optimization process
‣ In practice, hard to tune evolution strategy & parameters
‣ For a given problem: a dedicated solution always better (when
  possible)
Genetic algorithm: a solution for everything?

‣ GA looks like a magic solution to any optimization process
‣ In practice, hard to tune evolution strategy & parameters
‣ For a given problem: a dedicated solution always better (when
  possible)
‣ For the queens problems, the recursive method is much faster
Genetic algorithm: a solution for everything?

‣ GA looks like a magic solution to any optimization process
‣ In practice, hard to tune evolution strategy & parameters
‣ For a given problem: a dedicated solution always better (when
  possible)
‣ For the queens problems, the recursive method is much faster
‣ For 32 knights: GA is much faster (not all solutions!)
32 Knights on the board




                          34
Board with knights
Board with knights

‣ ChessBoard.groovy:
boolean isPieceConflict(List<Integer> pA,
                        List<Integer> pB){

   
   //same row or same column

   
   if((pA[0] == pB [0]) || (pA[1] == pB[1]))

   
   
 return true

   

   
   //first diagonal

   
   if((pA[0] - pA [1]) == (pB[0] - pB[1]))

   
   
 return true

   

   
   //second diagonal

   
   if((pA[0] + pA [1]) == (pB[0] + pB[1]))

   
   
 return true

   

   
   return false

 }
Shall we redefine all the previous methods
   from the ChessBoard with queens?
                  DRY!




                                             36
A generic ChessBoard : abstract class
A generic ChessBoard : abstract class




‣ ChessBoard.groovy:
abstract class ChessBoard{
  ... all other methods/fields are the same ...

    abstract boolean isPieceConflict(List<Integer> pA,
                          List<Integer> pB);

}
Queen specialization
Queen specialization
Queen specialization


‣ Then a implementation class
 class ChessBoardWithQueens extends ChessBoard{
   //only method
   boolean isPieceConflict(List<Integer> pA,
                         List<Integer> pB){
 
 
 //same row or same column
 
 
 if((pA[0] == pB [0]) || (pA[1] == pB[1]))
 
 
 
 return true
 
 
 //first diagonal
 
 
 if((pA[0] - pA [1]) == (pB[0] - pB[1]))
 
 
 
 return true
 
 
 //second diagonal
 
 
 if((pA[0] + pA [1]) == (pB[0] + pB[1]))
 
 
 
 return true
 
 
 return false
 
 }
Knight specialization
Knight specialization

‣ ChessBoardWithKnights.groovy:
class ChessBoardWithKnights extends ChessBoard{
  //only method
  boolean isPieceConflict(List<Integer> pA,
                         List<Integer> pB){

 
 if( (Math.abs(pA[0]-pB[0])==2) &&
         (Math.abs(pA[1]-pB[1])==1) )

 
 
 return true


 
   if( (Math.abs(pA[1]-pB[1])==2) &&
          (Math.abs(pA[0]-pB[0])==1) )

 
   
 return true


 
   return false

 }
And from the exploration script
And from the exploration script

‣ In main script:
 //ChessBoardWithQueens board=[size:8, maxPieces:8]
 ChessBoardWithKnights board=[size:8, maxPieces:32]

 explore(board)
And from the exploration script

‣ In main script:
 //ChessBoardWithQueens board=[size:8, maxPieces:8]
 ChessBoardWithKnights board=[size:8, maxPieces:32]

 explore(board)
‣ Nothing more...
Do not forget unit tests!




                            41
abstract class testing

‣ Not possible to instantiate new ChessBoard()
abstract class testing

‣ Not possible to instantiate new ChessBoard()

‣ Create a fake ChessBoard class for test
 class ChessBoardTest extends GroovyTestCase {
 
 class ChessBoardDummy extends ChessBoard{
 
 
 boolean isPieceConflict(List<Integer> pA,
                              List<Integer> pB){
 
 
 
 return ( (pA[0]==pB[0]) && (pA[1]==pB[1]) )
 
 
 }
 
 }
 ...
 }
abstract class testing

‣ Not possible to instantiate new ChessBoard()

‣ Create a fake ChessBoard class for test
    class ChessBoardTest extends GroovyTestCase {
    
 class ChessBoardDummy extends ChessBoard{
    
 
 boolean isPieceConflict(List<Integer> pA,
                                 List<Integer> pB){
    
 
 
 return ( (pA[0]==pB[0]) && (pA[1]==pB[1]) )
    
 
 }
    
 }
    ...
    }
‣    Then all tests are with instances
    ChessBoardDummy board=[size:4, maxPieces:3]
abstract class testing   (cont’d)
abstract class testing                                 (cont’d)

‣ ChessBoardWithQueens only test for pieces conflict
 class ChessBoardWithQueensTest extends GroovyTestCase {
 
 
 public void testPieceConflict(){
 
 
 ChessBoardWithQueens board=[size:4, maxPieces:3]
 
 
 //same spot
 
 
 assert board.isPieceConflict([0, 0], [0, 0])
 
 
 //same row
 
 
 assert board.isPieceConflict([0, 2], [0, 0])
 
 
 //same column
 
 
 assert board.isPieceConflict([2, 0], [0, 0])
 
 
 
 
 ...
   }

More Related Content

Similar to groovy & grails - lecture 8

Greedy algorithms -Making change-Knapsack-Prim's-Kruskal's
Greedy algorithms -Making change-Knapsack-Prim's-Kruskal'sGreedy algorithms -Making change-Knapsack-Prim's-Kruskal's
Greedy algorithms -Making change-Knapsack-Prim's-Kruskal'sJay Patel
 
Segmentation Faults, Page Faults, Processes, Threads, and Tasks
Segmentation Faults, Page Faults, Processes, Threads, and TasksSegmentation Faults, Page Faults, Processes, Threads, and Tasks
Segmentation Faults, Page Faults, Processes, Threads, and TasksDavid Evans
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that LetterKevlin Henney
 
BackTracking Algorithm: Technique and Examples
BackTracking Algorithm: Technique and ExamplesBackTracking Algorithm: Technique and Examples
BackTracking Algorithm: Technique and ExamplesFahim Ferdous
 
graph2tab, a library to convert experimental workflow graphs into tabular for...
graph2tab, a library to convert experimental workflow graphs into tabular for...graph2tab, a library to convert experimental workflow graphs into tabular for...
graph2tab, a library to convert experimental workflow graphs into tabular for...Rothamsted Research, UK
 
Rust concurrency tutorial 2015 12-02
Rust concurrency tutorial 2015 12-02Rust concurrency tutorial 2015 12-02
Rust concurrency tutorial 2015 12-02nikomatsakis
 
The Towers of Hanoi puzzle has three posts and some number n of disk.pdf
The Towers of Hanoi puzzle has three posts and some number n of disk.pdfThe Towers of Hanoi puzzle has three posts and some number n of disk.pdf
The Towers of Hanoi puzzle has three posts and some number n of disk.pdffcsondhiindia
 
Ee693 sept2014quiz1
Ee693 sept2014quiz1Ee693 sept2014quiz1
Ee693 sept2014quiz1Gopi Saiteja
 
Unit 1-logic
Unit 1-logicUnit 1-logic
Unit 1-logicraksharao
 
Bidirectional graph search techniques for finding shortest path in image base...
Bidirectional graph search techniques for finding shortest path in image base...Bidirectional graph search techniques for finding shortest path in image base...
Bidirectional graph search techniques for finding shortest path in image base...Navin Kumar
 
CS345-Algorithms-II-Lecture-1-CS345-2016.pdf
CS345-Algorithms-II-Lecture-1-CS345-2016.pdfCS345-Algorithms-II-Lecture-1-CS345-2016.pdf
CS345-Algorithms-II-Lecture-1-CS345-2016.pdfOpenWorld6
 
Hashing In Data Structure Download PPT i
Hashing In Data Structure Download PPT iHashing In Data Structure Download PPT i
Hashing In Data Structure Download PPT icajiwol341
 
Branch and bound
Branch and boundBranch and bound
Branch and boundAcad
 
RecSplit Minimal Perfect Hashing
RecSplit Minimal Perfect HashingRecSplit Minimal Perfect Hashing
RecSplit Minimal Perfect HashingThomas Mueller
 
5.5 back track
5.5 back track5.5 back track
5.5 back trackKrish_ver2
 

Similar to groovy & grails - lecture 8 (20)

Greedy algorithms -Making change-Knapsack-Prim's-Kruskal's
Greedy algorithms -Making change-Knapsack-Prim's-Kruskal'sGreedy algorithms -Making change-Knapsack-Prim's-Kruskal's
Greedy algorithms -Making change-Knapsack-Prim's-Kruskal's
 
Segmentation Faults, Page Faults, Processes, Threads, and Tasks
Segmentation Faults, Page Faults, Processes, Threads, and TasksSegmentation Faults, Page Faults, Processes, Threads, and Tasks
Segmentation Faults, Page Faults, Processes, Threads, and Tasks
 
And or graph problem reduction using predicate logic
And or graph problem reduction using predicate logicAnd or graph problem reduction using predicate logic
And or graph problem reduction using predicate logic
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that Letter
 
BackTracking Algorithm: Technique and Examples
BackTracking Algorithm: Technique and ExamplesBackTracking Algorithm: Technique and Examples
BackTracking Algorithm: Technique and Examples
 
Back tracking
Back trackingBack tracking
Back tracking
 
graph2tab, a library to convert experimental workflow graphs into tabular for...
graph2tab, a library to convert experimental workflow graphs into tabular for...graph2tab, a library to convert experimental workflow graphs into tabular for...
graph2tab, a library to convert experimental workflow graphs into tabular for...
 
Shoot-for-A-Star
Shoot-for-A-StarShoot-for-A-Star
Shoot-for-A-Star
 
Rust concurrency tutorial 2015 12-02
Rust concurrency tutorial 2015 12-02Rust concurrency tutorial 2015 12-02
Rust concurrency tutorial 2015 12-02
 
The Towers of Hanoi puzzle has three posts and some number n of disk.pdf
The Towers of Hanoi puzzle has three posts and some number n of disk.pdfThe Towers of Hanoi puzzle has three posts and some number n of disk.pdf
The Towers of Hanoi puzzle has three posts and some number n of disk.pdf
 
Ee693 sept2014quiz1
Ee693 sept2014quiz1Ee693 sept2014quiz1
Ee693 sept2014quiz1
 
Programming Hp33s talk v3
Programming Hp33s talk v3Programming Hp33s talk v3
Programming Hp33s talk v3
 
Unit 1-logic
Unit 1-logicUnit 1-logic
Unit 1-logic
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
Bidirectional graph search techniques for finding shortest path in image base...
Bidirectional graph search techniques for finding shortest path in image base...Bidirectional graph search techniques for finding shortest path in image base...
Bidirectional graph search techniques for finding shortest path in image base...
 
CS345-Algorithms-II-Lecture-1-CS345-2016.pdf
CS345-Algorithms-II-Lecture-1-CS345-2016.pdfCS345-Algorithms-II-Lecture-1-CS345-2016.pdf
CS345-Algorithms-II-Lecture-1-CS345-2016.pdf
 
Hashing In Data Structure Download PPT i
Hashing In Data Structure Download PPT iHashing In Data Structure Download PPT i
Hashing In Data Structure Download PPT i
 
Branch and bound
Branch and boundBranch and bound
Branch and bound
 
RecSplit Minimal Perfect Hashing
RecSplit Minimal Perfect HashingRecSplit Minimal Perfect Hashing
RecSplit Minimal Perfect Hashing
 
5.5 back track
5.5 back track5.5 back track
5.5 back track
 

More from Alexandre Masselot

Offshoring software development in Switzerland: You can do it
Offshoring software development in Switzerland: You can do itOffshoring software development in Switzerland: You can do it
Offshoring software development in Switzerland: You can do itAlexandre Masselot
 
Dev Wednesday - Swiss Transport in Real Time: Tribulations in the Big Data Stack
Dev Wednesday - Swiss Transport in Real Time: Tribulations in the Big Data StackDev Wednesday - Swiss Transport in Real Time: Tribulations in the Big Data Stack
Dev Wednesday - Swiss Transport in Real Time: Tribulations in the Big Data StackAlexandre Masselot
 
Swiss Transport in Real Time: Tribulations in the Big Data Stack
Swiss Transport in Real Time: Tribulations in the Big Data StackSwiss Transport in Real Time: Tribulations in the Big Data Stack
Swiss Transport in Real Time: Tribulations in the Big Data StackAlexandre Masselot
 

More from Alexandre Masselot (10)

Offshoring software development in Switzerland: You can do it
Offshoring software development in Switzerland: You can do itOffshoring software development in Switzerland: You can do it
Offshoring software development in Switzerland: You can do it
 
Dev Wednesday - Swiss Transport in Real Time: Tribulations in the Big Data Stack
Dev Wednesday - Swiss Transport in Real Time: Tribulations in the Big Data StackDev Wednesday - Swiss Transport in Real Time: Tribulations in the Big Data Stack
Dev Wednesday - Swiss Transport in Real Time: Tribulations in the Big Data Stack
 
Swiss Transport in Real Time: Tribulations in the Big Data Stack
Swiss Transport in Real Time: Tribulations in the Big Data StackSwiss Transport in Real Time: Tribulations in the Big Data Stack
Swiss Transport in Real Time: Tribulations in the Big Data Stack
 
groovy & grails - lecture 1
groovy & grails - lecture 1groovy & grails - lecture 1
groovy & grails - lecture 1
 
groovy & grails - lecture 11
groovy & grails - lecture 11groovy & grails - lecture 11
groovy & grails - lecture 11
 
groovy & grails - lecture 12
groovy & grails - lecture 12groovy & grails - lecture 12
groovy & grails - lecture 12
 
groovy & grails - lecture 13
groovy & grails - lecture 13groovy & grails - lecture 13
groovy & grails - lecture 13
 
groovy & grails - lecture 7
groovy & grails - lecture 7groovy & grails - lecture 7
groovy & grails - lecture 7
 
groovy & grails - lecture 6
groovy & grails - lecture 6groovy & grails - lecture 6
groovy & grails - lecture 6
 
groovy & grails - lecture 5
groovy & grails - lecture 5groovy & grails - lecture 5
groovy & grails - lecture 5
 

Recently uploaded

Call US '' 8377087607'' !! Call Girls In Model Town Metro (Delhi NCR)
Call US '' 8377087607'' !! Call Girls In Model Town Metro (Delhi NCR)Call US '' 8377087607'' !! Call Girls In Model Town Metro (Delhi NCR)
Call US '' 8377087607'' !! Call Girls In Model Town Metro (Delhi NCR)dollysharma2066
 
NO1 WorldWide Amil baba in pakistan Amil Baba in Karachi Black Magic Islamaba...
NO1 WorldWide Amil baba in pakistan Amil Baba in Karachi Black Magic Islamaba...NO1 WorldWide Amil baba in pakistan Amil Baba in Karachi Black Magic Islamaba...
NO1 WorldWide Amil baba in pakistan Amil Baba in Karachi Black Magic Islamaba...Amil baba
 
Call Girls in Najafgarh Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Najafgarh Delhi 💯Call Us 🔝8264348440🔝Call Girls in Najafgarh Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Najafgarh Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Fun Call Girls In Goa 7028418221 Escort Service In Morjim Beach Call Girl
Fun Call Girls In Goa 7028418221 Escort Service In Morjim Beach Call GirlFun Call Girls In Goa 7028418221 Escort Service In Morjim Beach Call Girl
Fun Call Girls In Goa 7028418221 Escort Service In Morjim Beach Call GirlApsara Of India
 
Fun Call Girls In Goa 7028418221 Call Girl Service In Panaji Escorts
Fun Call Girls In Goa 7028418221 Call Girl Service In Panaji EscortsFun Call Girls In Goa 7028418221 Call Girl Service In Panaji Escorts
Fun Call Girls In Goa 7028418221 Call Girl Service In Panaji EscortsApsara Of India
 
Call Girls in Faridabad 9000000000 Faridabad Escorts Service
Call Girls in Faridabad 9000000000 Faridabad Escorts ServiceCall Girls in Faridabad 9000000000 Faridabad Escorts Service
Call Girls in Faridabad 9000000000 Faridabad Escorts ServiceTina Ji
 
VIP Call Girls In Goa 7028418221 Call Girls In Baga Beach Escorts Service
VIP Call Girls In Goa 7028418221 Call Girls In Baga Beach Escorts ServiceVIP Call Girls In Goa 7028418221 Call Girls In Baga Beach Escorts Service
VIP Call Girls In Goa 7028418221 Call Girls In Baga Beach Escorts ServiceApsara Of India
 
Real NO1 Amil baba in Faisalabad Kala jadu in faisalabad Aamil baba Faisalaba...
Real NO1 Amil baba in Faisalabad Kala jadu in faisalabad Aamil baba Faisalaba...Real NO1 Amil baba in Faisalabad Kala jadu in faisalabad Aamil baba Faisalaba...
Real NO1 Amil baba in Faisalabad Kala jadu in faisalabad Aamil baba Faisalaba...Amil Baba Company
 
1681275559_haunting-adeline and hunting.pdf
1681275559_haunting-adeline and hunting.pdf1681275559_haunting-adeline and hunting.pdf
1681275559_haunting-adeline and hunting.pdfTanjirokamado769606
 
High Profile Call Girls Sodepur - 8250192130 Escorts Service with Real Photos...
High Profile Call Girls Sodepur - 8250192130 Escorts Service with Real Photos...High Profile Call Girls Sodepur - 8250192130 Escorts Service with Real Photos...
High Profile Call Girls Sodepur - 8250192130 Escorts Service with Real Photos...Riya Pathan
 
Amil Baba in Pakistan Kala jadu Expert Amil baba Black magic Specialist in Is...
Amil Baba in Pakistan Kala jadu Expert Amil baba Black magic Specialist in Is...Amil Baba in Pakistan Kala jadu Expert Amil baba Black magic Specialist in Is...
Amil Baba in Pakistan Kala jadu Expert Amil baba Black magic Specialist in Is...Amil Baba Company
 
Call Girl Contact Number Andheri WhatsApp:+91-9833363713
Call Girl Contact Number Andheri WhatsApp:+91-9833363713Call Girl Contact Number Andheri WhatsApp:+91-9833363713
Call Girl Contact Number Andheri WhatsApp:+91-9833363713Sonam Pathan
 
QUIZ BOLLYWOOD ( weekly quiz ) - SJU quizzers
QUIZ BOLLYWOOD ( weekly quiz ) - SJU quizzersQUIZ BOLLYWOOD ( weekly quiz ) - SJU quizzers
QUIZ BOLLYWOOD ( weekly quiz ) - SJU quizzersSJU Quizzers
 
Kolkata Call Girl Bagbazar 👉 8250192130 ❣️💯 Available With Room 24×7
Kolkata Call Girl Bagbazar 👉 8250192130 ❣️💯 Available With Room 24×7Kolkata Call Girl Bagbazar 👉 8250192130 ❣️💯 Available With Room 24×7
Kolkata Call Girl Bagbazar 👉 8250192130 ❣️💯 Available With Room 24×7Riya Pathan
 
Call Girls In Karnal O8860008073 Sector 6 7 8 9 Karnal Escorts
Call Girls In Karnal O8860008073 Sector 6 7 8 9 Karnal EscortsCall Girls In Karnal O8860008073 Sector 6 7 8 9 Karnal Escorts
Call Girls In Karnal O8860008073 Sector 6 7 8 9 Karnal EscortsApsara Of India
 
Call Girl Price Andheri WhatsApp:+91-9833363713
Call Girl Price Andheri WhatsApp:+91-9833363713Call Girl Price Andheri WhatsApp:+91-9833363713
Call Girl Price Andheri WhatsApp:+91-9833363713Sonam Pathan
 
Cash Payment Contact:- 7028418221 Goa Call Girls Service North Goa Escorts
Cash Payment Contact:- 7028418221 Goa Call Girls Service North Goa EscortsCash Payment Contact:- 7028418221 Goa Call Girls Service North Goa Escorts
Cash Payment Contact:- 7028418221 Goa Call Girls Service North Goa EscortsApsara Of India
 
Call Girls Near Delhi Pride Hotel New Delhi 9873777170
Call Girls Near Delhi Pride Hotel New Delhi 9873777170Call Girls Near Delhi Pride Hotel New Delhi 9873777170
Call Girls Near Delhi Pride Hotel New Delhi 9873777170Sonam Pathan
 
Call Girls Somajiguda Sarani 7001305949 all area service COD available Any Time
Call Girls Somajiguda Sarani 7001305949 all area service COD available Any TimeCall Girls Somajiguda Sarani 7001305949 all area service COD available Any Time
Call Girls Somajiguda Sarani 7001305949 all area service COD available Any Timedelhimodelshub1
 
Vip Udaipur Call Girls 9602870969 Dabok Airport Udaipur Escorts Service
Vip Udaipur Call Girls 9602870969 Dabok Airport Udaipur Escorts ServiceVip Udaipur Call Girls 9602870969 Dabok Airport Udaipur Escorts Service
Vip Udaipur Call Girls 9602870969 Dabok Airport Udaipur Escorts ServiceApsara Of India
 

Recently uploaded (20)

Call US '' 8377087607'' !! Call Girls In Model Town Metro (Delhi NCR)
Call US '' 8377087607'' !! Call Girls In Model Town Metro (Delhi NCR)Call US '' 8377087607'' !! Call Girls In Model Town Metro (Delhi NCR)
Call US '' 8377087607'' !! Call Girls In Model Town Metro (Delhi NCR)
 
NO1 WorldWide Amil baba in pakistan Amil Baba in Karachi Black Magic Islamaba...
NO1 WorldWide Amil baba in pakistan Amil Baba in Karachi Black Magic Islamaba...NO1 WorldWide Amil baba in pakistan Amil Baba in Karachi Black Magic Islamaba...
NO1 WorldWide Amil baba in pakistan Amil Baba in Karachi Black Magic Islamaba...
 
Call Girls in Najafgarh Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Najafgarh Delhi 💯Call Us 🔝8264348440🔝Call Girls in Najafgarh Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Najafgarh Delhi 💯Call Us 🔝8264348440🔝
 
Fun Call Girls In Goa 7028418221 Escort Service In Morjim Beach Call Girl
Fun Call Girls In Goa 7028418221 Escort Service In Morjim Beach Call GirlFun Call Girls In Goa 7028418221 Escort Service In Morjim Beach Call Girl
Fun Call Girls In Goa 7028418221 Escort Service In Morjim Beach Call Girl
 
Fun Call Girls In Goa 7028418221 Call Girl Service In Panaji Escorts
Fun Call Girls In Goa 7028418221 Call Girl Service In Panaji EscortsFun Call Girls In Goa 7028418221 Call Girl Service In Panaji Escorts
Fun Call Girls In Goa 7028418221 Call Girl Service In Panaji Escorts
 
Call Girls in Faridabad 9000000000 Faridabad Escorts Service
Call Girls in Faridabad 9000000000 Faridabad Escorts ServiceCall Girls in Faridabad 9000000000 Faridabad Escorts Service
Call Girls in Faridabad 9000000000 Faridabad Escorts Service
 
VIP Call Girls In Goa 7028418221 Call Girls In Baga Beach Escorts Service
VIP Call Girls In Goa 7028418221 Call Girls In Baga Beach Escorts ServiceVIP Call Girls In Goa 7028418221 Call Girls In Baga Beach Escorts Service
VIP Call Girls In Goa 7028418221 Call Girls In Baga Beach Escorts Service
 
Real NO1 Amil baba in Faisalabad Kala jadu in faisalabad Aamil baba Faisalaba...
Real NO1 Amil baba in Faisalabad Kala jadu in faisalabad Aamil baba Faisalaba...Real NO1 Amil baba in Faisalabad Kala jadu in faisalabad Aamil baba Faisalaba...
Real NO1 Amil baba in Faisalabad Kala jadu in faisalabad Aamil baba Faisalaba...
 
1681275559_haunting-adeline and hunting.pdf
1681275559_haunting-adeline and hunting.pdf1681275559_haunting-adeline and hunting.pdf
1681275559_haunting-adeline and hunting.pdf
 
High Profile Call Girls Sodepur - 8250192130 Escorts Service with Real Photos...
High Profile Call Girls Sodepur - 8250192130 Escorts Service with Real Photos...High Profile Call Girls Sodepur - 8250192130 Escorts Service with Real Photos...
High Profile Call Girls Sodepur - 8250192130 Escorts Service with Real Photos...
 
Amil Baba in Pakistan Kala jadu Expert Amil baba Black magic Specialist in Is...
Amil Baba in Pakistan Kala jadu Expert Amil baba Black magic Specialist in Is...Amil Baba in Pakistan Kala jadu Expert Amil baba Black magic Specialist in Is...
Amil Baba in Pakistan Kala jadu Expert Amil baba Black magic Specialist in Is...
 
Call Girl Contact Number Andheri WhatsApp:+91-9833363713
Call Girl Contact Number Andheri WhatsApp:+91-9833363713Call Girl Contact Number Andheri WhatsApp:+91-9833363713
Call Girl Contact Number Andheri WhatsApp:+91-9833363713
 
QUIZ BOLLYWOOD ( weekly quiz ) - SJU quizzers
QUIZ BOLLYWOOD ( weekly quiz ) - SJU quizzersQUIZ BOLLYWOOD ( weekly quiz ) - SJU quizzers
QUIZ BOLLYWOOD ( weekly quiz ) - SJU quizzers
 
Kolkata Call Girl Bagbazar 👉 8250192130 ❣️💯 Available With Room 24×7
Kolkata Call Girl Bagbazar 👉 8250192130 ❣️💯 Available With Room 24×7Kolkata Call Girl Bagbazar 👉 8250192130 ❣️💯 Available With Room 24×7
Kolkata Call Girl Bagbazar 👉 8250192130 ❣️💯 Available With Room 24×7
 
Call Girls In Karnal O8860008073 Sector 6 7 8 9 Karnal Escorts
Call Girls In Karnal O8860008073 Sector 6 7 8 9 Karnal EscortsCall Girls In Karnal O8860008073 Sector 6 7 8 9 Karnal Escorts
Call Girls In Karnal O8860008073 Sector 6 7 8 9 Karnal Escorts
 
Call Girl Price Andheri WhatsApp:+91-9833363713
Call Girl Price Andheri WhatsApp:+91-9833363713Call Girl Price Andheri WhatsApp:+91-9833363713
Call Girl Price Andheri WhatsApp:+91-9833363713
 
Cash Payment Contact:- 7028418221 Goa Call Girls Service North Goa Escorts
Cash Payment Contact:- 7028418221 Goa Call Girls Service North Goa EscortsCash Payment Contact:- 7028418221 Goa Call Girls Service North Goa Escorts
Cash Payment Contact:- 7028418221 Goa Call Girls Service North Goa Escorts
 
Call Girls Near Delhi Pride Hotel New Delhi 9873777170
Call Girls Near Delhi Pride Hotel New Delhi 9873777170Call Girls Near Delhi Pride Hotel New Delhi 9873777170
Call Girls Near Delhi Pride Hotel New Delhi 9873777170
 
Call Girls Somajiguda Sarani 7001305949 all area service COD available Any Time
Call Girls Somajiguda Sarani 7001305949 all area service COD available Any TimeCall Girls Somajiguda Sarani 7001305949 all area service COD available Any Time
Call Girls Somajiguda Sarani 7001305949 all area service COD available Any Time
 
Vip Udaipur Call Girls 9602870969 Dabok Airport Udaipur Escorts Service
Vip Udaipur Call Girls 9602870969 Dabok Airport Udaipur Escorts ServiceVip Udaipur Call Girls 9602870969 Dabok Airport Udaipur Escorts Service
Vip Udaipur Call Girls 9602870969 Dabok Airport Udaipur Escorts Service
 

groovy & grails - lecture 8

  • 1. Groovy: Efficiency Oriented Programming Lecture 8 Master Proteomics & Bioinformatics - University of Geneva Alexandre Masselot - summer 2011
  • 2. Contents ‣ Eclipse tips ‣ 8 queens on a chess board ‣ Genetic algorithm ‣ Abstract class (a little bit more about inheritance)
  • 3. Eclipse tips ‣ Outline view in the right column - get a list of your field and method of the current class
  • 4. Eclipse tips ‣ Outline view in the right column - get a list of your field and method of the current class ‣ Help > Key assist - get a list of all the possible shortcuts
  • 5. Eclipse tips ‣ Outline view in the right column - get a list of your field and method of the current class ‣ Help > Key assist - get a list of all the possible shortcuts
  • 6. 8 queens puzzle ‣ Problem - put 8 queens on a chess board, - none is able to capture another (columns, rows and diagonal)
  • 7. 8 queens puzzle: history ‣ Chess player Max Bezzel proposed the problem in 1848
  • 8. 8 queens puzzle: history ‣ Chess player Max Bezzel proposed the problem in 1848 ‣ Mathematicians (including Gauss) worked on the problem (and generalization to n-queens)
  • 9. 8 queens puzzle: history ‣ Chess player Max Bezzel proposed the problem in 1848 ‣ Mathematicians (including Gauss) worked on the problem (and generalization to n-queens) ‣ Franz Nauck proposed the first solutions (1850)
  • 10. 8 queens puzzle: history ‣ Chess player Max Bezzel proposed the problem in 1848 ‣ Mathematicians (including Gauss) worked on the problem (and generalization to n-queens) ‣ Franz Nauck proposed the first solutions (1850) ‣ Computer scientists joined the party: Edsger Dijkstra (1972) used the problem to illustrate depth-first backtracking algorithm
  • 11. As usually, sexy problems diverge n-queens, n×n chessboard with kings, knights... 6
  • 12. 8 queens on a 8×8 chessboard: how many solutions? 7
  • 13. 8
  • 14. 8
  • 15. 8 queens: some combinatorial considerations ‣ Number of possible positions of 8 queens on a 8x8 chess board (no constraints): - 64 choose 8= = 4,426,165,368
  • 16. 8 queens: some combinatorial considerations ‣ Number of possible positions of 8 queens on a 8x8 chess board (no constraints): - 64 choose 8= = 4,426,165,368 ‣ Number of solution to the 8 queens puzzle: - 92, and reducing symmetries: 12 distinct
  • 17. 8 queens: some combinatorial considerations ‣ Number of possible positions of 8 queens on a 8x8 chess board (no constraints): - 64 choose 8= = 4,426,165,368 ‣ Number of solution to the 8 queens puzzle: - 92, and reducing symmetries: 12 distinct ‣ extend to any n queens, on a n x n board
  • 18. 8 queens: some combinatorial considerations ‣ Number of possible positions of 8 queens on a 8x8 chess board (no constraints): - 64 choose 8= = 4,426,165,368 ‣ Number of solution to the 8 queens puzzle: - 92, and reducing symmetries: 12 distinct ‣ extend to any n queens, on a n x n board n 1 2 3 4 5 6 7 8 9 10 distinct 1 0 0 2 2 1 6 12 46 92 unique 1 0 0 1 10 4 40 92 352 724 http://en.wikipedia.org/wiki/Eight_queens_puzzle
  • 19. Goals for today ‣ Write code to find solutions
  • 20. Goals for today ‣ Write code to find solutions ‣ Brute force
  • 21. Goals for today ‣ Write code to find solutions ‣ Brute force ‣ Genetic programming (evolving random approach)
  • 22. Goals for today ‣ Write code to find solutions ‣ Brute force ‣ Genetic programming (evolving random approach) ‣ generalize the problem to kings
  • 23. Goals for today ‣ Write code to find solutions ‣ Brute force ‣ Genetic programming (evolving random approach) ‣ generalize the problem to kings ‣ code in tp8-solutions @ dokeos
  • 24. An algorithm for solutions
  • 25. An algorithm for solutions
  • 26. An algorithm for solutions
  • 27. An algorithm for solutions
  • 28. An algorithm for solutions
  • 29. An algorithm for solutions
  • 30. An algorithm for solutions
  • 31. An algorithm for solutions
  • 32. An algorithm for solutions
  • 33. An algorithm for solutions
  • 34. An algorithm for solutions
  • 35. An algorithm for solutions
  • 36. An algorithm for solutions
  • 37. An algorithm for solutions
  • 38. An algorithm for solutions
  • 39. An algorithm for solutions
  • 40. An algorithm for solutions
  • 41. An algorithm for solutions
  • 42. An algorithm for solutions
  • 43. An algorithm for solutions
  • 44. An algorithm for solutions
  • 45. A solution finder code: ‣ A chessboard structure: - size & max number of pieces - add/remove pieces - count how many pieces are on the board - check if two pieces are conflicting
  • 46. A solution finder code: ‣ A chessboard structure: - size & max number of pieces - add/remove pieces - count how many pieces are on the board - check if two pieces are conflicting ‣ A mechanism to explore one by one all solutions - mimic the brute force previous example
  • 47. A code synopsis: board fields
  • 48. A code synopsis: board fields ‣ ChessBoard.groovy/ChessBoardWithQueens.groovy /// number of rows and column for the board int size=8
  • 49. A code synopsis: board fields ‣ ChessBoard.groovy/ChessBoardWithQueens.groovy /// number of rows and column for the board int size=8 /// maximum number of pieces on the board int maxPieces=0
  • 50. A code synopsis: board fields ‣ ChessBoard.groovy/ChessBoardWithQueens.groovy /// number of rows and column for the board int size=8 /// maximum number of pieces on the board int maxPieces=0 /** list of list of 2 integers each of them representing a piece on the board (between 0 and (size-1)) */ List piecesPositions = []
  • 51. A code synopsis: board fields ‣ ChessBoard.groovy/ChessBoardWithQueens.groovy /// number of rows and column for the board int size=8 /// maximum number of pieces on the board int maxPieces=0 /** list of list of 2 integers each of them representing a piece on the board (between 0 and (size-1)) */ List piecesPositions = []
  • 52. A code synopsis: board methods
  • 53. A code synopsis: board methods /// how many pieces on the board int countPieces(){...}
  • 54. A code synopsis: board methods /// how many pieces on the board int countPieces(){...} /// synopsis: board << [0, 3] void leftShift(List<Integer> pos){...}
  • 55. A code synopsis: board methods /// how many pieces on the board int countPieces(){...} /// synopsis: board << [0, 3] void leftShift(List<Integer> pos){...} /// remove last introduced piece List<Integer> removeLastPiece(){...}
  • 56. A code synopsis: board methods /// how many pieces on the board int countPieces(){...} /// synopsis: board << [0, 3] void leftShift(List<Integer> pos){...} /// remove last introduced piece List<Integer> removeLastPiece(){...} /// are two pieces positions in conflict? boolean isPieceConflict(List<Integer> pA, List<Integer> pB){...}
  • 57. A code synopsis: a recursive algorithm
  • 58. A code synopsis: a recursive algorithm ‣ Exploring means - placing a new piece at the next non-conflicting position - if all pieces are on the board, flag as a solution - exploring deeper
  • 59. A code synopsis: a recursive algorithm ‣ Exploring means - placing a new piece at the next non-conflicting position - if all pieces are on the board, flag as a solution - exploring deeper ‣ The recursion means calling the same explore method deeper until and end is reached (e.g. all pieces are on the board)
  • 60. A code synopsis: a recursive algorithm ‣ Implementing the displayed algorithm explore: if (all pieces are on the board){ !! one solution !! return } pos ← next position after last piece while (pos is on the board){ add a piece on the board at pos if (no conflict){ explore() } remove last piece pos ← next position }
  • 61. A code synopsis: a recursive algorithm ‣ Implementing the displayed algorithm explore: if (all pieces are on the board){ !! one solution !! return } pos ← next position after last piece while (pos is on the board){ add a piece on the board at pos if (no conflict){ explore() } remove last piece pos ← next position }
  • 62. A code synopsis: a recursive algorithm ‣ Implementing the displayed algorithm explore: if (all pieces are on the board){ !! one solution !! return } pos ← next position after last piece while (pos is on the board){ add a piece on the board at pos if (no conflict){ explore() } remove last piece pos ← next position }
  • 63. A code synopsis: a recursive algorithm ‣ Implementing the displayed algorithm Implementing the displayed algorithm explore: if (all pieces are on the board){ !! one solution !! return } pos ← next position after last piece while (pos is on the board){ add a piece on the board at pos if (no conflict){ explore() } remove last piece pos ← next position }
  • 64. A code synopsis: a recursive algorithm ‣ Implementing the displayed algorithm Implementing the displayed algorithm explore: if (all pieces are on the board){ !! one solution !! return } pos ← next position after last piece while (pos is on the board){ add a piece on the board at pos if (no conflict){ explore() } remove last piece pos ← next position }
  • 65. A codesynopsis: a a recursive algorithm A code synopsis: recursive algorithm ‣ Implementing the displayed algorithm Implementing the displayed algorithm explore: if (all pieces are on the board){ !! one solution !! return } pos ← next position after last piece while (pos is on the board){ add a piece on the board at pos if (no conflict){ explore() } remove last piece pos ← next position }
  • 66. So we only need to code two functionalities a) increment position; b) explore 17
  • 67. A code synopsis: incrementing a position ‣ Incrementing a piece position means
  • 68. A code synopsis: incrementing a position ‣ Incrementing a piece position means - Incrementing the column
  • 69. A code synopsis: incrementing a position ‣ Incrementing a piece position means - Incrementing the column - If end of line is reached: increment row and goto first column
  • 70. A code synopsis: incrementing a position ‣ Incrementing a piece position means - Incrementing the column - If end of line is reached: increment row and goto first column - Return null is end of the board is reached
  • 71. A code synopsis: incrementing a position ‣ Incrementing a piece position means - Incrementing the column - If end of line is reached: increment row and goto first column - Return null is end of the board is reached - Return [0,0] if starting position is null
  • 72. A code synopsis: incrementing a position
  • 73. A code synopsis: incrementing a position ‣ Groovy code:
  • 74. A code synopsis: incrementing a position ‣ Groovy code: /* a position is a List of 2 integer in [0, boardSize[
  • 75. A code synopsis: incrementing a position ‣ Groovy code: /* a position is a List of 2 integer in [0, boardSize[ increment second coordinates if possible
  • 76. A code synopsis: incrementing a position ‣ Groovy code: /* a position is a List of 2 integer in [0, boardSize[ increment second coordinates if possible then the first (and second is set to 0)
  • 77. A code synopsis: incrementing a position ‣ Groovy code: /* a position is a List of 2 integer in [0, boardSize[ increment second coordinates if possible then the first (and second is set to 0) returns null if end of board is reached
  • 78. A code synopsis: incrementing a position ‣ Groovy code: /* a position is a List of 2 integer in [0, boardSize[ increment second coordinates if possible then the first (and second is set to 0) returns null if end of board is reached returns [0,0] if a null position is to be incremented */
  • 79. A code synopsis: incrementing a position ‣ Groovy code: /* a position is a List of 2 integer in [0, boardSize[ increment second coordinates if possible then the first (and second is set to 0) returns null if end of board is reached returns [0,0] if a null position is to be incremented */ List<Integer> incrementPiecePosition(int boardSize, List<Integer> p){ return [p[0], p[1]+1] }
  • 80. A code synopsis: incrementing a position ‣ Groovy code: /* a position is a List of 2 integer in [0, boardSize[ increment second coordinates if possible then the first (and second is set to 0) returns null if end of board is reached returns [0,0] if a null position is to be incremented */ List<Integer> incrementPiecePosition(int boardSize, List<Integer> p){ if(p[1] == (boardSize - 1) ){ return [p[0]+1, 0] } return [p[0], p[1]+1] }
  • 81. A code synopsis: incrementing a position ‣ Groovy code: /* a position is a List of 2 integer in [0, boardSize[ increment second coordinates if possible then the first (and second is set to 0) returns null if end of board is reached returns [0,0] if a null position is to be incremented */ List<Integer> incrementPiecePosition(int boardSize, List<Integer> p){ if(p[1] == (boardSize - 1) ){ if(p[0] == (boardSize -1) ) return null return [p[0]+1, 0] } return [p[0], p[1]+1] }
  • 82. A code synopsis: incrementing a position ‣ Groovy code: /* a position is a List of 2 integer in [0, boardSize[ increment second coordinates if possible then the first (and second is set to 0) returns null if end of board is reached returns [0,0] if a null position is to be incremented */ List<Integer> incrementPiecePosition(int boardSize, List<Integer> p){ if(p==null) return [0,0] if(p[1] == (boardSize - 1) ){ if(p[0] == (boardSize -1) ) return null return [p[0]+1, 0] } return [p[0], p[1]+1] }
  • 83. 8 queens: a recursive algorithm (cont’d) def explore(board){ //walk through all possible position until it is not possible anymore to increment while(p = incrementPiecePosition(board.size, p)){ //put the current piece on the board to give it a try board<<p //remove the piece before training another position board.removeLastPiece() } }
  • 84. 8 queens: a recursive algorithm (cont’d) def explore(board){ //walk through all possible position until it is not possible anymore to increment while(p = incrementPiecePosition(board.size, p)){ //put the current piece on the board to give it a try board<<p if(!board.countConflicts()){ // if it can be added without conflict try exploration deeper // (with one nore piece) explore(board) } //remove the piece before training another position board.removeLastPiece() } }
  • 85. 8 queens: a recursive algorithm (cont’d) def explore(board){ //let's take the last piece as starting point or null if the board is empty def p=board.countPieces()?board.piecesPositions[-1]:null //walk through all possible position until it is not possible anymore to increment while(p = incrementPiecePosition(board.size, p)){ //put the current piece on the board to give it a try board<<p if(!board.countConflicts()){ // if it can be added without conflict try exploration deeper // (with one nore piece) explore(board) } //remove the piece before training another position board.removeLastPiece() } }
  • 86. 8 queens: a recursive algorithm (cont’d) def explore(board){ if((! board.countConflicts()) && (board.countPieces() == board.maxPieces)){ println "A working setup :n$board" return } //let's take the last piece as starting point or null if the board is empty def p=board.countPieces()?board.piecesPositions[-1]:null //walk through all possible position until it is not possible anymore to increment while(p = incrementPiecePosition(board.size, p)){ //put the current piece on the board to give it a try board<<p if(!board.countConflicts()){ // if it can be added without conflict try exploration deeper // (with one nore piece) explore(board) } //remove the piece before training another position board.removeLastPiece() } }
  • 87. A recursive function calls itself 21
  • 88. 8 queens: a recursive algorithm (cont’d) ‣ Initialization contains: - defining a empty board with correct size - launching the first call to the recursive explore function ChessBoard board=[size:8, maxPieces:8] explore(board)
  • 89. 8 queens: a recursive algorithm (cont’d) ‣ Initialization contains: - defining a empty board with correct size - launching the first call to the recursive explore function ChessBoard board=[size:8, maxPieces:8] explore(board) ‣ See scripts/recursiveChessExploration.groovy
  • 90. 8 queens: a recursive algorithm (cont’d) ‣ Initialization contains: - defining a empty board with correct size - launching the first call to the recursive explore function ChessBoard board=[size:8, maxPieces:8] explore(board) ‣ See scripts/recursiveChessExploration.groovy
  • 91. 8 queens: a recursive algorithm (cont’d) ‣ Initialization contains: - defining a empty board with correct size - launching the first call to the recursive explore function ChessBoard board=[size:8, maxPieces:8] explore(board) ‣ See scripts/recursiveChessExploration.groovy
  • 92. 8 queens: a recursive algorithm (cont’d) ‣ Initialization contains: - defining a empty board with correct size - launching the first call to the recursive explore function ChessBoard board=[size:8, maxPieces:8] explore(board) ‣ See scripts/recursiveChessExploration.groovy
  • 94. Recursion: the limits ‣ Recursive method is concise
  • 95. Recursion: the limits ‣ Recursive method is concise ‣ But it requires - time (method call) - memory (deep tree!)
  • 96. Recursion: the limits ‣ Recursive method is concise ‣ But it requires - time (method call) - memory (deep tree!) ‣ In practice, faster methods exist - walking through solution staying at the same stack level
  • 97. Recursion: the limits ‣ Recursive method is concise ‣ But it requires - time (method call) - memory (deep tree!) ‣ In practice, faster methods exist - walking through solution staying at the same stack level ‣ Dedicated solutions if often better - In the case of the queens problems, knowing the pieces move can greatly help to write a dedicated algorithm (one per row, one per column...)
  • 99. Genetic Algorithm: an introduction ‣ A problem ⇒ a fitness function
  • 100. Genetic Algorithm: an introduction ‣ A problem ⇒ a fitness function ‣ A candidate solution ⇒ a score given by the fitness function
  • 101. Genetic Algorithm: an introduction ‣ A problem ⇒ a fitness function ‣ A candidate solution ⇒ a score given by the fitness function ‣ The higher the fit, the fittest the candidate
  • 102. Genetic Algorithm: an introduction (cont’d) ‣ Searching for a solution simulating a natural selection
  • 103. Genetic Algorithm: an introduction (cont’d) ‣ Searching for a solution simulating a natural selection ‣ One candidate solution ⇔ one gene
  • 104. Genetic Algorithm: an introduction (cont’d) ‣ Searching for a solution simulating a natural selection ‣ One candidate solution ⇔ one gene ‣ population ⇔ set of genes
  • 105. Genetic Algorithm: an introduction (cont’d) ‣ Searching for a solution simulating a natural selection ‣ One candidate solution ⇔ one gene ‣ population ⇔ set of genes ‣ Start : initialize a random population
  • 106. Genetic Algorithm: an introduction (cont’d) ‣ Searching for a solution simulating a natural selection ‣ One candidate solution ⇔ one gene ‣ population ⇔ set of genes ‣ Start : initialize a random population ‣ One generation - fittest genes are selected - cross-over between those genes - random mutation
  • 107. GA for the 8 queens problem
  • 108. GA for the 8 queens problem ‣ Gene ⇔ 8 positions
  • 109. GA for the 8 queens problem ‣ Gene ⇔ 8 positions ‣ Fitness ⇔ -board.countConflicts()
  • 110. GA for the 8 queens problem ‣ Gene ⇔ 8 positions ‣ Fitness ⇔ -board.countConflicts() ‣ Cross-over ⇔ mixing pieces of two boards
  • 111. GA for the 8 queens problem ‣ Gene ⇔ 8 positions ‣ Fitness ⇔ -board.countConflicts() ‣ Cross-over ⇔ mixing pieces of two boards ‣ Mutation ⇔ moving randomly one piece
  • 112. A GA in practice (Evolution.groovy) class Evolution { int nbGenes=200 double mutationRate = 0.1 int nbKeepBest = 50 int nbAddRandom = 10 Random randomGenerator = new Random() def geneFactory List genePool ... }
  • 113. A GA in practice (Evolution.groovy) def nextGeneration(){ //select a subset of the best gene + mutate them according to a rate List reproPool=selectBest().toList().unique{it} //keep the repro pool in the best genePool=reproPool }
  • 114. A GA in practice (Evolution.groovy) def nextGeneration(){ //select a subset of the best gene + mutate them according to a rate List reproPool=selectBest().toList().unique{it} //keep the repro pool in the best genePool=reproPool //finally mutate genes with the given rate genePool.each {gene -> if(randomGenerator.nextDouble() < mutationRate) gene.mutate() } }
  • 115. A GA in practice (Evolution.groovy) def nextGeneration(){ //select a subset of the best gene + mutate them according to a rate List reproPool=selectBest().toList().unique{it} //keep the repro pool in the best genePool=reproPool //from the 'fittest' reproPool, rebuild the total population by crossover (1..<((nbGenes-genePool.size())/2) ).each{ def geneA = reproPool[randomGenerator.nextInt(nbKeepBest)].clone() def geneB = reproPool[randomGenerator.nextInt(nbKeepBest)].clone() geneA.crossOver(geneB) genePool << geneA genePool << geneB } //finally mutate genes with the given rate genePool.each {gene -> if(randomGenerator.nextDouble() < mutationRate) gene.mutate() } }
  • 116. A GA in practice (Evolution.groovy) def nextGeneration(){ //select a subset of the best gene + mutate them according to a rate List reproPool=selectBest().toList().unique{it} //keep the repro pool in the best genePool=reproPool //add a few random to the pool buildRandom(nbAddRandom).each{ genePool << it } //from the 'fittest' reproPool, rebuild the total population by crossover (1..<((nbGenes-genePool.size())/2) ).each{ def geneA = reproPool[randomGenerator.nextInt(nbKeepBest)].clone() def geneB = reproPool[randomGenerator.nextInt(nbKeepBest)].clone() geneA.crossOver(geneB) genePool << geneA genePool << geneB } //finally mutate genes with the given rate genePool.each {gene -> if(randomGenerator.nextDouble() < mutationRate) gene.mutate() } }
  • 118. 31
  • 120. GA: more evolution ‣ Mutation rate can be time dependent (decrease over time...)
  • 121. GA: more evolution ‣ Mutation rate can be time dependent (decrease over time...) ‣ Different population pools (different parameters), long term cross-over
  • 122. GA: more evolution ‣ Mutation rate can be time dependent (decrease over time...) ‣ Different population pools (different parameters), long term cross-over ‣ Regular introduction of new random genes
  • 123. Genetic algorithm: a solution for everything?
  • 124. Genetic algorithm: a solution for everything? ‣ GA looks like a magic solution to any optimization process
  • 125. Genetic algorithm: a solution for everything? ‣ GA looks like a magic solution to any optimization process ‣ In practice, hard to tune evolution strategy & parameters
  • 126. Genetic algorithm: a solution for everything? ‣ GA looks like a magic solution to any optimization process ‣ In practice, hard to tune evolution strategy & parameters ‣ For a given problem: a dedicated solution always better (when possible)
  • 127. Genetic algorithm: a solution for everything? ‣ GA looks like a magic solution to any optimization process ‣ In practice, hard to tune evolution strategy & parameters ‣ For a given problem: a dedicated solution always better (when possible) ‣ For the queens problems, the recursive method is much faster
  • 128. Genetic algorithm: a solution for everything? ‣ GA looks like a magic solution to any optimization process ‣ In practice, hard to tune evolution strategy & parameters ‣ For a given problem: a dedicated solution always better (when possible) ‣ For the queens problems, the recursive method is much faster ‣ For 32 knights: GA is much faster (not all solutions!)
  • 129. 32 Knights on the board 34
  • 131. Board with knights ‣ ChessBoard.groovy: boolean isPieceConflict(List<Integer> pA, List<Integer> pB){ //same row or same column if((pA[0] == pB [0]) || (pA[1] == pB[1])) return true //first diagonal if((pA[0] - pA [1]) == (pB[0] - pB[1])) return true //second diagonal if((pA[0] + pA [1]) == (pB[0] + pB[1])) return true return false }
  • 132. Shall we redefine all the previous methods from the ChessBoard with queens? DRY! 36
  • 133. A generic ChessBoard : abstract class
  • 134. A generic ChessBoard : abstract class ‣ ChessBoard.groovy: abstract class ChessBoard{ ... all other methods/fields are the same ... abstract boolean isPieceConflict(List<Integer> pA, List<Integer> pB); }
  • 137. Queen specialization ‣ Then a implementation class class ChessBoardWithQueens extends ChessBoard{ //only method boolean isPieceConflict(List<Integer> pA, List<Integer> pB){ //same row or same column if((pA[0] == pB [0]) || (pA[1] == pB[1])) return true //first diagonal if((pA[0] - pA [1]) == (pB[0] - pB[1])) return true //second diagonal if((pA[0] + pA [1]) == (pB[0] + pB[1])) return true return false }
  • 139. Knight specialization ‣ ChessBoardWithKnights.groovy: class ChessBoardWithKnights extends ChessBoard{ //only method boolean isPieceConflict(List<Integer> pA, List<Integer> pB){ if( (Math.abs(pA[0]-pB[0])==2) && (Math.abs(pA[1]-pB[1])==1) ) return true if( (Math.abs(pA[1]-pB[1])==2) && (Math.abs(pA[0]-pB[0])==1) ) return true return false }
  • 140. And from the exploration script
  • 141. And from the exploration script ‣ In main script: //ChessBoardWithQueens board=[size:8, maxPieces:8] ChessBoardWithKnights board=[size:8, maxPieces:32] explore(board)
  • 142. And from the exploration script ‣ In main script: //ChessBoardWithQueens board=[size:8, maxPieces:8] ChessBoardWithKnights board=[size:8, maxPieces:32] explore(board) ‣ Nothing more...
  • 143. Do not forget unit tests! 41
  • 144. abstract class testing ‣ Not possible to instantiate new ChessBoard()
  • 145. abstract class testing ‣ Not possible to instantiate new ChessBoard() ‣ Create a fake ChessBoard class for test class ChessBoardTest extends GroovyTestCase { class ChessBoardDummy extends ChessBoard{ boolean isPieceConflict(List<Integer> pA, List<Integer> pB){ return ( (pA[0]==pB[0]) && (pA[1]==pB[1]) ) } } ... }
  • 146. abstract class testing ‣ Not possible to instantiate new ChessBoard() ‣ Create a fake ChessBoard class for test class ChessBoardTest extends GroovyTestCase { class ChessBoardDummy extends ChessBoard{ boolean isPieceConflict(List<Integer> pA, List<Integer> pB){ return ( (pA[0]==pB[0]) && (pA[1]==pB[1]) ) } } ... } ‣ Then all tests are with instances ChessBoardDummy board=[size:4, maxPieces:3]
  • 147. abstract class testing (cont’d)
  • 148. abstract class testing (cont’d) ‣ ChessBoardWithQueens only test for pieces conflict class ChessBoardWithQueensTest extends GroovyTestCase { public void testPieceConflict(){ ChessBoardWithQueens board=[size:4, maxPieces:3] //same spot assert board.isPieceConflict([0, 0], [0, 0]) //same row assert board.isPieceConflict([0, 2], [0, 0]) //same column assert board.isPieceConflict([2, 0], [0, 0]) ... }

Editor's Notes

  1. today end of a cycle\nnext week: genetic algorithm\nthen web programming\nend of the year exam: bring in your ideas\nplay customer + coder\ncustomer phase with me, then iterative development.\n
  2. we go to real world\ngood news : no exercise to do\nbad news : you must understand the whole project\nThis project is something like a semester project\nabstract class =&gt; a little more in OOP\n\n
  3. \n
  4. \n
  5. \n
  6. \n
  7. check out more on wikipedia\n
  8. check out more on wikipedia\n
  9. check out more on wikipedia\n
  10. check out more on wikipedia\n
  11. bishops, rooks,\nqueens + knights etc...\n
  12. back to the roots\n
  13. \n
  14. modulo rotation, reflexion\n92 solution in the total\n
  15. no known formula to compute the number of solution based on n\nquite some literature\n
  16. no known formula to compute the number of solution based on n\nquite some literature\n
  17. no known formula to compute the number of solution based on n\nquite some literature\n
  18. no known formula to compute the number of solution based on n\nquite some literature\n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. go with aimant on the board\n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n
  47. for queens, positions could only been one column, but let&amp;#x2019;s not over-engineer our chessboard from start\n
  48. for queens, positions could only been one column, but let&amp;#x2019;s not over-engineer our chessboard from start\n
  49. for queens, positions could only been one column, but let&amp;#x2019;s not over-engineer our chessboard from start\n
  50. for queens, positions could only been one column, but let&amp;#x2019;s not over-engineer our chessboard from start\n
  51. for queens, positions could only been one column, but let&amp;#x2019;s not over-engineer our chessboard from start\n
  52. for queens, positions could only been one column, but let&amp;#x2019;s not over-engineer our chessboard from start\n
  53. for queens, positions could only been one column, but let&amp;#x2019;s not over-engineer our chessboard from start\n
  54. for queens, positions could only been one column, but let&amp;#x2019;s not over-engineer our chessboard from start\n
  55. for queens, positions could only been one column, but let&amp;#x2019;s not over-engineer our chessboard from start\n
  56. for queens, positions could only been one column, but let&amp;#x2019;s not over-engineer our chessboard from start\n
  57. for queens, positions could only been one column, but let&amp;#x2019;s not over-engineer our chessboard from start\n
  58. for queens, positions could only been one column, but let&amp;#x2019;s not over-engineer our chessboard from start\n
  59. for queens, positions could only been one column, but let&amp;#x2019;s not over-engineer our chessboard from start\n
  60. most attentive of you will notice that isPieceConflict is defined only into ChessBoardWithQueens.groovy\nAnd will notice that some methods are not (yet) needed (clone(), countConflicts() etc.\nQ: how do you know your code works?\n
  61. most attentive of you will notice that isPieceConflict is defined only into ChessBoardWithQueens.groovy\nAnd will notice that some methods are not (yet) needed (clone(), countConflicts() etc.\nQ: how do you know your code works?\n
  62. most attentive of you will notice that isPieceConflict is defined only into ChessBoardWithQueens.groovy\nAnd will notice that some methods are not (yet) needed (clone(), countConflicts() etc.\nQ: how do you know your code works?\n
  63. most attentive of you will notice that isPieceConflict is defined only into ChessBoardWithQueens.groovy\nAnd will notice that some methods are not (yet) needed (clone(), countConflicts() etc.\nQ: how do you know your code works?\n
  64. most attentive of you will notice that isPieceConflict is defined only into ChessBoardWithQueens.groovy\nAnd will notice that some methods are not (yet) needed (clone(), countConflicts() etc.\nQ: how do you know your code works?\n
  65. most attentive of you will notice that isPieceConflict is defined only into ChessBoardWithQueens.groovy\nAnd will notice that some methods are not (yet) needed (clone(), countConflicts() etc.\nQ: how do you know your code works?\n
  66. most attentive of you will notice that isPieceConflict is defined only into ChessBoardWithQueens.groovy\nAnd will notice that some methods are not (yet) needed (clone(), countConflicts() etc.\nQ: how do you know your code works?\n
  67. most attentive of you will notice that isPieceConflict is defined only into ChessBoardWithQueens.groovy\nAnd will notice that some methods are not (yet) needed (clone(), countConflicts() etc.\nQ: how do you know your code works?\n
  68. most attentive of you will notice that isPieceConflict is defined only into ChessBoardWithQueens.groovy\nAnd will notice that some methods are not (yet) needed (clone(), countConflicts() etc.\nQ: how do you know your code works?\n
  69. most attentive of you will notice that isPieceConflict is defined only into ChessBoardWithQueens.groovy\nAnd will notice that some methods are not (yet) needed (clone(), countConflicts() etc.\nQ: how do you know your code works?\n
  70. most attentive of you will notice that isPieceConflict is defined only into ChessBoardWithQueens.groovy\nAnd will notice that some methods are not (yet) needed (clone(), countConflicts() etc.\nQ: how do you know your code works?\n
  71. most attentive of you will notice that isPieceConflict is defined only into ChessBoardWithQueens.groovy\nAnd will notice that some methods are not (yet) needed (clone(), countConflicts() etc.\nQ: how do you know your code works?\n
  72. \n
  73. \n
  74. \n
  75. \n
  76. \n
  77. \n
  78. \n
  79. \n
  80. \n
  81. \n
  82. \n
  83. \n
  84. \n
  85. \n
  86. \n
  87. Q: how do you know your code works?\n
  88. Q: how do you know your code works?\n
  89. Q: how do you know your code works?\n
  90. Q: how do you know your code works?\n
  91. Q: how do you know your code works?\n
  92. Q: how do you know your code works?\n
  93. Q: how do you know your code works?\n
  94. Q: how do you know your code works?\n
  95. Q: how do you know your code works?\n
  96. Q: how do you know your code works?\n
  97. Q: how do you know your code works?\n
  98. Q: how do you know your code works?\n
  99. Q: how do you know your code works?\n
  100. Q: how do you know your code works?\n
  101. Q: how do you know your code works?\n
  102. Q: how do you know your code works?\n
  103. Q: how do you know your code works?\n
  104. Q: how do you know your code works?\n
  105. Q: how do you know your code works?\n
  106. Q: how do you know your code works?\n
  107. Q: how do you know your code works?\n
  108. Q: how do you know your code works?\n
  109. Q: how do you know your code works?\n
  110. \n
  111. \n
  112. \n
  113. divide and conquer\nmust not call itself indefinitely\n
  114. \n
  115. \n
  116. \n
  117. \n
  118. \n
  119. \n
  120. time can also be measured taken into consideration the number of lines written, not just computing time\nThink of building a taxonomy subtree\n walking through a deep tree means remembering all the precedent status\n
  121. time can also be measured taken into consideration the number of lines written, not just computing time\nThink of building a taxonomy subtree\n walking through a deep tree means remembering all the precedent status\n
  122. time can also be measured taken into consideration the number of lines written, not just computing time\nThink of building a taxonomy subtree\n walking through a deep tree means remembering all the precedent status\n
  123. time can also be measured taken into consideration the number of lines written, not just computing time\nThink of building a taxonomy subtree\n walking through a deep tree means remembering all the precedent status\n
  124. We know the finality =&gt; we can write a dedicated solution\nbut another approach exists\n
  125. \n
  126. \n
  127. \n
  128. motto: the fittest survive and transfer its genes\n random new genes can be incorporated into the population\n
  129. motto: the fittest survive and transfer its genes\n random new genes can be incorporated into the population\n
  130. motto: the fittest survive and transfer its genes\n random new genes can be incorporated into the population\n
  131. motto: the fittest survive and transfer its genes\n random new genes can be incorporated into the population\n
  132. motto: the fittest survive and transfer its genes\n random new genes can be incorporated into the population\n
  133. \n
  134. \n
  135. \n
  136. \n
  137. \n
  138. \n
  139. \n
  140. \n
  141. a gene factory which can generate gene related to our problem\nthose genes can mutate, crossover, compute there fitness, being randomly built\n\n
  142. local minima =&gt; never get out\n
  143. different pools =&gt; each explore a specificity\nmix to avoid consanguinity....\n
  144. different pools =&gt; each explore a specificity\nmix to avoid consanguinity....\n
  145. different pools =&gt; each explore a specificity\nmix to avoid consanguinity....\n
  146. if you know the finality, darwinism is not the correct path...\n
  147. if you know the finality, darwinism is not the correct path...\n
  148. if you know the finality, darwinism is not the correct path...\n
  149. if you know the finality, darwinism is not the correct path...\n
  150. if you know the finality, darwinism is not the correct path...\n
  151. \n
  152. 32 knights, or 14 bishops, 16 kings or 8 rooks,\n
  153. \n
  154. not good...\n
  155. not good...\n
  156. not good...\nnote the missing {} and\n
  157. not good...\nnote the missing {} and\n
  158. not good...\nnote the missing {} and\n
  159. Test all with ChessBoardWithQueensTest\nonly pieces conflict with ChessBoardWithKnightsTests\n
  160. In practice: think agile!!! refactor when the knights come on the table!\nGA: much slower for the queens, but so much faster for the knights...\n
  161. In practice: think agile!!! refactor when the knights come on the table!\nGA: much slower for the queens, but so much faster for the knights...\n
  162. \n
  163. \n
  164. \n
  165. \n
  166. \n