SimpleMutation.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. """Mutation implementation for binary solution, swap two bits randomly from solution
  2. """
  3. # main imports
  4. import random
  5. import sys
  6. # module imports
  7. from .Mutation import Mutation
  8. from ...solutions.BinarySolution import BinarySolution
  9. from ...solutions.Solution import Solution
  10. class SimpleMutation(Mutation):
  11. """Mutation implementation for binary solution, swap two bits randomly from solution
  12. Attributes:
  13. kind: {KindOperator} -- specify the kind of operator
  14. """
  15. def apply(self, _solution):
  16. """Create new solution based on solution passed as parameter
  17. Args:
  18. _solution: {Solution} -- the solution to use for generating new solution
  19. Returns:
  20. {Solution} -- new generated solution
  21. """
  22. size = _solution.size
  23. firstCell = 0
  24. secondCell = 0
  25. # copy data of solution
  26. currentData = _solution.data.copy()
  27. while firstCell == secondCell:
  28. firstCell = random.randint(0, size - 1)
  29. secondCell = random.randint(0, size - 1)
  30. temp = currentData[firstCell]
  31. # swicth values
  32. currentData[firstCell] = currentData[secondCell]
  33. currentData[secondCell] = temp
  34. # create solution of same kind with new data
  35. return globals()[type(_solution).__name__](currentData, size)