Skip to content

Commit 49a34d7

Browse files
committed
finished and tested crossover
1 parent f6d6b8d commit 49a34d7

File tree

1 file changed

+25
-4
lines changed

1 file changed

+25
-4
lines changed

crossover.py

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,10 @@
11
import random
22

3-
A = [1, 2, 3, 4, 5, 6, 7, 8]
4-
B = [2, 4, 6, 8, 7, 5, 3, 1]
53

64
def cycle_crossover(A, B):
75
n = len(A)
86
child = [None] * n
97
case = random.choice([0,1])
10-
case = 0
118
if(case == 0):
129
# the first cycle
1310
child[0] = A[0]
@@ -33,9 +30,33 @@ def cycle_crossover(A, B):
3330

3431
print(child)
3532

36-
33+
if(case == 1):
34+
# the first cycle
35+
child[0] = B[0]
36+
cycle = [B[0]]
37+
n = A.index(B[0])
38+
child[n] = B[n]
39+
cycle.append(B[n])
40+
while(cycle[-1] != cycle[0]):
41+
n = A.index(cycle[-1])
42+
child[n] = B[n]
43+
cycle.append(B[n])
3744

45+
i = child.index(None)
46+
child[i] = A[i]
47+
cycle = [A[i]]
48+
n = B.index(A[i])
49+
child[n] = A[n]
50+
cycle.append(A[n])
51+
while(cycle[-1] != cycle[0]):
52+
n = B.index(cycle[-1])
53+
child[n] = A[n]
54+
cycle.append(A[n])
55+
56+
print(child)
3857

58+
A = [1, 2, 3, 4, 5, 6, 7, 8]
59+
B = [2, 4, 6, 8, 7, 5, 3, 1]
3960
cycle_crossover(A, B)
4061

4162

0 commit comments

Comments
 (0)