3 * Matches anagrams and subgrams
5 * (c) 2001 Mark Wooding
8 /*----- Licensing notice --------------------------------------------------*
10 * This file is part of Anag: a simple wordgame helper.
12 * Anag is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
17 * Anag is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with Anag; if not, write to the Free Software Foundation,
24 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
27 /*----- Header files ------------------------------------------------------*/
31 /*----- Data structures ---------------------------------------------------*/
33 typedef unsigned countmap
[UCHAR_MAX
+ 1];
35 typedef struct node_gram
{
41 /*----- Main code ---------------------------------------------------------*/
43 /* --- @compile@ --- *
45 * Arguments: @node_gram *n@ = pointer to node to fill in
46 * @const char *p@ = pointer to string to compile from
50 * Use: Fills in an anagram node with letter frequencies.
53 static void compile(const char *p
, countmap count
)
55 memset(count
, 0, sizeof(countmap
));
56 while (*p
) count
[(unsigned char)*p
++]++;
59 /* --- Node matcher --- */
61 static int n_gram(node
*nn
, const char *p
, size_t sz
)
63 /* A string X is a subgram of Y unless, for some character CH, X has more
64 * characters of value CH than Y.
66 * Special feature: count `.' in the pattern as meaning `don't care'.
69 node_gram
*n
= (node_gram
*)nn
;
74 if (n
->sz
&& sz
!= n
->sz
) return (0);
75 memcpy(count
, n
->count
, sizeof(count
));
78 i
= (unsigned char)*p
++;
79 if (count
[i
]) count
[i
]--;
80 else if (count
['.']) count
['.']--;
86 /* --- Node creation --- */
88 node
*anagram(const char *const *av
)
90 node_gram
*n
= xmalloc(sizeof(*n
));
92 compile(av
[0], n
->count
);
93 n
->sz
= strlen(av
[0]);
97 node
*subgram(const char *const *av
)
99 node_gram
*n
= xmalloc(sizeof(*n
));
101 compile(av
[0], n
->count
);
106 /*----- That's all, folks -------------------------------------------------*/