-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMutation.java
More file actions
84 lines (77 loc) · 2.04 KB
/
Mutation.java
File metadata and controls
84 lines (77 loc) · 2.04 KB
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
import java.util.Random;
/*********************************************************
* Filename: Mutation.java
* Author: Charles Walker
* Created: 11/08/23
* Modified: 12/1/23
* Updated the class to perform as intended and added the setFirstChild method to get the index of the first child from the
* Crossover class.
*
* Purpose:
* Rolls a user chosen chance for each offspring to mutate. If selected,
* the class selects two random genes of the offspring's chromosome to
* swap.
*
* Attributes:
* -chance: double
* -firstChild: int
*
* Methods:
* +selectChild(): void
* +mutateGenes(): void
* +mutateGenesTest(): void
* +setChance(double): void
* +getChance(): int
* +setFirstChild(double): void
*
*********************************************************/
public class Mutation {
private int chance;
private int firstChild;
public void selectChild(Individual[] population) {
int num = 0;
for (int i = firstChild; i < population.length; i++) {
Random ran = new Random();
num = ran.nextInt(100) + 1;
if (num <= chance) {
population[i].setChromosome(mutateGenes(population[i].getChromosome()));
}
}
}
public int[] mutateGenes(int[] chrom) {
int gene1;
int gene2;
int temp;
Random ran1 = new Random();
Random ran2 = new Random();
gene1 = ran1.nextInt(48)+1;
gene2 = ran2.nextInt(48)+1;
temp = chrom[gene1];
chrom[gene1] = chrom[gene2];
chrom[gene2] = temp;
return chrom;
}
public int[] mutateGenesTest(int[] chrom) {
int gene1;
int gene2;
int temp;
Random ran1 = new Random();
Random ran2 = new Random();
gene1 = ran1.nextInt(48)+1;
gene2 = ran2.nextInt(48)+1;
System.out.println("Swapping gene "+chrom[gene1]+" in index "+gene1+" with gene "+chrom[gene2]+" in index "+gene2+".");
temp = chrom[gene1];
chrom[gene1] = chrom[gene2];
chrom[gene2] = temp;
return chrom;
}
public void setChance(double value) {
chance = (int) value;
}
public int getChance() {
return chance;
}
public void setFirstChild(double value) {
firstChild = (int)value;
}
}