-
Notifications
You must be signed in to change notification settings - Fork 1
/
GA_integer_factorization.py
145 lines (98 loc) · 2.28 KB
/
GA_integer_factorization.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
import random
N = 85
pop = []
pop_size = 10
dna_size = 2
def fitness(dna):
p = int(dna[0])
q = int(dna[1])
if p == 1 or q == 1:
return 10000
else:
return abs(N - p * q)
def zeroes():
dna = []
p = ""
q = ""
for i in range(dna_size):
p += '0'
q += '0'
dna.append(p)
dna.append(q)
return dna
def randomize():
dna = []
p = ""
q = ""
for i in range(dna_size):
p += str(random.randint(0, 9))
q += str(random.randint(0, 9))
dna.append(p)
dna.append(q)
return dna
def crossover(p1, p2):
child = zeroes()
mid = int(random.randint(0, dna_size))
for j in range(2):
c = list(child[j])
pa1 = list(p1[j])
pa2 = list(p2[j])
for i in range(dna_size):
if i > mid:
c[i] = pa1[i]
else:
c[i] = pa2[i]
child[j] = "".join(c)
return child
def mutate(dna, rate):
for i in range(len(dna)):
d = list(dna[i])
for j in range(dna_size):
if random.random() < rate:
d[j] = str(random.randint(0, 9))
dna[i] = "".join(d)
dna.append(fitness(dna))
return dna
def init_pop(pop):
for i in range(pop_size):
pop.append(randomize())
for i in pop:
i.append(fitness(i))
def select(pop):
s = 0
scores = []
for i in pop:
s += i[2]
for i in pop:
scores.append(i[2]/s)
for i in pop:
select = 0
selector = random.random()
while selector > 0:
selector -= scores[select]
select +=1
select-=1
return pop[select]
def ev(pop):
fits = []
for p in pop:
fits.append(p[2])
index = fits.index(min(fits))
fittest = pop[index]
p = int(fittest[0])
q = int(fittest[1])
n = p*q
f = min(fits)
print("Best Fitness = " + str(f) + " (p = " + str(p) + "; q = " + str(q) + ")")
if n == N:
print("Solution p = " + str(p) + "; q = " + str(q))
return True
init_pop(pop)
stop = False
while not stop:
stop = ev(pop)
for k in range(len(pop)):
pA = select(pop)
pB = select(pop)
ch = mutate(crossover(pA, pB), 0.08)
pop[k] = ch