public Object result(Object s, Action a) { if (a is QueenAction) { QueenAction qa = (QueenAction)a; NQueensBoard board = (NQueensBoard)s; NQueensBoard newBoard = new NQueensBoard(board.getSize()); newBoard.setBoard(board.getQueenPositions()); if (qa.getName() == QueenAction.PLACE_QUEEN) { newBoard.AddQueenAt(qa.getLocation()); } else if (qa.getName() == QueenAction.REMOVE_QUEEN) { newBoard.removeQueenFrom(qa.getLocation()); } else if (qa.getName() == QueenAction.MOVE_QUEEN) { newBoard.moveQueenTo(qa.getLocation()); } s = newBoard; } // if action is not understood or is a NoOp // the result will be the current state. return(s); }
// // START - Interface FitnessFunction public double getValue(String individual) { double fitness = 0; NQueensBoard board = getBoardForIndividual(individual); int boardSize = board.getSize(); // Calculate the number of non-attacking pairs of queens (refer to AIMA // page 117). List <XYLocation> qPositions = board.getQueenPositions(); for (int fromX = 0; fromX < (boardSize - 1); fromX++) { for (int toX = fromX + 1; toX < boardSize; toX++) { int fromY = qPositions.get(fromX).getYCoOrdinate(); bool nonAttackingPair = true; // Check right beside int toY = fromY; if (board.queenExistsAt(new XYLocation(toX, toY))) { nonAttackingPair = false; } // Check right and above toY = fromY - (toX - fromX); if (toY >= 0) { if (board.queenExistsAt(new XYLocation(toX, toY))) { nonAttackingPair = false; } } // Check right and below toY = fromY + (toX - fromX); if (toY < boardSize) { if (board.queenExistsAt(new XYLocation(toX, toY))) { nonAttackingPair = false; } } if (nonAttackingPair) { fitness += 1.0; } } } return(fitness); }