Advertisement
finalshare

Untitled

Apr 14th, 2017
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <time.h>
  5.  
  6. char *list;
  7. const char *line = "--------+--------------------\n";
  8. int len = 0;
  9.  
  10. int irand(int n)
  11. {
  12. int r, rand_max = RAND_MAX - (RAND_MAX % n);
  13. do { r = rand(); } while(r >= rand_max);
  14. return r / (rand_max / n);
  15. }
  16.  
  17. char* get_digits(int n, char *ret)
  18. {
  19. int i, j;
  20. char d[] = "123456789";
  21.  
  22. for (i = 0; i < n; i++) {
  23. j = irand(9 - i);
  24. ret[i] = d[i + j];
  25. if (j) d[i + j] = d[i], d[i] = ret[i];
  26. }
  27. return ret;
  28. }
  29.  
  30. #define MASK(x) (1 << (x - '1'))
  31. int score(const char *digits, const char *guess, int *cow)
  32. {
  33. int i, bits = 0, bull = *cow = 0;
  34.  
  35. for (i = 0; guess[i] != '\0'; i++)
  36. if (guess[i] != digits[i])
  37. bits |= MASK(digits[i]);
  38. else ++bull;
  39.  
  40. while (i--) *cow += ((bits & MASK(guess[i])) != 0);
  41.  
  42. return bull;
  43. }
  44.  
  45. void pick(int n, int got, int marker, char *buf)
  46. {
  47. int i, bits = 1;
  48. if (got >= n)
  49. strcpy(list + (n + 1) * len++, buf);
  50. else
  51. for (i = 0; i < 9; i++, bits *= 2) {
  52. if ((marker & bits)) continue;
  53. buf[got] = i + '1';
  54. pick(n, got + 1, marker | bits, buf);
  55. }
  56. }
  57.  
  58. void filter(const char *buf, int n, int bull, int cow)
  59. {
  60. int i = 0, c;
  61. char *ptr = list;
  62.  
  63. while (i < len) {
  64. if (score(ptr, buf, &c) != bull || c != cow)
  65. strcpy(ptr, list + --len * (n + 1));
  66. else
  67. ptr += n + 1, i++;
  68. }
  69. }
  70.  
  71. void game(const char *tgt, char *buf)
  72. {
  73. int i, p, bull, cow, n = strlen(tgt);
  74.  
  75. for (i = 0, p = 1; i < n && (p *= 9 - i); i++);
  76. list = malloc(p * (n + 1));
  77.  
  78. pick(n, 0, 0, buf);
  79. for (p = 1, bull = 0; n - bull; p++) {
  80. strcpy(buf, list + (n + 1) * irand(len));
  81. bull = score(tgt, buf, &cow);
  82.  
  83. printf("Guess %2d| %s (from: %d)\n"
  84. "Score | %d bull, %d cow\n%s",
  85. p, buf, len, bull, cow, line);
  86.  
  87. filter(buf, n, bull, cow);
  88. }
  89. }
  90.  
  91. int main(int c, char **v)
  92. {
  93. int n = c > 1 ? atoi(v[1]) : 4;
  94.  
  95. char secret[10] = "", answer[10] = "";
  96. srand(time(0));
  97.  
  98. printf("%sSecret | %s\n%s", line, get_digits(n, secret), line);
  99. game(secret, answer);
  100.  
  101. return 0;
  102. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement