fork download
  1.  
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <stdbool.h>
  6.  
  7. int char_cmp(const void *pa, const void *pb)
  8. {
  9. const char *a = pa;
  10. const char *b = pb;
  11.  
  12. return *a - *b;
  13. }
  14.  
  15. bool partial_anagram(const char *aa, const char *bb)
  16. {
  17. char A[64];
  18. char B[64];
  19.  
  20. const char *a = strcpy(A, aa);
  21. const char *b = strcpy(B, bb);
  22.  
  23. qsort(A, strlen(A), 1, char_cmp);
  24. qsort(B, strlen(B), 1, char_cmp);
  25.  
  26. while (*b) {
  27. while (*a && *a < *b) a++;
  28.  
  29. if (*a != *b) return false;
  30. a++;
  31. b++;
  32. }
  33.  
  34. return true;
  35. }
  36.  
  37. static const char *bool_str(bool x)
  38. {
  39. return x ? "true" : "false";
  40. }
  41.  
  42. int test(const char *a, const char *b, bool expected)
  43. {
  44. bool have = partial_anagram(a, b);
  45.  
  46. printf("\"%s\" matches \"%s\": %s", a, b, bool_str(have));
  47.  
  48. if (have != expected) {
  49. printf(", expected %s", bool_str(expected));
  50. }
  51.  
  52. puts(".");
  53.  
  54. return (have != expected);
  55. }
  56.  
  57. int main(void)
  58. {
  59. int misses = test("try", "try", true)
  60. + test("try", "rty", true)
  61. + test("try", "tray", false)
  62. + test("try", "", true)
  63. + test("try", "y", true)
  64. + test("try", "t", true)
  65. + test("try", "z", false)
  66. + test("try", "rytt", false)
  67. + test("try", "yt", true)
  68. + test("try", "yurt", false)
  69. + test("tree", "eert", true)
  70. + test("tree", "eeert", false);
  71.  
  72. printf("\n%d misses.\n", misses);
  73.  
  74. return 0;
  75. }
  76.  
Success #stdin #stdout 0s 5348KB
stdin
Standard input is empty
stdout
"try" matches "try": true.
"try" matches "rty": true.
"try" matches "tray": false.
"try" matches "": true.
"try" matches "y": true.
"try" matches "t": true.
"try" matches "z": false.
"try" matches "rytt": false.
"try" matches "yt": true.
"try" matches "yurt": false.
"tree" matches "eert": true.
"tree" matches "eeert": false.

0 misses.