Initial data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 72d218235f
commit f23f22d71c
199087 changed files with 3378941 additions and 0 deletions

View file

@ -0,0 +1,52 @@
set.seed(1234, kind="Mersenne-Twister")
## Easier if the string is a character vector
target <- unlist(strsplit("METHINKS IT IS LIKE A WEASEL", ""))
charset <- c(LETTERS, " ")
parent <- sample(charset, length(target), replace=TRUE)
mutaterate <- 0.01
## Number of offspring in each generation
C <- 100
## Hamming distance between strings normalized by string length is used
## as the fitness function.
fitness <- function(parent, target) {
sum(parent == target) / length(target)
}
mutate <- function(parent, rate, charset) {
p <- runif(length(parent))
nMutants <- sum(p < rate)
if (nMutants) {
parent[ p < rate ] <- sample(charset, nMutants, replace=TRUE)
}
parent
}
evolve <- function(parent, mutate, fitness, C, mutaterate, charset) {
children <- replicate(C, mutate(parent, mutaterate, charset),
simplify=FALSE)
children <- c(list(parent), children)
children[[which.max(sapply(children, fitness, target=target))]]
}
.printGen <- function(parent, target, gen) {
cat(format(i, width=3),
formatC(fitness(parent, target), digits=2, format="f"),
paste(parent, collapse=""), "\n")
}
i <- 0
.printGen(parent, target, i)
while ( ! all(parent == target)) {
i <- i + 1
parent <- evolve(parent, mutate, fitness, C, mutaterate, charset)
if (i %% 20 == 0) {
.printGen(parent, target, i)
}
}
.printGen(parent, target, i)

View file

@ -0,0 +1,34 @@
# Setup
set.seed(42)
target= unlist(strsplit("METHINKS IT IS LIKE A WEASEL", ""))
chars= c(LETTERS, " ")
C= 100
# Fitness function; high value means higher fitness
fitness= function(x){
sum(x == target)
}
# Mutate function
mutate= function(x, rate= 0.01){
idx= which(runif(length(target)) <= rate)
x[idx]= replicate(n= length(idx), expr= sample(x= chars, size= 1, replace= T))
x
}
# Evolve function
evolve= function(x){
parents= rep(list(x), C+1) # Repliction
parents[1:C]= lapply(parents[1:C], function(x) mutate(x)) # Mutation
idx= which.max(lapply(parents, function(x) fitness(x))) # Selection
parents[[idx]]
}
# Initialize first parent
parent= sample(x= chars, size= length(target), replace= T)
# Main program
while (fitness(parent) < fitness(target)) {
parent= evolve(parent)
cat(paste0(parent, collapse=""), "\n")
}