Question

# Parts to be completed are marked with '<<<<< COMPLETE' import random N = 8 MAXSTEPS...

# Parts to be completed are marked with '<<<<< COMPLETE'
import random

N = 8
MAXSTEPS = 5000

# generates a random n-queens board
# representation: a list of length n the value at index i is
# row that contains the ith queen;
# exampe for 4-queens: [0,2,0,3] means that the queen in column 0 is
# sitting in row 0, the queen in colum 1 is in row, the queen in column 2
# is in row 0, and the queen in column 3 is in row 3;
def random_queens(n):
queens = []
for i in range(n):
queens.append(random.randint(0,n-1))
return queens

# displays the n-queens board as indicated by list qs
# example for 4-queens: [0,2,0,3] prints out as
#
# Q _ Q _
# _ _ _ _
# _ Q _ _
# _ _ _ Q ... notice queens conflicts that need repair ...

def show_nqueens(qs):
for row in range(len(qs)):
for col in range(len(qs)):
if row == qs[col]:
print 'Q',
else:
print '_',
print ""
return


# prints out the coordinates [row,col] for each queen on the board
# represented by list qs;

def queens_coords(qs):
coords = []
for col in range(len(qs)):
coords.append([qs[col],col])
return coords

# how many queens are in row k?
# = how many times does k appear in qs list?
# for the queens board [0,2,0,3] and each row, you get
#
# queens in row 0: 2
# queens in row 1: 0
# queens in row 2: 1
# queens in row 3: 1

def queens_in_row(k,qs):
return qs.count(k)


# returns how many queens are in diagonals 1 and 2 going through cell (row,col);
# also counts the queen that may be sitting in exactly (row,col)

#NEW VERSION 2/16, 7pm
def queens_in_diags1(row,col,qs):
k = 0
for r in range(len(qs)):
for c in range(len(qs)):
if (row - r) == (col - c):
if qs[c] == r:
k += 1
return k

def queens_in_diags2(row,col,qs):
k = 0
for r in range(len(qs)):
for c in range(len(qs)):
if (row - r) == -(col - c):
if qs[c] == r:
k += 1
return k

# combines diagonal conflicts and removes double counting for fields
# that have a queen;

def queens_in_diags(row,col,qs):
qd1 = queens_in_diags1(row,col,qs)
qd2 = queens_in_diags2(row,col,qs)
if qs[col] == row:
return qd1 + qd2 - 1
else:
return qd1 + qd2

# WARNING: When using any of the queens_in_diagsX functions, be aware of
# which one(s) have double counts (with likely need to compensate later) in
# their return values and which one(s) do not; both variants can be used, but
# you need to be aware of the implications of your choice down the line; program
# accordingly;


# given a column number (col) and the queens board qs, returns the
# number of conflicts in this colum for each row;
# for column 0 of queens board [0,2,0,3] which prints as
#
# Q _ Q _
# _ _ _ _
# _ Q _ _
# _ _ _ Q
#
# you get conflicts [3,1,2,2,] in rows 0..3 of col 0;

# NEW VERSION, 02/16, 7:14pm

def column_conflicts(col,qs):
rowsqs = map(lambda r: queens_in_row(r,qs),range(len(qs)))
#print rowsqs
diags1qs = map(lambda r: queens_in_diags1(r,col,qs), range(len(qs)))
#print diags1qs
diags2qs = map(lambda r: queens_in_diags2(r,col,qs), range(len(qs)))
#print diags2qs
confs = map(lambda x,y,z: x+y+z, rowsqs,diags1qs,diags2qs)
#print confs
# if a queen sits in field [r,col], then this field has been
# counted as threatened 3x by this one queen: via the row, and
# via both diagonals; adjust by subtracting 2; one queen is one "threat" to its own field;
for r in range(len(qs)):
if qs[col] == r:
confs[r] -= 2
#print confs
return confs

# returns the row index of the field in column numbered 'col' that is
# threatened by the smallest number of queens; for the above example
# with conflicts [3,1,2,2,] in rows 0..3 of col 0, this function returns
# row index 1 (field (1,0), row 1 in col 0, is threatened by the minimal number
# of queens, here: 1;
def min_conflicts_row(col,qs):
conf = column_conflicts(col,qs)

#<<<< COMPLETE (1)

return # replace as appropriate

# change qs so that the queen in column col is in row 'row; unless it already is
def column_repair(col,row,qs):
qs[col] = row
return

# returns True if there is at most one queen in every row and diagonal; False
# otherwise; (by virtue of the representation, it is a given that each column contains
# a single queen; thus no need to test for columns);
def queens_solved(qs):

#<<<<< COMPLETE (2)

return # replace as appropriate
  
def hrepair(queens):
step = 1
print "Heuristic Repair of:\n"
show_nqueens(queens)
print "\n\n"
while True:
if queens_solved(queens):
# <<<<< COMPLETE (3)
pass # place holder; remove/replace as appropriate
  
if step > MAXSTEPS:
# <<<<< COMPLETE (4)
pass # place holder; remove/replace as appropriate
  
for i in range(len(queens)):
targetrow = min_conflicts_row(i,queens)
print "[%d] col %d: min conflicts in row %d" % (step,i,targetrow)

# <<<<< COMPLETE (5)
  
step += 1
return


'''
# uncomment for later testing and demo ...

def main():
n = int(raw_input("How many queens: "))
qs = random_queens(n)
hrepair(qs)

if __name__ == "__main__":
main()
  
'''

Homework Answers

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
It is N queens problem please complete it use this code //*************************************************************** // D.S. Malik //...
It is N queens problem please complete it use this code //*************************************************************** // D.S. Malik // // This class specifies the functions to solve the n-queens // puzzle. //*************************************************************** class nQueensPuzzle { public: nQueensPuzzle(int queens = 8);     //constructor     //Postcondition: noOfSolutions = 0; noOfQueens = queens;     // queensInRow is a pointer to the array     // that store the n-tuple.     // If no value is specified for the parameter queens,     // the default value, which is 8, is assigned to it. bool...
import pandas as pd import numpy as np import matplotlib.pyplot as plt mtcars = pd.read_csv("mtcars.csv", index_col...
import pandas as pd import numpy as np import matplotlib.pyplot as plt mtcars = pd.read_csv("mtcars.csv", index_col = 0) mtcars x = mtcars["hp"] y = mtcars["mpg"] plt.plot(x,y,"*") plt.grid(True) plt.xlabel("Horse Power") plt.ylabel("Miles per Gallon") plt.show() def standardize(x): return (x-x.mean())/x.std(), x.mean(), x.std() x, muX, stdX = standardize(x) y, muY, stdY = standardize(y) if len(x.shape) == 1: num_var = 1 else: num_var = x.shape[1] beta0 = np.random.rand() beta1 = np.random.rand() def predict(x, beta0, beta1): return beta0 + beta1*x def loss(y, ypred): return np.mean((y-ypred)**2)/2 def...
## We will be simulating the ideal solution to Hanoi's tower problem. ## The discs will...
## We will be simulating the ideal solution to Hanoi's tower problem. ## The discs will be numers from 0 to n-1, with the larger number being the smaller disc. ## each rod with discs will be encoded by a list, from bottom to top. For example, a rod with discs 0, 3, 5 will be encoded as [0,3,5] ## current configuration of rods will be encoded as a list of 3 lists. For example, starting state with 3 discs...
convert code from python to cpp L = [2,7,4,19,45,16,9,13,8,69,55,11,23,98,14,5,1,3]   #Merging function def merge(M,N): merging_list = []...
convert code from python to cpp L = [2,7,4,19,45,16,9,13,8,69,55,11,23,98,14,5,1,3]   #Merging function def merge(M,N): merging_list = []        //create empty list to merge the lists M and N if not M:                //if M is empty list, m = 0                //set m = 0 else: m = len(M)             //otherwise, set m = len(M) if not N:                //if N is empty list, n = 0       ...
Python Blackjack Game Here are some special cases to consider. If the Dealer goes over 21,...
Python Blackjack Game Here are some special cases to consider. If the Dealer goes over 21, all players who are still standing win. But the players that are not standing have already lost. If the Dealer does not go over 21 but stands on say 19 points then all players having points greater than 19 win. All players having points less than 19 lose. All players having points equal to 19 tie. The program should stop asking to hit if...
Program will allow anywhere between 1 and 6 players (inclusive). Here is what your output will...
Program will allow anywhere between 1 and 6 players (inclusive). Here is what your output will look like: Enter number of players: 2 Player 1: 7S 5D - 12 points Player 2: 4H JC - 14 points Dealer: 10D Player 1, do you want to hit? [y / n]: y Player 1: 7S 5D 8H - 20 points Player 1, do you want to hit? [y / n]: n Player 2, do you want to hit? [y / n]: y...
Homework Draw class diagrams for your HW4 - the Tetris Game shown below: Part 1: UML...
Homework Draw class diagrams for your HW4 - the Tetris Game shown below: Part 1: UML As a review, Here are some links to some explanations of UML diagrams if you need them. • https://courses.cs.washington.edu/courses/cse403/11sp/lectures/lecture08-uml1.pdf (Links to an external site.) • http://creately.com/blog/diagrams/class-diagram-relationships/ (Links to an external site.) • http://www.cs.bsu.edu/homepages/pvg/misc/uml/ (Links to an external site.) However you ended up creating the UML from HW4, your class diagram probably had some or all of these features: • Class variables: names, types, and...
I NEED TASK 3 ONLY TASK 1 country.py class Country:     def __init__(self, name, pop, area, continent):...
I NEED TASK 3 ONLY TASK 1 country.py class Country:     def __init__(self, name, pop, area, continent):         self.name = name         self.pop = pop         self.area = area         self.continent = continent     def getName(self):         return self.name     def getPopulation(self):         return self.pop     def getArea(self):         return self.area     def getContinent(self):         return self.continent     def setPopulation(self, pop):         self.pop = pop     def setArea(self, area):         self.area = area     def setContinent(self, continent):         self.continent = continent     def __repr__(self):         return (f'{self.name} (pop:{self.pop}, size: {self.area}) in {self.continent} ') TASK 2 Python Program: File: catalogue.py from Country...
please use linux/unix command terminal to complete, step 1 1-create a new directory named by inlab4...
please use linux/unix command terminal to complete, step 1 1-create a new directory named by inlab4 enter directory inlab4 create a new file named by reverse.c with the following contents and then close the file: /*reverse.c */ #include <stdio.h> reverse(char *before, char *after); main() { char str[100]; /*Buffer to hold reversed string */ reverse("cat", str); /*Reverse the string "cat" */ printf("reverse(\"cat\")=%s\n", str); /*Display result */ reverse("noon", str); /*Reverse the string "noon" */ printf("reverse(\"noon\")=%s\n", str); /*Display result */ } reverse(char *before,...
You can complete this assignment individually or as a group of two people. In this assignment...
You can complete this assignment individually or as a group of two people. In this assignment you will create a ​​Sorted Singly-Linked List​ that performs basic list operations using C++. This linked list should not allow duplicate elements. Elements of the list should be of type ‘ItemType’. ‘ItemType’ class should have a private integer variable with the name ‘value’. Elements in the linked list should be sorted in the ascending order according to this ‘value’ variable. You should create a...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT