/*********** Problem 1--Gray Codes ************************************
 This problem was pretty straightforward:  the algorithm was given to
 you in the problem description.
 **********************************************************************/

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

int main (int argc, char **argv);
static unsigned int getnormalposition (int k, int A);
static int nthbit (unsigned int i, int n);
static void printgrayconverted (unsigned int i, int k, int cs);

FILE *in, *out;

/****** main **********************************************************
 This program repeatedly reads in the number of bits in a Gray code
 and the angle to which a drum is rotated, and prints out the Gray code
 for that region of the drum.
 **********************************************************************/

int main (int argc, char **argv) {

  int k, A,    /* the k and A values */
      cs=0;    /* the case number */

 in = fopen ("prob1.in","r");    /* redirect input and output */
 out = fopen ("prob1.out","w");
 while (1) {
  fscanf (in,"%d %d",&k,&A);   /* read in k and A until both are zero */
  if (k==0 && A==0) break;
                              /* print the pattern */
  printgrayconverted (getnormalposition(k,A),k,++cs);
 }
 fclose (in);   /* close our files */
 fclose (out);
 return EXIT_SUCCESS;
}

/******* getnormalposition ********************************************
 getnormalposition accepts k and A and returns the number corresponding
 to its position.  There are 2^k positions, and the angle is measured
 in degrees.
 **********************************************************************/

static unsigned int getnormalposition (int k, int A) {

 return floor (A*pow(2,k)/360);
}

/******* nthbit *******************************************************
 nthbit accepts an unsigned integer and a bit position, and returns
 the value of that bit in that integer.  It uses C's built-in
 right-shift command.
 **********************************************************************/

static int nthbit (unsigned int i, int n) {

 return (i>>n) %2;
}

/********** printgrayconverted ****************************************
 printgrayconverted takes an unsigned integer, the number of bit
 positions and the case number, and prints out the gray code for that
 integer using the algorithm described in the problem.
 **********************************************************************/

static void printgrayconverted (unsigned int i, int k, int cs) {

  int j;   /* loop iterator */

 fprintf (out,"%d: %d ",cs,nthbit(i,k-1));
                                /* printing the leftmost bit */
 for (j=k-2;j>=0;j--)
                     /* totalling adjacent bits to print the next */
  fprintf (out,"%d ",(nthbit(i,j+1)+nthbit(i,j))%2);  /* Gray code */
 fprintf (out,"\n");
}
