-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBitArrayChromosome.hs
More file actions
72 lines (59 loc) · 1.68 KB
/
BitArrayChromosome.hs
File metadata and controls
72 lines (59 loc) · 1.68 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
-- CPSC 312 - 2018 - Genetic Algorithm Library
module BitArrayChromosome (
Chromosome,
Bin,
--chromosome2lst,
mkChromosome,
mkData,
getFst,
getSnd,
mutategene
) where
-- defines single chromosome data, being either 0 or 1
data Bin = Bin Int
deriving (Show, Eq)
-- insures that the Chromosome only has values 0 or 1
mkBin :: Int -> Bin
mkBin n
| n == 1 || n == 0 = Bin n
| otherwise = error "Invalid Integer"
-- defines the whole chromosome
-- chromosome is a list of 6 chromosomes
type Chromosome = [Bin]
-- ensures that chromosome has a list lenght of 6
mkChromosome :: [Bin] -> Chromosome
mkChromosome list
| length list == 6 = list
| otherwise = error "Invalid length"
-- easy constructor function for chromosome
mkData :: [Int] -> Chromosome
mkData lst = mkChromosome (map mkBin lst)
{-
chromosome2lst :: Chromosome -> [Bin]
chromosome2lst (Chromosome lst) = lst
-}
-- test cases
-- mkData [1,1,1,1,1,1]
-- mkData [1,1,1,1,0,1]
-- mkData [1,1,1,1,0,0,0]
-- mkData [1,1,1,1,0,2]
-- gets the first half of the chromosome
getFst :: Chromosome -> [Bin]
getFst chromosome = fst (splitAt 3 chromosome)
-- gets the second half of the chromosome
getSnd :: Chromosome -> [Bin]
getSnd chromosome = snd (splitAt 3 chromosome)
-- test cases
-- foo = mkData[1,1,1,0,0,0]
-- getFst foo
-- getSnd foo
mutategene :: Chromosome -> Int -> Chromosome
mutategene ch i = replaceNth ch newv i
where
newv = if ch!!i == Bin 0 then Bin 1 else Bin 0
-- Replace the nth element in a list by newVal
replaceNth :: [a] -> a -> Int -> [a]
replaceNth [] _ _ = []
replaceNth (x:xs) newVal n
| n == 0 = newVal:xs
| otherwise = x:replaceNth xs newVal (n-1)