// gcc -o intersect2 intersect2.c

#include <stdio.h>

#define MIN(a,b) ((a)<(b)?(a):(b))
#define MAX(a,b) ((a)>(b)?(a):(b))

static void
intersect1(char caps1[4], char caps2[4])
{
  int len1 = 4, len2 = 4;

  int i,j,k,l;
  char caps[]="    ";
  int p = 0;

  for (i = 0; i < len1 + len2 - 1; i++) {
    /* caps1 index goes from 0 to caps1->structs->len-1 */
    j = MIN (i, len1 - 1);
    /* caps2 index stays 0 until i reaches caps1->structs->len, then it counts
     * up from 1 to caps2->structs->len - 1 */
    k = MAX (0, i - j);

    /* now run the diagonal line, end condition is the left or bottom
     * border */
    while (k < len2) {
      if (caps1[j] == caps2[k]) {
        caps[p++] = caps1[j];
      }
      /* move down left */
      k++;
      if (j == 0)
        break;                  /* so we don't roll back to G_MAXUINT */
      j--;
    }
  }
  
  printf ("intersect1(%s,%s)=%s\n", caps1, caps2, caps);
}

static void
intersect2(char caps1[4], char caps2[4])
{
  int len1 = 4, len2 = 4;

  int j,l;
  int i = 0;
  int k = len2;
  char caps[]="    ";
  int p = 0;
  
  while (1) {
    
    if (i >=  len1 + len2)
      break;

    if (k == len2) {
      /* caps1 index goes from 0 to caps1->structs->len-1 */
      j = MIN (i, len1 - 1);
      /* caps2 index stays 0 until i reaches caps1->structs->len, then it counts
       * up from 1 to caps2->structs->len - 1 */
      k = MAX (0, i - j);

      i++;
    }
  
    if (caps1[j] == caps2[k]) {
      caps[p++] = caps1[j];
    }
    /* move down left */
    k++;
    if (j == 0)
      k = len2;                  /* so we don't roll back to G_MAXUINT */
    else
      j--;
  }
  printf ("intersect2(%s,%s)=%s\n", caps1, caps2, caps);
}


int main(int argc, char **argv)
{
  char caps1[] = "ABCD", caps2[] = "CABD";

  intersect1 (caps1, caps2);
  intersect1 (caps2, caps1);

  intersect2 (caps1, caps2);
  intersect2 (caps2, caps1);

  return 0;
}

