-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMutation.java
79 lines (70 loc) · 2.34 KB
/
Mutation.java
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
package zad2;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Random;
public class Mutation {
private static final Random random = new Random();
public static int[] mutate(int[] child) {
int first = random.nextInt(child.length), second = random.nextInt(child.length);
while(first == second) {
second = random.nextInt(child.length);
}
int temp = child[first];
child[first] = child[second];
child[second] = temp;
return child;
}
public static int[] mutate(int[] child, int lenToChange) {
int maxStartInx = child.length - lenToChange;
int startInx = random.nextInt(maxStartInx);
for (int i = lenToChange - 1; i > 0; i--) {
int j = random.nextInt(i+1);
int temp = child[i + startInx];
child[i + startInx] = child[j + startInx];
child[j + startInx] = temp;
}
return child;
}
}
class MutationTest {
@Test
public void mutationTest1() {
var child = new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
var childCopy = child.clone();
var mutated = Mutation.mutate(child);
int sumChange = 0;
int sumChangeCopy = 0;
for (int i = 0; i < child.length; i++) {
if(child[i] != mutated[i]) {
sumChange += 1;
}
if(childCopy[i] != mutated[i]) {
sumChangeCopy += 1;
}
}
Assertions.assertEquals(0, sumChange);
Assertions.assertEquals(2, sumChangeCopy);
}
@Test
public void mutationTest2() {
var child = new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
var childCopy = child.clone();
var mutated = Mutation.mutate(child, 4);
int sumChange = 0;
int sumChangeCopy = 0;
for (int i = 0; i < child.length; i++) {
if(child[i] != mutated[i]) {
sumChange += 1;
}
if(childCopy[i] != mutated[i]) {
sumChangeCopy += 1;
}
}
System.out.println(Arrays.toString(childCopy));
System.out.println(Arrays.toString(child));
System.out.println(Arrays.toString(mutated));
Assertions.assertEquals(0, sumChange);
Assertions.assertTrue(sumChangeCopy <= 4);
}
}