rm(list = ls()) Nvar <- 10 Nsol <- 150 Ngen <- 100 Nrun <- 10 Cg <- 0.55 Cp <- 0.75 Cw <- 0.95 genBest<- 1 gBest <- 1 LB <- -5.12 UB <- 5.12 X <- matrix(0, Nsol, Nvar) pX <- matrix(0, Nsol, Nvar) f <- matrix(0, Nsol, 1) pF <- matrix(0, Nsol, 1) fitness_funtion = function(SOL){ top = 25 + sum(round(X[SOL,])) } par(mfrow = c(Nrun/5 ,3)) for (run in 1:Nrun){ stm <- proc.time() for ( sol in 1:Nsol){ X [sol, ] <- runif(Nvar)*(UB-LB)+LB pX[sol, ] <- X[sol,] pF[sol,] = f [sol,] <- fitness_funtion(sol) if (f[sol,] < f[gBest,]) gBest <- sol } for (gen in 1:Ngen){ for (sol in 1:Nsol){ for (var in 1:Nvar){ random_number = runif(1) if (random_number < Cg){ X[sol,var] <- pX[gBest,var] }else{ if (random_number< Cp){ X[sol,var] <- pX[sol,var] }else{ if (random_number > Cw){ X[sol,var] <- runif(1)*(UB-LB)+LB } } } } f[sol,] <- fitness_funtion(sol) if (f[sol, ] < pF[sol, ]) { pF[sol, ] <- f[sol, ] pX[sol, ] <- X[sol, ] if (f[sol, ] < pF[gBest, ]){ gBest <- sol genBest <- gen } } } plot(gen, pF[gBest,], type = "p", col = "red", xlab = "", ylab = "", xlim = c(0,Ngen), ylim = c(-30,0)) par(new=TRUE) } title(c("run=", run, "pF(gBest)=", pF[gBest,])) end_time <- proc.time() - stm cat('RunTime=' ,end_time[3],' ' ,'BestSol=' ,pF[gBest,] ,' ', 'genBest=' , genBest, sep="") cat("\n") box() }