Main.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #define SIZE 9
  4. #define SUM ((SIZE * (SIZE * SIZE + 1)) / 2)
  5. int data[SIZE][SIZE];
  6. void init() {
  7. for(int x = 0; x < SIZE; x++) {
  8. for(int y = 0; y < SIZE; y++) {
  9. data[x][y] = y * SIZE + x + 1;
  10. }
  11. }
  12. }
  13. int errorFactor(int e) {
  14. return e * e;
  15. }
  16. int getFitness() {
  17. int fitness = 0;
  18. for(int y = 0; y < SIZE; y++) {
  19. int sum = 0;
  20. for(int x = 0; x < SIZE; x++) {
  21. sum += data[x][y];
  22. }
  23. fitness += errorFactor(sum - SUM);
  24. }
  25. for(int x = 0; x < SIZE; x++) {
  26. int sum = 0;
  27. for(int y = 0; y < SIZE; y++) {
  28. sum += data[x][y];
  29. }
  30. fitness += errorFactor(sum - SUM);
  31. }
  32. int diaA = 0;
  33. int diaB = 0;
  34. for(int i = 0; i < SIZE; i++) {
  35. diaA += data[i][i];
  36. diaB += data[i][(SIZE - 1) - i];
  37. }
  38. fitness += errorFactor(diaA - SUM);
  39. fitness += errorFactor(diaB - SUM);
  40. return fitness;
  41. }
  42. void print() {
  43. printf("Fitness: %d\n", getFitness());
  44. for(int y = 0; y < SIZE; y++) {
  45. for(int x = 0; x < SIZE; x++) {
  46. printf("%2d ", data[x][y]);
  47. }
  48. putchar('\n');
  49. }
  50. putchar('\n');
  51. }
  52. void swap(int x1, int y1, int x2, int y2) {
  53. int tmp = data[x1][y1];
  54. data[x1][y1] = data[x2][y2];
  55. data[x2][y2] = tmp;
  56. }
  57. void randSwap() {
  58. swap(rand() % SIZE, rand() % SIZE, rand() % SIZE, rand() % SIZE);
  59. }
  60. void randSwaps(int swaps) {
  61. for(int i = 0; i < swaps; i++) {
  62. swap(rand() % SIZE, rand() % SIZE, rand() % SIZE, rand() % SIZE);
  63. }
  64. }
  65. int main() {
  66. init();
  67. for(int k = 0; k < 2000; k++) {
  68. for(int i = 0; i < 1000000; i++) {
  69. int oldFitness = getFitness();
  70. int x1 = rand() % SIZE;
  71. int y1 = rand() % SIZE;
  72. int x2 = rand() % SIZE;
  73. int y2 = rand() % SIZE;
  74. swap(x1, y1, x2, y2);
  75. int newFitness = getFitness();
  76. if(newFitness == 0) {
  77. break;
  78. }
  79. if(newFitness >= oldFitness) {
  80. swap(x1, y1, x2, y2);
  81. }
  82. }
  83. if(getFitness() == 0) {
  84. print();
  85. }
  86. randSwaps(400);
  87. }
  88. return 0;
  89. }