-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutil.py
90 lines (66 loc) · 2.64 KB
/
util.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import nonogram
from numpy import random
def printSol(sol, constraints):
rules, nLines, nColumns, nPoints, nPopulation = constraints
print(nonogram.Game(nLines, nColumns, sol.points))
def readRulesFile(fileName):
with open(fileName) as rulesFile:
readingLines = True
lines = []
columns = []
for fileLine in rulesFile:
if(fileLine == '-\n'):
readingLines = False
continue
rulesInFileLine = [[int(rule) for rule in fileLine.split()]]
if(readingLines):
lines += rulesInFileLine
else:
columns += rulesInFileLine
return nonogram.Rules(lines=lines, columns=columns)
def createConstraints(rules, nPopulation):
nLines = len(rules.lines)
nColumns = len(rules.columns)
nPoints = 0
# Count total number of points
for line in rules.lines:
for rule in line:
nPoints += rule
return (rules, nLines, nColumns, nPoints, nPopulation)
def fitness(sol, constraints):
rules, nLines, nColumns, nPoints, nPopulation = constraints
# Count how many rules it is following
count = 0
game = nonogram.Game(nLines, nColumns, sol)
board = sol
# Count in lines in ascending order
for lineIndex in range(nLines):
rulesQtt = len(rules.lines[lineIndex])
columnIndex = 0
ruleIndex = 0
while columnIndex < nColumns or ruleIndex < rulesQtt:
countSegment = 0
currRule = rules.lines[lineIndex][ruleIndex] if ruleIndex < rulesQtt else 0
while columnIndex < nColumns and not board[lineIndex*nColumns + columnIndex]:
columnIndex += 1
while columnIndex < nColumns and board[lineIndex*nColumns + columnIndex]:
countSegment += 1
columnIndex += 1
count -= abs(countSegment - currRule)
ruleIndex += 1
# Count in columns in ascending order
for columnIndex in range(nColumns):
rulesQtt = len(rules.columns[columnIndex])
lineIndex = 0
ruleIndex = 0
while lineIndex < nLines or ruleIndex < rulesQtt:
countSegment = 0
currRule = rules.columns[columnIndex][ruleIndex] if ruleIndex < rulesQtt else 0
while lineIndex < nLines and not board[lineIndex*nColumns + columnIndex]:
lineIndex += 1
while lineIndex < nLines and board[lineIndex*nColumns + columnIndex]:
countSegment += 1
lineIndex += 1
count -= abs(countSegment - currRule)
ruleIndex += 1
return count