I've been struggling to find the right logic for my sudoku solver. So far I've created a function to take (x,y) coordinates and the number and check if it is a legal move.
Though I don't understand how I can iterate through the grid replacing every 0 with a legal number, then go back and fix numbers that make the solve incorrect.
For example sometimes I will be left with 0's on the grid because some numbers can no longer be played. I took a deeper look at it and realized that numbers played previously in the same row were legal but ruined the puzzle. Instead, if those numbers were a bit higher the puzzle would be solved.
I understand backtracking would be my friend here but, I have no clue on how to implement it. So far here is what I have.
solve.py
import numpy as np
import time
class sodoku:
def __init__(self,grid,boxRange):
self.grid = grid
self.boxRange = boxRange
def show(self):
for row in self.grid:
print(row)
def solve(self):
def possible(num,x,y):
def box(x,y):
board = np.array(self.grid)
result = {}
size = 3
for i in range(len(board) // size):
for j in range(len(board) // size):
values = board[j * size:(j + 1) * size, i * size:(i + 1) * size]
result[i * size + j + 1] = values.flatten()
if y <= 2 and x <= 2:
squareBox = result[1]
if (y <= 5 and y > 2) and x <= 2:
squareBox = result[2]
if (y <= 8 and y > 5) and x <= 2:
squareBox = result[3]
if (y <= 2 ) and (x <= 5 and x > 2):
squareBox = result[4]
if (y <= 5 and y > 2)and (x <= 5 and x > 2):
squareBox = result[5]
if (y <= 8 and y > 5)and (x <= 5 and x > 2):
squareBox = result[6]
if (y <= 2) and (x <= 8 and x > 5):
squareBox = result[7]
if (y <= 5 and y > 2)and (x <= 8 and x > 5):
squareBox = result[8]
if (y <= 8 and y > 5)and (x <= 8 and x > 5):
squareBox = result[9]
return squareBox
row = self.grid[y]
column= [r[x] for r in self.grid]
square = box(x,y)
if (num not in row) and (num not in column) and (num not in square):
return True
else:
return False
y = 0
for row in self.grid:
x = 0
for number in row:
if number == 0:
for i in range(1,10):
if possible(i,x,y):
row[x] = i
elif i == 9 and possible(i,x,y) == False: pass
#what would I do here now
x += 1
y += 1
boxRange = "3x3"
bxd = []
with open('board.txt', 'r') as f:
for line in f:
line = line.strip()
line = line.split(' ')
bLine = [int(x) for x in line]
bxd.append(bLine)
# brd = [[3,0,0,2],[0,4,1,0],[0,3,2,0],[4,0,0,1]]
brd = sodoku(bxd,boxRange)
brd.show()
brd.solve()
print('-----Solved------')
brd.show()
board.txt
5 3 0 0 7 0 1 0 0
6 0 0 1 9 5 0 0 0
0 9 8 0 0 0 0 6 0
8 0 0 0 6 0 0 0 3
4 0 0 8 0 3 0 0 1
7 0 0 0 2 0 0 0 6
0 6 0 0 0 0 2 8 0
0 0 0 4 1 9 0 0 5
0 0 0 0 8 0 0 7 9
Recursive pseudocode backtracing sudoku solver:
#solve will return a solved board, or None if it fails
def solve(board):
#case 1: board is solved
if board.is_solved: #simple check for leftover empty spaces
return board #board is solved. unzip the call stack
pos = board.next_empty_space()
valid = [i for i in range(1,10) if board.is_valid(pos, i)]
#case 2: not solved and no more valid moves
if not valid:
return None #no valid moves left
new_board = copy(board) #don't step on the original data in case this isn't the solution
for value in valid:
new_board[pos] = value
result = solve(new_board)
#case 3: one of the valid moves led to a valid solution
if result is not None: #we found a fully solved board
return result #here's where we unzip the call stack
#case 4: none of the valid moves led to a valid solution
return None #none of the valid moves panned out
Basically you consider each empty space on the board as a branch in a tree, and sub-branches from each branch you insert a new number which is currently valid at that point in the tree. If you get to the end of a branch, and there are no more valid moves left (sub-branches) you have either successfully filled in all the blank spaces or one of the numbers is wrong. When None gets returned, and execution goes back to the caller (up a frame in the call stack), the local position in the for loop going over valid moves is what "remembers" where you're at, and what the next possible valid move should be. It's basically a depth-first tree search algorithm for a correct board state.
Related
I was given the following task:
Richard likes to ask his classmates questions like the following:
4 x 4 x 3 = 13
In order to solve this task, his classmates have to fill in the missing arithemtic operators (+, -, *, /) that the created equation is true. For this example the correct solution would be 4 * 4 - 3. Write a piece of code that creates similar questions to the one above. It should comply the following rules:
The riddles should only have one solution (e.g. not 3 x 4 x 3 = 15, which has two solutions)
The operands are numbers between 1-9
The solution is a positive integer
Point before dashes is taken into account (e.g. 1 + 3 * 4 = 13)
Every interim result is an integer (e.g. not 3 / 2 * 4 = 6)
Create riddles up to 15 arithmetic operands, which follow these rules.
My progress so far:
import random
import time
import sys
add = lambda a, b: a + b
sub = lambda a, b: a - b
mul = lambda a, b: a * b
div = lambda a, b: a / b if a % b == 0 else 0 / 0
operations = [(add, '+'),
(sub, '-'),
(mul, '*'),
(div, '/')]
operations_mul = [(mul, '*'),
(add, '+'),
(sub, '-'),
(div, '/')]
res = []
def ReprStack(stack):
reps = [str(item) if type(item) is int else item[1] for item in stack]
return ''.join(reps)
def Solve(target, numbers):
counter = 0
def Recurse(stack, nums):
global res
nonlocal counter
valid = True
end = False
for n in range(len(nums)):
stack.append(nums[n])
remaining = nums[:n] + nums[n + 1:]
pos = [position for position, char in enumerate(stack) if char == operations[3]]
for j in pos:
if stack[j - 1] % stack[j + 1] != 0:
valid = False
if valid:
if len(remaining) == 0:
# Überprüfung, ob Stack == target
solution_string = str(ReprStack(stack))
if eval(solution_string) == target:
if not check_float_division(solution_string)[0]:
counter += 1
res.append(solution_string)
if counter > 1:
res = []
values(number_ops)
target_new, numbers_list_new = values(number_ops)
Solve(target_new, numbers_list_new)
else:
for op in operations_mul:
stack.append(op)
stack = Recurse(stack, remaining)
stack = stack[:-1]
else:
if len(pos) * 2 + 1 == len(stack):
end = True
if counter == 1 and end:
print(print_solution(target))
sys.exit()
stack = stack[:-1]
return stack
Recurse([], numbers)
def simplify_multiplication(solution_string):
for i in range(len(solution_string)):
pos_mul = [position for position, char in enumerate(solution_string) if char == '*']
if solution_string[i] == '*' and len(pos_mul) > 0:
ersatz = int(solution_string[i - 1]) * int(solution_string[i + 1])
solution_string_new = solution_string[:i - 1] + solution_string[i + 1:]
solution_string_new_list = list(solution_string_new)
solution_string_new_list[i - 1] = str(ersatz)
solution_string = ''.join(str(x) for x in solution_string_new_list)
else:
return solution_string
return solution_string
def check_float_division(solution_string):
pos_div = []
solution_string = simplify_multiplication(solution_string)
if len(solution_string) > 0:
for i in range(len(solution_string)):
pos_div = [position for position, char in enumerate(solution_string) if char == '/']
if len(pos_div) == 0:
return False, pos_div
for j in pos_div:
if int(solution_string[j - 1]) % int(solution_string[j + 1]) != 0:
# Float division
return True, pos_div
else:
# No float division
return False, pos_div
def new_equation(number_ops):
equation = []
operators = ['+', '-', '*', '/']
ops = ""
if number_ops > 1:
for i in range(number_ops):
ops = ''.join(random.choices(operators, weights=(4, 4, 4, 4), k=1))
const = random.randint(1, 9)
equation.append(const)
equation.append(ops)
del equation[-1]
pos = check_float_division(equation)[1]
if check_float_division(equation):
if len(pos) == 0:
return equation
for i in pos:
equation[i] = ops
else:
'''for i in pos:
if equation[i+1] < equation[i-1]:
while equation[i-1] % equation[i+1] != 0:
equation[i+1] += 1'''
new_equation(number_ops)
else:
print("No solution with only one operand")
sys.exit()
return equation
def values(number_ops):
target = 0
equation = ''
while target < 1:
equation = ''.join(str(e) for e in new_equation(number_ops))
target = eval(equation)
numbers_list = list(
map(int, equation.replace('+', ' ').replace('-', ' ').replace('*', ' ').replace('/', ' ').split()))
return target, numbers_list
def print_solution(target):
equation_encrypted_sol = ''.join(res).replace('+', '○').replace('-', '○').replace('*', '○').replace('/', '○')
print("Try to find the correct operators " + str(equation_encrypted_sol) + " die Zahl " + str(
target))
end_time = time.time()
print("Duration: ", end_time - start_time)
input(
"Press random button and after that "ENTER" in order to generate result")
print(''.join(res))
if __name__ == '__main__':
number_ops = int(input("Number of arithmetic operators: "))
# number_ops = 10
target, numbers_list = values(number_ops)
# target = 590
# numbers_list = [9, 3, 5, 3, 5, 2, 6, 3, 4, 7]
start_time = time.time()
Solve(target, numbers_list)
Basically it's all about the "Solve(target, numbers)" method, which returns the correct solution. It uses Brute-Force in order to find that solution. It receives an equation and the corresponding result as an input, which has been generated in the "new_equation(number_ops)" method before. This part is working fine and not a big deal. My main issue is the "Solve(target, numbers)" method, which finds the correct solution using a stack. My aim is to make that program as fast as possible. Currently it takes about two hours until an arithmetic task with 15 operators has been found, which follows the rules above. Is there any way to make it faster or maybe another approach to the problem besides Brute-Force? I would really appreciate your help :)
This is mostly brute force but it only takes a few seconds for a 15 operation formula.
In order to check the result, I first made a solve function (recursive iterator) that will produce the solutions:
def multiplyDivide(numbers):
if len(numbers) == 1: # only one number, output it directly
yield numbers[0],numbers
return
product,n,*numbers = numbers
if product % n == 0: # can use division.
for value,ops in multiplyDivide([product//n]+numbers):
yield value, [product,"/",n] + ops[1:]
for value,ops in multiplyDivide([product*n]+numbers):
yield value, [product,"*",n] + ops[1:]
def solve(target,numbers,canGroup=True):
*others,last = numbers
if not others: # only one number
if last == target: # output it if it matches target
yield [last]
return
yield from ( sol + ["+",last] for sol in solve(target-last,others)) # additions
yield from ( sol + ["-",last] for sol in solve(target+last,others)) # subtractions
if not canGroup: return
for size in range(2,len(numbers)+1):
for value,ops in multiplyDivide(numbers[-size:]): # multiplicative groups
for sol in solve(target,numbers[:-size]+[value],canGroup=False):
yield sol[:-1] + ops # combined multipicative with rest
The solve function recurses through the numbers building an addition or subtraction with the last number and recursing to solve a smaller problem with the adjusted target and one less number.
In addition to the additions and subtraction, the solve function groups the numbers (from the end) into consecutive multiplications/divisions and processes them (recursing into solve) using the resulting value that will have calculation precedence over additions/subtractions.
The multiplyDivide function (also a recursive generator) combines the group of numbers it is given with multiplications and divisions performed from left to right. Divisions are only added when the current product divided by the additional number produces an integer intermediate result.
Using the solve iterator, we can find a first solution and know if there are more by iterating one additional time:
def findOper(S):
expression,target = S.split("=")
target = int(target.strip())
numbers = [ int(n.strip()) for n in expression.split("x") ]
iSolve = solve(target,numbers)
solution = next(iSolve,["no solution"])
more = " and more" * bool(next(iSolve,False))
return " ".join(map(str,solution+ ["=",target])) + more
Output:
print(findOper("10 x 5 = 2"))
# 10 / 5 = 2
print(findOper("10 x 5 x 3 = 6"))
# 10 / 5 * 3 = 6
print(findOper("4 x 4 x 3 = 13"))
# 4 * 4 - 3 = 13
print(findOper("1 x 3 x 4 = 13"))
# 1 + 3 * 4 = 13
print(findOper("3 x 3 x 4 x 4 = 25"))
# 3 * 3 + 4 * 4 = 25
print(findOper("2 x 6 x 2 x 4 x 4 = 40"))
# 2 * 6 * 2 + 4 * 4 = 40 and more
print(findOper("7 x 6 x 2 x 4 = 10"))
# 7 + 6 * 2 / 4 = 10
print(findOper("2 x 2 x 3 x 4 x 5 x 6 x 3 = 129"))
# 2 * 2 * 3 + 4 * 5 * 6 - 3 = 129
print(findOper("1 x 2 x 3 x 4 x 5 x 6 = 44"))
# 1 * 2 + 3 * 4 + 5 * 6 = 44
print(findOper("1 x 2 x 3 x 4 x 5 x 6 x 7 x 8 x 9 x 8 x 7 x 6 x 5 x 4 x 1= 1001"))
# 1 - 2 - 3 + 4 * 5 * 6 * 7 / 8 * 9 + 8 * 7 - 6 + 5 + 4 + 1 = 1001 and more
print(findOper("1 x 2 x 3 x 4 x 5 x 6 x 7 x 8 x 9 x 8 x 7 x 6 x 5 x 4 x 1= 90101"))
# no solution = 90101 (15 seconds, worst case is not finding any solution)
In order to create a single solution riddle, the solve function can be converted to a result generator (genResult) that will produce all possible computation results. This will allow us to find a result that only has one combination of operations for a given list of random numbers. Given that the multiplication of all numbers is very likely to be a unique result, this will converge rapidly without having to go through too many random lists:
import random
def genResult(numbers,canGroup=True):
*others,last = numbers
if not others:
yield last
return
for result in genResult(others):
yield result - last
yield result + last
if not canGroup: return
for size in range(2,len(numbers)+1):
for value,_ in multiplyDivide(numbers[-size:]):
yield from genResult(numbers[:-size]+[value],canGroup=False)
def makeRiddle(size=5):
singleSol = []
while not singleSol:
counts = dict()
numbers = [random.randint(1,9) for _ in range(size)]
for final in genResult(numbers):
if final < 0 : continue
counts[final] = counts.get(final,0) + 1
singleSol = [n for n,c in counts.items() if c==1]
return " x ".join(map(str,numbers)) + " = " + str(random.choice(singleSol))
The reason we have to loop for singleSol (single solution results) is that there are some cases where even the product of all numbers is not a unique solution. For example: 1 x 2 x 3 = 6 could be the product 1 * 2 * 3 = 6 but could also be the sum 1 + 2 + 3 = 6. There aren't too many of those cases but it's still a possibility, hence the loop. In a test generating 1000 riddles with 5 operators, this occurred 4 times (e.g. 4 x 1 x 1 x 4 x 2 has no unique solution). As you increase the size of the riddle, the occurrence of these no-unique-solution patterns becomes more frequent (e.g. 6 times generating 20 riddles with 15 operators).
output:
S = makeRiddle(15) # 7 seconds
print(S)
# 1 x 5 x 2 x 5 x 8 x 2 x 3 x 4 x 1 x 2 x 8 x 9 x 7 x 3 x 2 = 9715
print(findOper(S)) # confirms that there is only one solution
# 1 * 5 * 2 * 5 * 8 * 2 * 3 * 4 - 1 + 2 + 8 * 9 + 7 * 3 * 2 = 9715
I am trying to arrange slashes in print statement to Graph like this
Below is skeleton of my code
y = input("Enter numbers (seperated by space): ")
y_arr = []
y_list = y.split()
for n in range(len(y_list)):
y_arr.append(int(y_list[n]))
space_no = 0
for x in range(len(y_arr)):
value = y_arr[x]
for z in range(value):
if (x%2 == 0):
print (" "*space_no,"\\")
space_no += 1
else:
print (" "*space_no,"/")
space_no += 1
Input statement take numbers and put it into list, then the slashes are generated based on the value of list item. For exa: if value is 2 then 2 slashes will be printed. Even index values go up, odd index values go down. Print statement is printing every character in new line but I want to arrange them like shown in graph.
How to achieve this?
code edited to Python 3
That sounds like homework, but here it is.
y_list = '0 3 1 2 3 6 2 3 6 2 3'.split()
y_arr = []
for n in range(len(y_list)):
y_arr.append(int(y_list[n]))
def cumulative(lists):
cu_list = []
length = len(lists)
cu_list = [sum(lists[0:x:1]) for x in range(0, length+1)]
return cu_list[1:]
space_up = 0
space_dn = 0
last_idx = -1
lines = ['']*max(cumulative([-x if i%2 == 0 else x for i,x in enumerate(y_arr)]))
for x in range(len(y_arr)):
value = y_arr[x]
for z in range(value):
if (x%2 == 0):
lines[last_idx] += (" "*space_dn+"\\")
space_dn = len(lines[last_idx])-len(lines[last_idx-1])
last_idx -= 1
space_up = 0
else:
last_idx += 1
lines[last_idx] += (" "*space_up+"/")
try:
space_up = len(lines[last_idx])-len(lines[last_idx+1])
except IndexError:
pass
space_dn = 0
print('\n'.join(lines[::-1]))
Given a square matrix, calculate the absolute difference between the sums of its diagonals.
For example, the square matrix is shown below:
1 2 3
4 5 6
9 8 9
The left-to-right diagonal =1 + 5 + 9 = 15 . The right to left diagonal =3+5+9=17 . Their absolute difference is |15-17|=2.
Function description
Complete the diagonalDifference function in the editor below. It must return an integer representing the absolute diagonal difference.
diagonalDifference takes the following parameter:
arr: an array of integers .
Input Format
The first line contains a single integer,n , the number of rows and columns in the matrix arr.
Each of the next n lines describes a row,arr[i] , and consists of n space-separated integers arr[i][j] .
Sample Input
3
11 2 4
4 5 6
10 8 -12
Sample Output
15
My code:
def diagonalDifference(arr):
i = 0
j = 0
left = 0
right = 0
for x in range(arr+1):
left += arr[0 + i][0 + j]
right += arr[0 + i][n - j]
i += 1
j += 1
return abs(left - right)
Here's my code. I don't know what's wrong. Please help.
The Question is "Diagonal Difference" on Hackerrank.
EDIT: Second attempt
def diagonalDifference(arr):
left = 0
right = 0
for x in range(len(arr)):
left += arr[0+x][0+x]
right += arr[0+x][len(arr)-x]
return abs(left-right)
I get following error:
right += arr[0+x][len(arr)-x]
IndexError: list index out of range
You cannot access len(arr)-x - for x == 0 this is IndexError :
def diagonalDifference(arr):
left = 0
right = 0
for x in range(len(arr)):
left += arr[0+x][0+x]
right += arr[0+x][len(arr)-x]
return abs(left-right)
arr = [[1,2],[3,4]]
len_arr = len(arr) # len(arr) is 2, you index into arr[0][2-0] fox x==0
# but arr only has arr[0][0] and arr[0][1] for x == 0
You need to sum over:
k[0][0], k[1][1], k[2][2], ..., k[n-1][n-1] where n = len(k) for the forward diag
and
k[0][n-1-0], k[1][n-1-1], k[2][n-1-2], ..., k[n-1][n-1-(n-1)] for the backward diag
Codewise:
def diag (data, reverse=False):
ld = len(data)
if reverse:
return sum(data[i][ld-i-1] for i in range(ld))
else:
return sum(data[i][i] for i in range(ld))
k = [[0,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20],[0,22,23,24,25]]
print (diag(k)) # 64
print(diag(k,True)) # 44
def absDiagDiff(data):
return abs(diag(data)-diag(data,True))
print(absDiagDiff(k)) # 20
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'diagonalDifference' function below.
#
# The function is expected to return an INTEGER.
# The function accepts 2D_INTEGER_ARRAY arr as parameter.
#
def diagonalDifference(arr):
diag1=0
diag2=0
for x in range(int(len(arr))):
y=list(reversed(list(range(len(arr[x])))))
diag1+=arr[x][x]
diag2+=arr[x][y[x]]
return abs(diag1-diag2)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input().strip())
arr = []
for _ in range(n):
arr.append(list(map(int, input().rstrip().split())))
result = diagonalDifference(arr)
fptr.write(str(result) + '\n')
fptr.close()
If that can help, here's how I would of done it :
n = int(input())
array = []
total1 = 0
total2 = 0
index = 0
for i in range(n):
array = [[] for n in range(n)]
for arrays in array:
arrays += map(int,input().split())
if len(arrays) != n:
print(f"Error, need to be {n} by {n}")
if index == 0:
for arrays in array:
total1 += arrays[index]
index += 1
elif index == n:
for arrays in array:
total2 += arrays[index-1]
index -= 1
print(abs(total1-total2))
I'm still fairly new to programming and am currently attempting to generate a magic square based on the users input. I have managed to create some sort of abomination that works fine for a 3x3 square. The problem I'm having is that because I randomly generate a square without checking if the combination has been used before, anything bigger than 3x3 takes a huge amount of time to compute. Are there any modifications I can make to speed up the process? Apologies if I haven't formatted correctly.
Thanks in advance!
import random
import math
'''Checks if the diagonals add up to the magic sum (calculated below).'''
def diagonal_check(bList, point):
reversedDiagonalCount = 0
diagonalCount = 0
if point == 0:
for diagonal in range(magicSquareSize):
diagonalCount += bList[diagonal][diagonal]
else:
for reversedDiagonal in range(magicSquareSize):
reversedDiagonalCount += bList[-(reversedDiagonal+1)]
[reversedDiagonal]
if diagonalCount == magicNumber or reversedDiagonalCount == magicNumber:
return True
else:
return False
'''Iterates through column and row number "x" to see if both add up to the
magic sum.'''
def check_magic_sum(aList, x):
columnCount = 0
rowCount = 0
for columnNumber in range(magicSquareSize):
columnCount += aList[columnNumber][x]
if columnCount == magicNumber:
for rowNumber in range(magicSquareSize):
rowCount += aList[x][rowNumber]
print(columnCount, rowCount)
if columnCount == magicNumber and rowCount == magicNumber:
return True
else:
return False
'''Once initiated, created a randomly generated n x n matrix of numbers.'''
def create_square():
for number in range(1, magicSquareSize**2 + 1):
numberList.append(number)
for row in range(magicSquareSize):
currentList = []
magicNumberCount = magicNumber
magicSquareSizeCount = magicSquareSize
while len(currentList) < magicSquareSizeCount:
rowEntry = random.choice(numberList)
numberList.remove(rowEntry)
currentList.append(rowEntry)
magicNumberCount -= rowEntry
magicSquare.append(currentList)
'''User inputs the grid size they would like, a magic number is then
calculated for this value.'''
magicSquareSize = int(input('Please enter a number, "n" to generate an "n x
n" magic square: '))
magicNumber = int((magicSquareSize/2) * (2+(magicSquareSize**2 - 1)))
'''Initiates an empty list to hold the magic square and the numbers used in
it.'''
numberList = []
magicSquare = []
create_square()
'''Checks magic square to see if it is valid, if not, creates another
randomly generated square and checks again.'''
while True:
validSquare = 0
for checkNumber in range(magicSquareSize):
numberCheck = check_magic_sum(magicSquare, checkNumber)
if numberCheck == True:
validSquare += 1
if checkNumber == 0 or checkNumber == magicSquareSize-1:
isDiagonalGood = diagonal_check(magicSquare, checkNumber)
if isDiagonalGood == True:
validSquare += 1
if validSquare == magicSquareSize + 2:
break
else:
magicSquare = []
create_square()
'''Prints each element in the magicSquare list one by one to display a
roughly square shape.'''
for line in range(magicSquareSize):
print(magicSquare[line])
The magic square problem is NP-hard so it will be time-consuming to find a solution for N>=4. The problem can be formulated as a CSP (constraint satisfaction problem) and with constraint package we can try to solve it for a general N like the following, you may try to see if this approach is faster:
N = 4 #5 # number of rows / columns
n = N**2 # number of cells
s = n*(n+1)//6 # sum of each row
from constraint import *
p = Problem()
p.addVariables(range(n), range(1, n+1))
p.addConstraint(AllDifferentConstraint(), range(n))
p.addConstraint(ExactSumConstraint(s), [k*(N+1) for k in range(N)])
p.addConstraint(ExactSumConstraint(s), [(k+1)*(N-1) for k in range(N)])
for row in range(N):
p.addConstraint(ExactSumConstraint(s),
[row*N+i for i in range(N)])
for col in range(N):
p.addConstraint(ExactSumConstraint(s),
[col+N*i for i in range(N)])
sols = p.getSolutions()
for s in sols:
for row in range(N):
for col in range(N):
print s[row*N+col],
print
print
For N=3 it is very fast and immediately prints all possible solutions:
6 7 2
1 5 9
8 3 4
6 1 8
7 5 3
2 9 4
8 1 6
3 5 7
4 9 2
8 3 4
1 5 9
6 7 2
4 3 8
9 5 1
2 7 6
4 9 2
3 5 7
8 1 6
2 7 6
9 5 1
4 3 8
2 9 4
7 5 3
6 1 8
So, I'm generating an array of spaces, which have the property that they can be either red or black. However, I want to prevent red from being enclosed by black. I have some examples to show exactly what I mean:
0 0 0 0 0 0 0 1
0 1 0 0 0 0 1 0
1 0 1 0 0 0 0 1
0 1 0 0 1 1 1 0
0 0 0 0 1 0 1 0
1 1 1 0 1 1 1 0
0 0 1 0 0 0 0 0
0 0 1 0 0 0 0 0
If red is 0 and black is 1, then this example contains four enclosures, all of which I want to avoid when I generate the array. The inputs I have are the size of the array and the number of 1s I can generate.
How would I go about doing this?
Does this code fits well for you?
Basically I fill a matrix from left to right, from top to bottom.
When I have to assign 0 or 1 to a cell, I check (north and west) if adding a 1 could enclose a 0; in this case I put a 0, else a random 0 or 1.
import sys, random
n = int(sys.argv[1])
m = int(sys.argv[2])
# fill matrix with zeroes
matrix = [[0 for _ in xrange(m)] for _ in xrange(n)]
# functions to get north, south, west and east
# cell wrt this cell.
# If we are going out of bounds, we suppose the matrix
# is sorrounded by 1s.
def get_n(r, c):
if r <= 0: return 1
return matrix[r - 1][c]
def get_s(r, c):
if r >= n - 1: return 1
return matrix[r + 1][c]
def get_w(r, c):
if c <= 0: return 1
return matrix[r][c - 1]
def get_e(r, c):
if c >= m - 1: return 1
return matrix[r][c + 1]
# Checks if the cell is already enclosed by 3 1s.
def enclosed(r, c):
enclosing = get_n(r, c) + get_s(r, c) + get_w(r, c) + get_e(r, c)
if (enclosing > 3): raise Exception('Got a 0 enclosed by 1s')
return enclosing == 3
for r in xrange(n):
for c in xrange(m):
# check west and north
if enclosed(r, c - 1) or enclosed(r - 1, c):
matrix[r][c] = 0
else:
matrix[r][c] = random.randint(0, 1)
print str(matrix[r][c]) + ' ',
print ''
Sample run: python spaces.py 10 10
So you can do the following:
Fill array with zeroes
Randomly select a point
If the condition holds, flip color
Repeat from step 2 or exit
The condition holds for all-zeros array. It is hold on any iteration. So, by induction, it is also true for the final array.
In the step 4 you can decide whether to stop or continue by doing, say N=a*b*1000 iterations or whether the ratio red/black is close to 1. In both cases, the result would be slightly biased since you start from all zeros.
Now, what is the condition. You have to ensure that all black points connected and all red points connected as well. In other words, there's maximum 2 connected clusters. Flipping a color could create more connected clusters, so you flip only when the its number is one or two. You can do the check quite efficiently using Union-Find algorithm, described here.
Edit: if however you want to permit black points to be surrounded by red ones but not vice-versa, you may change the condition to have any number of black clusters but only 0 or 1 of red clusters.
This would be a possible way to check the condition:
def: findStart(myArr):
for i in range(len(myArr)):
for j in range(len(myArr[0])):
if(myArr[i][j] == 0):
return (i,j)
def: checkCon(myArr, number_Ones):
width = len(myArr[0])
height = len(myArr)
pen = [] #A list of all points that are waiting to get a visit
vis = [] #A list of all points that are already visited
x = findStart(myArr)
while(len(pen) != 0): #Visit points as long as there are points left
p = pen.pop() #Pick a point to visit
if p in vis:
#do nothing since this point already was visited
else:
vis.append(p)
x,y = p
#A vertical check
if(x == 0 and myArr[x+1][y] == 0):
pen.append((x+1,y))
elif(x == (height-1) and myArr[x-1][y] == 0):
pen.append((x-1,y))
else:
if(myArr[x-1][y] == 0 and x-1 >= 0):
pen.append((x-1,y))
if(myArr[x+1][y] == 0):
pen.append((x+1,y))
#A horizontal check
if(y == 0 and myArr[x][y+1] == 0):
pen.append((x,y+1))
elif(y == (width-1) and myArr[x][y-1] == 0):
pen.append((x,y-1))
else:
if(myArr[x][y+1] == 0):
pen.append((x,y+1))
if(myArr[x][y-1] == 0 and y-1 >= 0):
pen.append((x,y-1))
print((height*width-number_Ones) == len(vis)) #if true, alle Zeros are connected and not enclosed
To clarify this is just a concept to check the condition. The idea is to visit all connected zeros and see if there are any left (that are not connected). If that is the case, there are some enclosed.
This method also doesn't work when the 1's form a frame around the matrix like this:
1 1 1 1
1 0 0 1
1 0 0 1
1 1 1 1
Again, just a concept :)
The problem has two parts actually. Generating the board state, and then checking if it is correct. I realised that checking the correctness was actually worse than just being sure correct states were always generated. This is what I did:
Note that I have defined self.WallSpaces to be an array equal in length to the height of my array, comprised of integers with the number of bits equal to the width of my array. self.Width and self.Height provide the end indices for the array. Basically, Intersects works by checking all the spaces surrounding a point for 1s, except the direction the space was "built from" (see below) and returning True if any of these are the edge of the array or a 1.
def Intersects(self, point, direction):
if (point[0] > 0):
if (direction != [1, 0] and self.WallSpaces[point[0] - 1] & (1 << point[1]) != 0):
return True
if (point[1] == 0 or self.WallSpaces[point[0] - 1] & (1 << (point[1] - 1)) != 0):
return True
if (point[1] == self.Width or self.WallSpaces[point[0] - 1] & (1 << (point[1] + 1)) != 0):
return True
else:
return True
if (point[0] < self.Height):
if (direction != [-1, 0] and self.WallSpaces[point[0] + 1] & (1 << point[1]) != 0):
return True
if (point[1] == 0 or self.WallSpaces[point[0] + 1] & (1 << (point[1] - 1)) != 0):
return True
if (point[1] == self.Width or self.WallSpaces[point[0] + 1] & (1 << (point[1] + 1)) != 0):
return True
else:
return True
if (point[1] == 0 or (direction != [0, 1] and self.WallSpaces[ point[0] ] & (1 << (point[1] - 1)) != 0)):
return True
if (point[1] == self.Width or (direction != [0, -1] and self.WallSpaces[ point[0] ] & (1 << (point[1] + 1)) != 0)):
return True
return False
The directions GPacW.Left, GPacW.Right, GPackW.Up, and GPacW.Down represent the cardinal directions for movement. This function works by constructing "walls" in the array from random points, which can turn in random directions, ending when they have intersected twice.
def BuildWalls(self):
numWalls = 0
directions = [ [GPacW.Left, GPacW.Right], [GPacW.Up, GPacW.Down] ]
start = [ random.randint(0, self.Height), random.randint(0, self.Width) ]
length = 0
horizontalOrVertical = random.randint(0, 1)
direction = random.randint(0, 1)
d = directions[horizontalOrVertical][direction]
intersected = False
while (numWalls < self.Walls):
while (start == [0, 0] or start == [self.Height, self.Width] or self.Intersects(start, d)):
start = [ random.randint(0, self.Height), random.randint(0, self.Width) ]
if (length == 0):
horizontalOrVertical = not horizontalOrVertical
direction = random.randint(0, 1)
length = random.randint(3, min(self.Height, self.Width))
d = directions[horizontalOrVertical][direction]
if (self.WallSpaces[ start[0] ] & (1 << start[1] ) == 0):
self.WallSpaces[ start[0] ] |= 1 << start[1]
numWalls += 1
length -= 1
if (0 <= (start[0] + d[0]) <= self.Height and 0 <= (start[1] + d[1]) <= self.Width):
start[0] += d[0]
start[1] += d[1]
else:
start = [0,0]
if (self.Intersects(start, d)):
if (intersected):
intersected = False
start = [0,0]
length = 0
else:
intersected = True
return