A/*
* A160732.c
* Calculates the entries of Sloane's A160732
*
* Created by Nathaniel Johnston (nathaniel@nathanieljohnston.com)
* March 30, 2011
*/

#include <math.h>
#include <stdio.h>


unsigned int prevPts = 3, numPts = 3, pt[268435455];
FILE *file;

unsigned int getCoord (unsigned int pt, unsigned short coord)
{
    unsigned short shift = 14*(coord-1);
    return (pt & (16383*(1 << shift))) >> shift;
}

unsigned char getOrien (unsigned int pt)
{
    return (pt & (1 << 28)) >> 28;
}

unsigned int getPt (unsigned short x, unsigned short y, unsigned short orien)
{
    return x | (y << 14) | (orien << 28);
}

unsigned char addOrien (unsigned short x, unsigned short y, unsigned short orien)
{
    unsigned int j, nn = 0;
    unsigned short px, py, po;
    for(j=0;j<prevPts;j++)
    {
        px = getCoord(pt[j],1);
        py = getCoord(pt[j],2);
        po = getOrien(pt[j]);

        if(po == 1 && ((px == x && py == y+1) || (px == x && py == y-1))){
            if(orien == 1)return 0;nn++;
        }
        else if(po == 0 && ((px == x-1 && py == y) || (px == x+1 && py == y))){
            if(orien == 0)return 0;nn++;
        }
    }
    return (nn == 1);
}

unsigned char isOccupied (unsigned short x, unsigned short y)
{
    unsigned int j;
    for(j=0;j<prevPts;j++)
    {
        if(x == getCoord(pt[j],1) && y == getCoord(pt[j],2))return 1;
    }
    return 0;
}

int main ()
{
    unsigned short xi, yi, oi, tOr, gen, maxGens;
    pt[0] = getPt(8192,8192,0);
    pt[1] = getPt(8193,8193,1);
    pt[2] = getPt(8193,8191,1);

    printf("This tool will calculate the entries of Sloane's A160732.\nPlease enter the number of terms to compute (an integer from 1 to 8191): ");
    scanf("%d",&maxGens);

    file = fopen("b160732.txt","w");
    fprintf(file,"0 0\n1 3\n");
    fclose(file);
    printf("0 0\n1 3\n");

    for(gen=1;gen<maxGens;gen++){
        for(xi=8192-(int)((gen+1)/2);xi<=8193+(int)(gen/2);xi++){
            for(yi=8191-(int)((gen+1)/2);yi<=8193+(int)((gen+1)/2);yi++){
                tOr = isOccupied(xi,yi);
                for(oi=0;oi<2;oi++){
                    if(!tOr && addOrien(xi,yi,oi))pt[numPts++]=getPt(xi,yi,oi);
                }
            }
        }
        file = fopen("b160732.txt","a");
        fprintf(file,"%d %d\n",gen+1,numPts);
        fclose(file);
        printf("%d %d\n",gen+1,numPts);
        prevPts = numPts;
    }

    printf("Done!");
    getchar();
    return 0;
}