home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.os.msdos.apps
- Path: sparky!uunet!spool.mu.edu!darwin.sura.net!Sirius.dfn.de!chx400!news.unige.ch!ugsc2a!fisher
- From: fisher@sc2a.unige.ch
- Subject: Re: 'All Possible Combinations' Algorithms
- Message-ID: <1992Nov23.130227.1@sc2a.unige.ch>
- Lines: 46
- Sender: usenet@news.unige.ch
- Organization: University of Geneva, Switzerland
- References: <By0wH5.D3L@apollo.hp.com>
- Date: Mon, 23 Nov 1992 11:02:27 GMT
-
- In article <By0wH5.D3L@apollo.hp.com>, holbrook@apollo.HP.COM (Alan R. Holbrook) writes:
- > Can someone provide me with an algorithm suitable for writing a program
- > to dump all possible combinations of 'n' elements taken 'm' at a time?
-
- Wrong group, but here it goes (in somewhat portable c):
-
- #include <stdlib.h>
- #include <stdio.h>
-
- #define swapc(a,b) do {char tmp=(a); (a)=(b); (b)=tmp;} while(0)
-
- unsigned choose (unsigned n, char *s, unsigned p, unsigned nb)
- /* Select every possible combination of n chars out of s, printing them. */
- /* warning: n must be <= strlen(s) !!! */
- {
- char *c;
-
- if (n == 0)
- /* enough characters choosen, so print (incrementing nb) */
- printf("%5d: %.*s\n", ++nb, p, s);
- else
- /* select every possible next char and recurse */
- for (c = (s+p); *c; c++) {
- swapc(*c, s[p]);
- nb = choose(n-1, s, p+1, nb);
- swapc(*c, s[p]);
- }
- return nb;
- }
- /* simply call as: */
- #define combine(n,s) choose(n,s,0,0)
-
- void main(int argc, char *argv[])
- {
- if (argc<3) {
- printf("Usage %s <nb> <string>\n", argv[0]);
- printf("Prints all combinations of <nb> chars out of <string>\n");
- }
- else
- combine (atoi(argv[1]), argv[2]);
- }
-
-
- Good luck,
-
- Markus Fischer Dpt of Anthropology, Geneva CH fisher@sc2a.unige.ch
-