diff --git a/.gitignore b/.gitignore index 2f506c0..0990376 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ .RData .Rhistory +*.swp diff --git a/ue02/a2/ea_crossover.R b/ue02/a2/ea_crossover.R index e69de29..f21a2a3 100644 --- a/ue02/a2/ea_crossover.R +++ b/ue02/a2/ea_crossover.R @@ -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)) +} diff --git a/ue02/a2/experiment.R b/ue02/a2/experiment.R new file mode 100644 index 0000000..ecc8655 --- /dev/null +++ b/ue02/a2/experiment.R @@ -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) +} diff --git a/ue02/a2/individuals.pdf b/ue02/a2/individuals.pdf new file mode 100644 index 0000000..b0e3b2f Binary files /dev/null and b/ue02/a2/individuals.pdf differ