Computer Chess Club Archives


Search

Terms

Messages

Subject: Re: Permuting and Combining

Author: Dieter Buerssner

Date: 12:03:23 07/08/04

Go up one level in this thread


I actually had a similar problem recently (finding the maximum number of
possible moves with n Qs on a chess board - i just by burte force generated all
combinations). It was fun to think of an algorithm to do this, that does not
consist of many nested loops. That program just needed a few changes, for your
problem (if I undestand it correctly).

#include <stdio.h>

#define MAX 20

int main(int argc, char *argv[])
{
  int i, t, n, mx=argc-1;
  int q[MAX+1];

  if (mx > MAX)
    return 1;
  for (n=mx; n>=1; n--)
  {
    for (i=0; i<n; i++) /* Initialize combination array */
      q[i] = mx-(n-i);
    q[n] = mx+1;  /* Use q[n] for loop end detection */
    goto output;
    /* Generate all remaining combinations of n from mx objects */
    for (;;)
    {
      /* Could add a if (--q[0] < 0) around everyting upto output,
         and start the for loop at 1, to speed things up a bit */
      for (i=0; q[i] <= i; i++)
        ; /* Empty loop body, typically never executed. */
      if (i>=n) /* Hit the marker at the end? */
        break;
      t = --q[i];
      while (--i >= 0)
        q[i] = --t;
    output:
      for (i=0; i<n; i++)
        printf("%s ", argv[q[i]+1]);
      printf("\n");
    }
  }
  printf("\n"); /* one empty line to choose nothing */
  return 0;
}

G:\src\bb>gcc -O -Wall -ansi -pedantic allcomb.c -o allcomb

G:\src\bb>allcomb a sample to test
a sample to test
sample to test
a to test
a sample test
a sample to
to test
sample test
a test
sample to
a to
a sample
test
to
sample
a

Regards,
Dieter



This page took 0 seconds to execute

Last modified: Thu, 15 Apr 21 08:11:13 -0700

Current Computer Chess Club Forums at Talkchess. This site by Sean Mintz.