2001 LSU Computer Science High School Programming Contest

Sponsored by Texas Instruments

Veteran - Problem 6, Solution in c

/*
	Weird Math
*/

#include <stdio.h>
#include <string.h>

/* I use strings in this solution but it could be solved numerically...
LOG (base 10) could be used to find the length
of the code....  Integer division & Modulus could be used to
grab each digit.

My arrays could be replaced with switch/if statements
*/

main(int argc)
{
int z;
int numOfLoops;
int SHOWSTEPS=argc-1;  /*  SET THIS TO NON-ZERO TO SEE THE STEPS OF THE CALCULATIONS */
int code;
unsigned i;
unsigned numdigits;
int a,b,c;
char op;
char OPERATOR[]={'*','+','-','!'};
char temp[20], Astr[20], Bstr[20];
/*   Prof:  9 7 8 0 4 5 6 1 2 3
     US  :  0 1 2 3 4 5 6 7 8 9
*/

char  CONVERT [255];
CONVERT['7']='0';
CONVERT['8']='1';
CONVERT['9']='2';
CONVERT['0']='3';
CONVERT['4']='4';
CONVERT['5']='5';
CONVERT['6']='6';
CONVERT['1']='7';
CONVERT['2']='8';
CONVERT['3']='9';

code=1;
scanf("%d",&numOfLoops);

for (z=0; z<numOfLoops; z++)
 { // do each number
	scanf("%d",&code);

	if (code==-1)
		return 0;

	temp[0]=0;

	sprintf(temp,"%d",code);  /* I'm lazy at finding digits of integers */

	numdigits=temp[0]-'0';

	if (strlen(temp) < numdigits+2)
	 { // validate test
		printf("ERROR!!!!! INVALID TEST DATA!!!!!!!!!!!!\n");
		return 1;
	 } // validate test

	if (SHOWSTEPS) printf("A has %d digits\n",numdigits);
	if (SHOWSTEPS) printf("------------------------------\n");
	if (SHOWSTEPS) printf("  Before Conversion  : \n");
	if (SHOWSTEPS) printf("------------------------------\n");

	strncpy(Astr,temp+1,numdigits);  Astr[numdigits]=0;
	strncpy(Bstr,temp+2+numdigits,strlen(temp) - numdigits);
	op=OPERATOR [ (temp[1+numdigits]-'0') % 3];

	if (SHOWSTEPS) printf("Astr=[%s]\nBstr=[%s]\nOp: %c\n",Astr,Bstr,op);
	if (SHOWSTEPS) printf("------------------------------\n");
	if (SHOWSTEPS) printf("   After Conversion  : \n");
	if (SHOWSTEPS) printf("------------------------------\n");
	for (i=0; i < strlen(Astr); i++)
		 Astr[i]=CONVERT [ Astr[i] ];

	for (i=0; i < strlen(Bstr); i++)
		 Bstr[i]=CONVERT [ Bstr[i] ];
	if (SHOWSTEPS) printf("Astr=[%s]\nBstr=[%s]\nOp: %c\n",Astr,Bstr,op);

	sscanf(Astr,"%d",&a);
	sscanf(Bstr,"%d",&b);

	if (op=='*') c=a*b;
	if (op=='+') c=a+b;
	if (op=='-') c=a-b;

	printf ("%4d %c %4d = %4d\n",a,op,b,c);
 } // do each number

}





Return to Problem Index


 

The statements and opinions included in these pages are those of 2001 LSU Computer Science High School Programming Contest only. Any statements and opinions included in these pages are not those of Louisiana State University or the LSU Board of Supervisors.
© 2000,2001 Isaac Traxler
Last modified: Friday, 01 July, 2011 16:27:53