Advertisement
Guest User

Untitled

a guest
Jun 16th, 2019
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.72 KB | None | 0 0
  1. public void ConvertByteArrayToCoefficients(BitArray array)
  2. {
  3. Coefficients.Clear(); //Coefficients are stored in List<double>
  4.  
  5. for (int i = 0; i < _degree + 1; i++)
  6. {
  7. var arr = array.ToByteArray();
  8. double value = BitConverter.ToDouble(array.ToByteArray(), i * sizeof(double));
  9.  
  10. Coefficients.Add(value);
  11. }
  12. }
  13.  
  14. public BitArray GetAllCoefficientsInBytes()
  15. {
  16. BitArray bytes = new BitArray(0);
  17.  
  18. for (int i = 0; i < Coefficients.Count; i++) //append is extension method
  19. bytes = bytes.Append(new BitArray(BitConverter.GetBytes(Coefficients[i])));
  20.  
  21. return bytes;
  22. }
  23.  
  24. public void Mutate(int percentageChance)
  25. {
  26. BitArray bytes = GetAllCoefficientsInBytes();
  27.  
  28. for (int i = 0; i < bytes.Length; i++)
  29. {
  30. if (_randomProvider.Next(0, 100) < percentageChance)
  31. {
  32. if (bytes.Get(i))
  33. bytes[i] = false;
  34. else
  35. bytes[i] = true;
  36. }
  37. }
  38.  
  39. ConvertByteArrayToCoefficients(bytes);
  40. }
  41.  
  42. private void CrossoverSingle(Polynomial poly1, Polynomial poly2)
  43. {
  44. int cutPosition = _randomProvider.Next(1, (_degreeOfPolynomial + 1) * sizeof(double) * 8);
  45.  
  46. BitArray bytesOne = poly1.GetAllCoefficientsInBytes();
  47. BitArray bytesTwo = poly2.GetAllCoefficientsInBytes();
  48.  
  49. for (int i = bytesOne.Length-1; i >= cutPosition; i--)
  50. {
  51. bool bitOne = bytesOne[i];
  52. bool bitTwo = bytesTwo[i];
  53.  
  54. if (bitOne != bitTwo)
  55. {
  56. bytesOne[i] = bitTwo;
  57. bytesTwo[i] = bitOne;
  58. }
  59. }
  60.  
  61. _crossoveredChildren.Add(new Polynomial(_randomProvider, _degreeOfPolynomial, bytesOne));
  62. _crossoveredChildren.Add(new Polynomial(_randomProvider, _degreeOfPolynomial, bytesTwo));
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement