Advertisement
jordan83221

GA

Aug 8th, 2018
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.17 KB | None | 0 0
  1. local next=next
  2.  
  3. local password = "test"
  4. local points={}
  5.  
  6. --Brain--
  7. local point={
  8.   new=function(self)
  9.     return {passwordtest="", fitnessLevel=0}
  10.   end
  11. }
  12.  
  13. local calculator={
  14.   calculateFitness=function(self, point)
  15.     --Create fitness Variable
  16.     local fitnessLevelz=0
  17.     --Separate word based on single characters
  18.     local letters=SplitString(point.passwordtest);
  19.     local passLetters=SplitString(password); -- Separate letters of password
  20.     --Now compare
  21.     for i,v in next,letters do
  22.       if passLetters[i]==v then--Compare password letter to random word letter
  23.         fitnessLevelz=fitnessLevelz+1
  24.       end
  25.     end
  26.     return fitnessLevelz
  27.   end,
  28.   randPW=function(self, point, length)
  29.     local index, pw, rnd = 0, ""
  30.     local chars = {
  31.         "abcdefghijklmnopqrstuvwxyz"
  32.     }
  33.     repeat
  34.         index = index + 1
  35.         rnd = math.random(chars[index]:len())
  36.         if math.random(2) == 1 then
  37.             pw = pw .. chars[index]:sub(rnd, rnd)
  38.         else
  39.             pw = chars[index]:sub(rnd, rnd) .. pw
  40.         end
  41.         index = index % #chars
  42.     until pw:len() >= length
  43.     point.passwordtest=pw;
  44.     local fl = self:calculateFitness(point);
  45.     point.fitnessLevel = fl
  46.     return pw
  47.   end
  48. }
  49. --[[Helpful Functions]]--
  50. function SplitString(str)
  51.   local letters={}
  52.   for i = 1,str:len() do
  53.     table.insert(letters,str:sub(i,i))
  54.   end
  55.   return letters
  56. end
  57.  
  58. --Population
  59.  
  60. local population={
  61.   generationNum=1,
  62.   start=function(self)
  63.     self.generationNum=self.generationNum+1
  64.     for i = 1,100 do
  65.       local newPoint = point:new()
  66.       table.insert(points, newPoint)
  67.       calculator:randPW(newPoint,4)
  68.     end
  69.     return self
  70.   end,
  71.   GetBest=function(self)
  72.     local fitnesslevels={}
  73.     for i,v in next, points do
  74.       table.insert(fitnesslevels,v.fitnessLevel);
  75.     end
  76.     table.sort(fitnesslevels);
  77.     local best={}
  78.     for i,v in next,fitnesslevels do
  79.       if v==fitnesslevels[#fitnesslevels] then
  80.         table.insert(best,v)
  81.       end
  82.     end
  83.     return best
  84.   end
  85. }
  86. for i = 1,100 do
  87.   population:start();
  88.   local bestPoints = population:GetBest();
  89.   print(unpack(bestPoints))
  90. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement