Question

In: Computer Science

Python Code for 8-queens using random restart algorithms

Python Code for 8-queens using random restart algorithms

Solutions

Expert Solution

Code:

#!/usr/bin/python

import random,sys,copy

from optparse import OptionParser

try:

import psyco

psyco.full()

except ImportError:

pass

"""

cowboy code, but seems to work

USAGE: python prog <numberruns=1> <verbocity=False>

"""

class board:

def __init__(self, list=None):

    if list == None:

      self.board = [[0 for i in range(0,8)] for j in range(0,8)]

      #initialize queens at random places

      for i in range(0,8):

        while 1:

          rand_row = random.randint(0,7)

          rand_col = random.randint(0,7)

          if self.board[rand_row][rand_col] == 0:

            self.board[rand_row][rand_col] = "Q"

            break

    #TODO raise errors if board is not right format or dimension

#define how to print the board

def __repr__(self):

    mstr = ""

    for i in range(0,8):

      for j in range(0,8):

        mstr = mstr + str(self.board[i][j]) + " "

      mstr = mstr + "n"

    return (mstr)

class queens:

def __init__(self, numruns, verbocity, passedboard=None):

    #TODO check options

    self.totalruns = numruns

    self.totalsucc = 0

    self.totalnumsteps = 0

    self.verbocity = verbocity

    for i in range(0,numruns):

      if self.verbocity == True:

        print "===================="

        print "BOARD",i

        print "===================="

      self.mboard = board(passedboard)

      self.cost = self.calc_cost(self.mboard)

      self.hill_solution()

def hill_solution(self):

    while 1:

      currViolations = self.cost

      self.getlowercostboard()

      if currViolations == self.cost:

        break

      self.totalnumsteps += 1

      if self.verbocity == True:

        print "Board Violations", self.calc_cost(self.mboard)

        print self.mboard

    if self.cost != 0:

      if self.verbocity == True:

        print "NO SOLUTION FOUND"

    else:

      if self.verbocity == True:

        print "SOLUTION FOUND"

      self.totalsucc += 1

    return self.cost

def printstats(self):

    print "Total Runs: ", self.totalruns

    print "Total Success: ", self.totalsucc

    print "Success Percentage: ", float(self.totalsucc)/float(self.totalruns)

    print "Average number of steps: ", float(self.totalnumsteps)/float(self.totalruns)

def calc_cost(self, tboard):

    #these are separate for easier debugging

    totalhcost = 0

    totaldcost = 0

    for i in range(0,8):

      for j in range(0,8):

        #if this node is a queen, calculate all violations

        if tboard.board[i][j] == "Q":

          #subtract 2 so don't count self

          #sideways and vertical

          totalhcost -= 2

          for k in range(0,8):

            if tboard.board[i][k] == "Q":

              totalhcost += 1

            if tboard.board[k][j] == "Q":

              totalhcost += 1

          #calculate diagonal violations

          k, l = i+1, j+1

          while k < 8 and l < 8:

            if tboard.board[k][l] == "Q":

              totaldcost += 1

            k +=1

            l +=1

          k, l = i+1, j-1

        while k < 8 and l >= 0:

            if tboard.board[k][l] == "Q":

              totaldcost += 1

            k +=1

            l -=1

          k, l = i-1, j+1

          while k >= 0 and l < 8:

            if tboard.board[k][l] == "Q":

              totaldcost += 1

            k -=1

            l +=1

          k, l = i-1, j-1

          while k >= 0 and l >= 0:

            if tboard.board[k][l] == "Q":

              totaldcost += 1

            k -=1

            l -=1

    return ((totaldcost + totalhcost)/2)

#this function tries moving every queen to every spot, with only one move

#and returns the move that has the leas number of violations

def getlowercostboard(self):

    lowcost = self.calc_cost(self.mboard)

    lowestavailable = self.mboard

    #move one queen at a time, the optimal single move by brute force

    for q_row in range(0,8):

      for q_col in range(0,8):

        if self.mboard.board[q_row][q_col] == "Q":

          #get the lowest cost by moving this queen

          for m_row in range(0,8):

            for m_col in range(0,8):

              if self.mboard.board[m_row][m_col] != "Q":

                #try placing the queen here and see if it's any better

                tryboard = copy.deepcopy(self.mboard)

                tryboard.board[q_row][q_col] = 0

                tryboard.board[m_row][m_col] = "Q"

                thiscost = self.calc_cost(tryboard)

                if thiscost < lowcost:

                  lowcost = thiscost

                  lowestavailable = tryboard

    self.mboard = lowestavailable

    self.cost = lowcost

if __name__ == "__main__":

parser = OptionParser()

parser.add_option("-q", "--quiet", dest="verbose",

                   action="store_false", default=True,

                   help="Don't print all the moves... wise option if using large numbers")

parser.add_option("--numrun", dest="numrun", help="Number of random Boards", default=1,

                   type="int")

(options, args) = parser.parse_args()

mboard = queens(verbocity=options.verbose, numruns=options.numrun)

mboard.printstats()


Related Solutions

Write a python script to solve the 4-queens problem using. The code should allow for random...
Write a python script to solve the 4-queens problem using. The code should allow for random starting, and for placed starting. "The 4-Queens Problem[1] consists in placing four queens on a 4 x 4 chessboard so that no two queens can capture each other. That is, no two queens are allowed to be placed on the same row, the same column or the same diagonal." Display the iterations until the final solution Hill Climbing (your choice of variant)
In this case study, your task is to study different search algorithms to solve the N-Queens...
In this case study, your task is to study different search algorithms to solve the N-Queens Problem which has been presented in class. We will focus on the incremental formulation in which we add a queen to any square in the leftmost empty column that is not attacked by any other queen. We will compare the following algorithms: 1- Breadth-first Seatch (BFS) 2- Depth-first Search (DFS) 3- Simulated Annealing (SA) 4- Hill Climbing (HC) Question is:. Using any of the...
need a code MIPS assembly language program to implement algorithms of an 8-bit integer "positive integer"...
need a code MIPS assembly language program to implement algorithms of an 8-bit integer "positive integer" to calculate the square root for an-8 bit integer using The Radix-2 SRT-Redundant and Non-Redundant Algorithm to approximate square root
I am trying to create an 8-bit random number generator in verilog code using a mux,...
I am trying to create an 8-bit random number generator in verilog code using a mux, a d flip flop and a LFSR not sure what I am doing wrong but need some help with getting it working properly any help would be greatly appreciated. here is what I have so far: module RNG #(parameter size=8)(output [7:0]SO,output [7:0] RN,input clk,rst,input[size-1:0]seed,input L);    wire [7:0] Sin=SO[7]^SO[5]^SO[4]^SO[3];    ffw F1 (SO,clk,rst,Sin);    MUX M1 (Sin,seed,{SO[size-2:0],next},L);    xor X1 (next,SO[6],SO[7]);    assign RN=next;...
For these of string functions, write the code for it in C++ or Python (without using...
For these of string functions, write the code for it in C++ or Python (without using any of thatlanguage's built-in functions) You may assume there is a function to convert Small string into the language string type and a function to convert your language's string type back to Small string type. 1. int [] searchA,ll(string in...str, string sub): returns an array of positions of sub in in...str or an one element array with -1 if sub doesn't exist in in...str
"PYTHON" Write some code " USING PYTHON" to keep reading numbers from the user until the...
"PYTHON" Write some code " USING PYTHON" to keep reading numbers from the user until the users enters a negative number. The program then prints out: a) the sum of all the numbers b) the average of all the numbers c) the max of the numbers d) the min of the numbers Note we did not cover lists (array) so you will not use them in this problem. Finally, ask the user for their name, then print their name as...
Need a python code for LU factorization( for partial pivoting and complete pivoting) of a random...
Need a python code for LU factorization( for partial pivoting and complete pivoting) of a random matrix size 5x5.
#python. Explain code script of each part using comments for the reader. The code script must...
#python. Explain code script of each part using comments for the reader. The code script must work without any errors or bugs. Ball moves in a 2D coordinate system beginning from the original point (0,0). The ball can move upwards, downwards, left and right using x and y coordinates. Code must ask the user for the destination (x2, y2) coordinate point by using the input x2 and y2 and the known current location, code can use the euclidean distance formula...
Using Python code create a program only with beginners code. You are taking online reservations at...
Using Python code create a program only with beginners code. You are taking online reservations at the The inn Ask for your client’s name and save in a variable Ask how many nights your client will be staying and save in a variable Room rental is $145 per night Sales tax is 8.5% Habitation tax is $5 per night (not subject to sales tax) Print out: Client’s name Room rate per night Number of nights Room cost (room rate *...
This is using Python, it is utilizing code from a Fraction class to create a Binary...
This is using Python, it is utilizing code from a Fraction class to create a Binary Class Please leave comments so I may be able to learn from this. Instruction for Binary Class: Exercise 6.18: Design an immutable class BinaryNumber, in the style of our Fraction class. Internally, your only instance variable should be a text string that represents the binary value, of the form '1110100'. Implement a constructor that takes a string parameter that specifies the original binary value....
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT