Browse Source

ue2 a2

master
Tom 3 years ago
parent
commit
801d428399
4 changed files with 96 additions and 0 deletions
  1. +1
    -0
      .gitignore
  2. +54
    -0
      ue02/a2/ea_crossover.R
  3. +41
    -0
      ue02/a2/experiment.R
  4. BIN
      ue02/a2/individuals.pdf

+ 1
- 0
.gitignore View File

@ -1,2 +1,3 @@
.RData .RData
.Rhistory .Rhistory
*.swp

+ 54
- 0
ue02/a2/ea_crossover.R View File

@ -0,0 +1,54 @@
ea.crossover <- function(p1, p2, mask) {
ch1 <- c()
ch2 <- c()
for(i in 1:length(mask)) {
if(mask[i]) {
ch1[i] <- p2[i]
ch2[i] <- p1[i]
} else {
ch1[i] <- p1[i]
ch2[i] <- p2[i]
}
}
return(list(ch1, ch2))
}
indiv2int <- function(indiv) {
res <- 0
indiv_rev <- rev(indiv)
for(i in 1:length(indiv)) {
res <- res + indiv_rev[i] * 2^(i-1)
}
return(res)
}
ea.n_point_mask <- function(len, n_points) {
return( function() {
points <- sort(c(c(1), sample(2:(len - 1), n_points), c(len)))
val <- TRUE
mask <- c()
for(i in 1:(length(points) - 1)) {
mask <- append(mask, rep(val, points[i + 1] - points[i]))
if(val) {val <- FALSE} else {val <- TRUE}
}
return(mask)
})
}
ea.uniform_mask <- function(len) {
return(function() sample(c(TRUE, FALSE), len, replace=TRUE))
}
rand.individual <- function(len) {
return(sample(c(0,1), len, replace=TRUE))
}

+ 41
- 0
ue02/a2/experiment.R View File

@ -0,0 +1,41 @@
source("ea_crossover.R")
n_point_crossover <- function(p1, p2, mask_gen, iterations) {
indivs <- c()
for(i in 1:iterations) {
children <- ea.crossover(p1, p2, mask_gen())
p1 <- children[[1]]
p2 <- children[[2]]
indivs <- append(indivs, c(indiv2int(p1), indiv2int(p2)))
}
return(indivs)
}
experiment <- function() {
p1 <- rand.individual(10)
p2 <- rand.individual(10)
iterations <- 10000
tmp_indivs <- n_point_crossover(p1, p2, ea.n_point_mask(10, 1), iterations)
df <- data.frame(i=1:iterations, individual=tmp_indivs)
df["crossover"] <- "1 point"
tmp_indivs <- n_point_crossover(p1, p2, ea.n_point_mask(10, 2), iterations)
df <- rbind(df, data.frame(i=(iterations+1):(2*iterations)
,individual=tmp_indivs
,crossover="2 point"))
tmp_indivs <- n_point_crossover(p1, p2, ea.uniform_mask(10), iterations)
df <- rbind(df, data.frame(i=(2*iterations+1):(3*iterations)
,individual=tmp_indivs
,crossover="uniform"))
return(df)
}

BIN
ue02/a2/individuals.pdf View File


Loading…
Cancel
Save