コード例 #1
0
//Main function
int main(void){
	while(true){ //Loop program forever (unless termination condition reached)

		//Variables used within function
		int degree, * coeff; 

		//User interaction
		printf("Please enter the maximum degree of the polynomial: ");
		scanf("%d", &degree); //Promt for input

		if (degree < 0) return 0; //Terminate if negative coefficient given

		coeff = (int*) calloc(degree + 1, sizeof(int));

		printf("Please enter the coefficients: ");
		readCoefficients(degree, coeff); //Read the coefficients

		printf("The polynomial is ");
		printPolynomial(degree, coeff); //Print out the polynomial
		printf("\n");
		
		printf("Its derivative is ");
		printDerivative(degree, coeff); //Print out the derivative of the polynomial
		printf("\n");

		printf("\n");

		free(coeff); //Deallocate memory used by array to avoid memory leaks

	}
	return 0;
}
コード例 #2
0
ファイル: cw3c-dynamic.cpp プロジェクト: oferoze/Automarking
void startProgram() {

	// Set up the variables
	int degree = 0, *coefficients = NULL;

	// Ask the user to input the maximum degree of the polynomial
	printf("Please enter the maximum degree of the polynomial: ");
	scanf("%d", &degree); 

	// Allocate the required memory for the coefficients
	coefficients = (int*) calloc (degree+1, sizeof(int));

	// Let the user know if there was a memory allocation error (&terminate the program)...
	if(coefficients == NULL)                     
	{
		printf("Wooops! There was a memory allocation error. The monkeys are working on it...");
		return;
	} 
	// ...otherwise get on with the program
	else {
		// If the degree is negative
		if(degree<0) {
			return;
		}	

		// Ask the user to input the coefficients (can be white-space or newline delimited)
		printf("Please enter the coefficients: ");

		// Allow user input so that the number of coefficients is equal to the maximum degree
		for(int i=0; i<=degree; i++) {
			scanf("%d", &coefficients[i]);
		}

		// Start processing the output
		printf("The polynomial is ");

		// First we print the polynomial
		printPolynomial(1, coefficients, degree, 0);

		// Then we let the user know we will print the derivative
		printf("\nIts derivative is ");

		// Now we derive
		derive(1, coefficients, degree, 0);

		// Free the memory
		free(coefficients);

		// Clear the address that was pointed to
		coefficients = NULL;

		// Clear the input buffer in case the user entered too many coefficients
		int ch;
		while ((ch = getchar()) != EOF && ch != '\n') ;
		/* Code seen and borrowed from http://www.dreamincode.net/forums/topic/89633-input-buffer-problems-with-scanf/page__view__findpost__p__557060 */ 

		// Finally we rerun the program 
		startProgram();
	} 
}
コード例 #3
0
ファイル: main.c プロジェクト: ramntry/numerical_analysis
void printReport(Table const *table, char const *name)
{
    char const func_char = table->f == my_f ? f_charrep : g_charrep;
    char const *func_str = table->f == my_f ? f_strrep  : g_strrep;
    printf("\n%s for %c(x) = %s on [%Lf, %Lf]\n", name, func_char, func_str, min_x, max_x);
    printTable(table);
    long double const error_coeff = (table->f == my_f ? error_coeff_f : error_coeff_g)(table->xs.size);
    long double const step = (max_x - min_x) / numof_checkpoints;
    long double curr_x = min_x;
    long double max_error = 0.0;
    long double max_upperbound = 0.0;
    Polynomial polynomial;
    makeLagrangePolynomial(&polynomial, table);
    printf("Ln(%c, x) = ", func_char);
    printPolynomial(&polynomial, stdout);
    printf("\n\nNo | x            | %c(x)         | Ln(%c, x)         | error            | A                      | error <= A\n", func_char, func_char);
    printf("---+--------------+--------------+------------------+------------------+------------------------+-----------\n");
    for (size_t i = 1; i <= numof_checkpoints; ++i) {
        long double const x = curr_x + frand() * step;
        long double const y = table->f(x);
        long double const lagrange = lagrangeValue(table, x);

        assert(fabsl(calcValue(&polynomial, x) - lagrange) < 1.e-6);

        long double const error = fabsl(y - lagrange);
        long double const error_upperbound = errorUpperbound(table, x, error_coeff);
        printf("%2zu | %+.9Lf | %+.9Lf | %+16.9Lf | %+16.9Lf | %+22.9Lf | %s\n"
                , i, x, y, lagrange, error, error_upperbound, error <= error_upperbound ? "Yes" : "No");
        curr_x += step;
        max_error = error > max_error ? error : max_error;
        max_upperbound = error_upperbound > max_upperbound ? error_upperbound : max_upperbound;
    }
    printf("\nmax error = %+.9Lf\nmax A     = %+.9Lf\n\n", max_error, max_upperbound);
    disposePolynomial(&polynomial);
}
コード例 #4
0
ファイル: hw10_task01.cpp プロジェクト: ramntry/homeworks
void opPrint(Polynomial *space)
{
    char name = '"';
    scanf("%*[ \n\t\r]%c", &name);
    if (name >= 'a' && name <= 'z')
        printPolynomial(space[name - 'a']);
}
コード例 #5
0
ファイル: cw3c-dynamic.cpp プロジェクト: oferoze/Automarking
void printPolynomial(int start, int* coefficients, int degree, int wasZero) {

	int *current, previousZero;
	current = &coefficients[start-1];

	// If there are no degrees of the polynomial we print the sole coefficient 
	if(degree == 0) {
		printf("%d", *current);
	} 
	// Otherwise we start checks on the coefficient. Firstly we make sure it isn't 0
	else if(*current != 0) {

		// Run the makePretty function
		makePretty(degree, wasZero, start, *current);

		// We then decide whether to output an x 
		if(start < degree) {
			printf("x^%d", (degree - start + 1));
		}

		// If we're on the final degree of the polynomial we omit the power (^1)
		if(start == degree) {
			putchar('x');
		}
		// This coefficient isn't 0, so we pass that in the function
		previousZero = 0;
	} else {
		// This coefficient is 0, so we pass that in the function
		previousZero = 1;
	}
	// If there are still coefficients to print we re-run the function
	if(start<degree+1) {
		printPolynomial(start + 1, coefficients, degree, previousZero);
	}
}
コード例 #6
0
void test2()
{
	Polynomial* pol4 = createYourPolynomial();
	printPolynomial(pol4);
	getc(stdin);
	double v = valueInPoint(pol4,24);
	printf(" %0.3f\n",v);
}
コード例 #7
0
void test1()
{
	Polynomial* pol = createPolynomial(3);
	Polynomial* pol2 = createPolynomial(0);
	addToPolynomial(pol,-1,1);
	addToPolynomial(pol,-1,2);
	addToPolynomial(pol,-1,3);
	printPolynomial(pol);
	printf("\n");

	addToPolynomial(pol2,5,4);
	addToPolynomial(pol2,-1,3);
	addToPolynomial(pol2,5,2);
	printPolynomial(pol2);
	printf("\n");

	Polynomial* pol3 = mergePolynomials(pol,pol2);
	printPolynomial(pol3);
}
コード例 #8
0
void printDerivative(int degree, int* coeff){ //Print the derivative of a polynomial
	int* deriv; //Store derivative coefficients in new array

	deriv = (int*) calloc(degree, sizeof(int));

	if (degree == 0){ //Special case
		deriv[0] = 0; //Derivative of 0 degree polynomial always 0
		printPolynomial(0, deriv);
		return;
	}

	for (int i = degree; i > 0; i--){
		deriv[degree - i] = coeff[degree - i] * i; //Differentiate each coefficient
	}

	printPolynomial(degree - 1, deriv); //Reuse printPolynomial(), by passing deriv instead of coeff, to make code more manageable
	
	free(deriv); //Deallocate memory used by array to avoid memory leaks
}
コード例 #9
0
ファイル: cw3c-dynamic.cpp プロジェクト: oferoze/Automarking
int main(void)
{
	int maxDegree,*a;

	while (1 > 0) { //loop until end of program
		printf("Please enter the maximum degree of the polynomial: ");
		scanf("%d",&maxDegree);

		if (maxDegree < 0) { //if a negative is given, exit
			return 0;
		} else {		
			printf("Please enter the coefficients: ");
			a = (int*)calloc(maxDegree,sizeof(int)); //dynamic memory allocation
			for (int n=0;n<=maxDegree;n++) {
				scanf("%d",&a[n]);
			}

			while (a[0] == 0 && maxDegree > 1) { //while the first coefficient is 0 or until it is an integer
				maxDegree -= 1; //decrease maximum power by 1
				for (int n=0;n<=maxDegree;n++){
					a[n] = a[n+1]; //and move all coefficients along by one element
				}
			}

			printf("The polynomial is ");
			if (maxDegree == 0) printf("%d\n",a[0]); //if the polynomial is just an integer, then print the integer
			else printPolynomial(a, maxDegree); //print the polynomial

			for (int n=0;n<=maxDegree;n++) { //multiply coefficients by powers
				a[n] *= (maxDegree - n);
			}

			printf("The derivative is ");							//print the derivative as a polynomial with new
			if (maxDegree > 1) printPolynomial(a, maxDegree - 1);	//coefficients all the powers decreased by one
			else if (maxDegree == 1) printf("%d\n",a[0]); //just an integer
			else printf("0\n"); //maxDegree == 0, so derivative is 0
			free(a); //free memory allocation to avoid memory leak
		}

		printf("\n");
	}
}
コード例 #10
0
ファイル: DrawPolynomial.c プロジェクト: ilansh/c_course
/*
 * Main function.
 * Receives the user input and calls functions to performs the required
 * operations.
 */
int main()
{
    //polynomial coefficients a,b,c,d:
    double a,b,c,d;
    printf("y(x)=a+b*x+c*x^2+d*x^3\n");
    a = getCoefficient('a');
    b = getCoefficient('b');
    c = getCoefficient('c');
    d = getCoefficient('d');
    printPolynomial(a,b,c,d);
    drawGraph(a,b,c,d);
    return 0;
}
コード例 #11
0
ファイル: 1-cw3b-pretty.cpp プロジェクト: oferoze/Automarking
void startProgram() {

    // Set up the variables. As per the specification, we assume that the maximum number of coefficients is 10
    int degree = 0, coefficients[MAXDEGREE+1];

    // Ask the user to input the maximum degree of the polynomial
    printf("Please enter the maximum degree of the polynomial: ");
    scanf("%d", &degree);

    // If the degree is negative or greater than 10 then we terminate
    if(degree<0 || degree>MAXDEGREE) {
        return;
    }

    // Ask the user to input the coefficients (can be white-space or newline delimited)
    printf("Please enter the coefficients: ");

    // Allow user input so that the number of coefficients is equal to the maximum degree
    for(int i=0; i<=degree; i++) {
        scanf("%d", &coefficients[i]);
    }

    // Start processing the output
    printf("The polynomial is ");

    // First we print the polynomial
    printPolynomial(1, coefficients, degree, 0);

    // Then we let the user know we will print the derivative
    printf("\nIts derivative is ");

    // Now we derive
    derive(1, coefficients, degree, 0);

    // Clear the input buffer in case the user entered too many coefficients
    int ch;
    while ((ch = getchar()) != EOF && ch != '\n') ;
    /* Code seen and borrowed from http://www.dreamincode.net/forums/topic/89633-input-buffer-problems-with-scanf/page__view__findpost__p__557060 */


    // Finally we rerun the program
    startProgram();
}
コード例 #12
0
ファイル: main.c プロジェクト: ramntry/numerical_analysis
void reportMaxError()
{
    size_t const numof_tests = 5000;
    size_t const max_numof_xs = 400;
    size_t const numof_avg_iters = no_random ? 1 : 50;
    printf("\nMax error for function g(x) = %s (on [%Lf, %Lf]) and various number (#) of interpolation points:\n", g_strrep, min_x, max_x);
    printf(" #   | error (avg among %4zu)\n", numof_avg_iters);
    printf("-----+-----------------------\n");
    Polynomial best_polynomial;
    initPolynomial(&best_polynomial, DISPOSED_POLYNOMIAL_DEG);
    double best_error = LDBL_MAX;
    for (size_t numof_xs_step = 1; numof_xs_step <= 100; numof_xs_step *= 10) {
        Polynomial curr_polynomial;
        initPolynomial(&curr_polynomial, DISPOSED_POLYNOMIAL_DEG);
        size_t curr_numof_xs = numof_xs_step;
        for (size_t i = 0; i < 9 && curr_numof_xs <= max_numof_xs; ++i) {
            long double error = 0.0;
            for (size_t k = 0; k < numof_avg_iters; ++k) {
                long double curr_error = calcMaxError(my_g, &curr_polynomial, curr_numof_xs, numof_tests, min_x, max_x);
                if (fabsl(best_error) > fabsl(curr_error)) {
                    best_error = curr_error;
                    disposePolynomial(&best_polynomial);
                    best_polynomial = curr_polynomial;
                } else {
                    disposePolynomial(&curr_polynomial);
                }
                error += curr_error;
            }
            error /= numof_avg_iters;
            printf("%4zu | %-+22.4Lg\n", curr_numof_xs, error);
            fflush(stdout);
            curr_numof_xs += numof_xs_step;
        }
    }
    if (best_polynomial.deg != DISPOSED_POLYNOMIAL_DEG) {
        printf("The best polynomial is: ");
        printPolynomial(&best_polynomial, stdout);
        putchar('\n');
    }
    disposePolynomial(&best_polynomial);
}
コード例 #13
0
ファイル: zad1.c プロジェクト: mskiba/MO
int main() {
    double *A, **t, x0;
    int i, n;
    char chce_podac_x[2];

    do {
        printf("Podaj liczbę naturalną z przedziału od 0 do %d: ", N_MAX);
        scanf("%d", &n);
    } while(n < 0 || n > N_MAX);

    n += 1;
    A = malloc(n * sizeof (double));
    for (i = 0; i < n; i++) {
        printf("Podaj A[%d]: ", i);
        scanf("%lf", &A[i]);
    }
    t = malloc(n * sizeof (double*));
    for (i = 0; i < n; i++) {
        t[i] = malloc((n + 1) * sizeof (double));
    }

    do {
        printf("Podaj X0: ");
        scanf("%lf", &x0);
        clearMatrix(n, t, A);
        fillMatrix(n, t, x0);
        resolveMatrix(n, t);
        printPolynomial(n, t);

        do {
            printf("Chcesz podać kolejne X0? (tak/nie): ");
            scanf("%s", chce_podac_x);
            if(strcmp(chce_podac_x, "tak") == 0 || strcmp(chce_podac_x, "nie") == 0) break;
        } while(1);

    } while (strcmp(chce_podac_x, "tak") == 0);

    return 0;
}
コード例 #14
0
ファイル: cw3b-pretty.cpp プロジェクト: oferoze/Automarking
int main(void) {
    // Infinite loop so that it loops till being terminated
    for(;;) {
        int max_d = 0;			// Maximum degree of the polynomial
        int co[11];				// Assume maximum degree is never bigger than 10

        printf("Please enter the maximum degree of the polynomial: ");
        scanf("%d", &max_d);

        // Program terminates if maximum degree is negative
        if (max_d < 0) {
            return 0;
        }

        printf("Please enter the coefficients: ");
        for (int i = 0; i < max_d + 1; i++) {
            scanf("%d", &co[i]);
        }

        printPolynomial(max_d, co);
        printDerivative(max_d, co);
    }
}
コード例 #15
0
ファイル: main.c プロジェクト: CodexVII/CE4703project
int main(){ 
  polynomial a, b, c, sum, difference, product, quotient, normal;
  double coeff;
  int order;

  //these will be converted into dynamic arrays later on.
  //they just store the coeffs to be used for the polynomials.
  double data1[3];
  data1[2] = 5;
  double data2[3] = {5.2, -2, 4};
  double data3[7]= {5.0, 2.0, 20, 0, 5, 2, 40.2};

  //clear the screen to focus on this single session's tests
  system("clear");

  //////////////////////////////////////////////////////////////////
  //creating base polynomials we'll be using for the entirity of
  //these test cases.
  //
  //NOTE: second parameter of initalisePolynomial(poly, size) 
  //      MUST match the test case arrays above.
  //////////////////////////////////////////////////////////////////  
  createPolynomial(&a, 3, data1);
  createPolynomial(&b, 3, data2);
  createPolynomial(&c, 7, data3);
  
  printf("--------------------------------------------------------------------------------\n");
  printf("These are the starting polynomials which will be used for the later operations\n");
  printf("--------------------------------------------------------------------------------\n");
  printf("Polynomial (A): ");
  verify(printPolynomial(&a));
  printf("Polynomial (B): ");
  verify(printPolynomial(&b));
  printf("Polynomial (C): ");
  verify(printPolynomial(&c));

  //////////////////////////////////////////////////////////////////
  //testing add/subtract polynomials of same length
  //////////////////////////////////////////////////////////////////
  printf("--------------------------------------------------------------------------------\n");
  printf("testing add/subtract polynomials of same length\n");
  printf("--------------------------------------------------------------------------------\n");
  printf("Polynomial (A): ");
  verify(printPolynomial(&a));
  printf("Polynomial (B): ");
  verify(printPolynomial(&b));

  //add
  printf("A + B =  ");
  verify(add(&a, &b, &sum));
  verify(printPolynomial(&sum));

  //subtract
  printf("A - B =  ");
  verify(subtract(&a, &b, &difference));
  verify(printPolynomial(&difference));

  deletePolynomial(&sum);
  deletePolynomial(&difference);

  //////////////////////////////////////////////////////////////////
  //testing add/subtract polynomials of different length  
  //////////////////////////////////////////////////////////////////
  printf("--------------------------------------------------------------------------------\n");
  printf("testing add/subtract polynomials of different length\n");
  printf("--------------------------------------------------------------------------------\n");
  printf("Polynomial (A): ");
  verify(printPolynomial(&a));

  printf("Polynomial (C): ");
  verify(printPolynomial(&c));

  printf("A + C =  ");
  verify(add(&a, &c, &sum));
  verify(printPolynomial(&sum));

  printf("A - C =  ");
  verify(subtract(&a, &c, &difference));
  verify(printPolynomial(&difference));

  deletePolynomial(&sum);
  deletePolynomial(&difference);

  //////////////////////////////////////////////////////////////////
  //testing multiplcation/division by a scalar  
  //////////////////////////////////////////////////////////////////
  printf("--------------------------------------------------------------------------------\n");
  printf("testing multiplcation/division by a scalar\n");
  printf("--------------------------------------------------------------------------------\n");
  printf("Polynomial (A): ");
  printPolynomial(&a);
  printf("Polynomial (C): ");
  printPolynomial(&c);

  coeff = 5;
  //multiply
  printf("A * %.2lf =  ", coeff);
  multiply(&a, coeff, &product);
  printPolynomial(&product);

  //divide
  printf("C / %.2lf =  ", coeff);
  divide(&c, coeff, &quotient);
  printPolynomial(&quotient);

  deletePolynomial(&product);
  deletePolynomial(&quotient);

  //////////////////////////////////////////////////////////////////
  //testing for normalising polynomials
  //////////////////////////////////////////////////////////////////
  printf("--------------------------------------------------------------------------------\n");
  printf("testing for normalising polynomials\n");
  printf("--------------------------------------------------------------------------------\n");
  printf("Polynomial (A): ");
  printPolynomial(&a);
  printf("Polynomial (C): ");
  printPolynomial(&c);
  
  //test1
  printf("Noramlised (A) =  "); 
  normalise(&a, &normal);
  printPolynomial(&normal);

  deletePolynomial(&normal);

  //test2  
  printf("Noramlised (C) =  "); 
  normalise(&c, &normal);
  printPolynomial(&normal);

  deletePolynomial(&normal);

  //////////////////////////////////////////////////////////////////
  //testing for order of poly
  //////////////////////////////////////////////////////////////////
  printf("--------------------------------------------------------------------------------\n");
  printf("testing for order of poly\n");
  printf("--------------------------------------------------------------------------------\n");
  printf("Polynomial (A): ");
  printPolynomial(&a);
  getOrder(&a, &order);
  printf("Order: %d\n", order); 
 
  //////////////////////////////////////////////////////////////////
  //delete original polynomials
  //end of testing.
  //////////////////////////////////////////////////////////////////
  deletePolynomial(&a);
  deletePolynomial(&b);
  deletePolynomial(&c);

  return EXIT_SUCCESS;
}
コード例 #16
0
int main()
{
	/*test1();
	test2();*/
	Polynomial* polynomialSet[101] = {};
	printf("1-exit\n2-check the equation of two polynomials\n3-calculate the value in a point\n4-sum two polynomials\n5-multiply polynomials\n6-print polynomial\n");
	printf("======================\nFILL TWO POLYNOMIALS");
	printf("\n===Polynomial_1===:");
	Polynomial* pol1 = createYourPolynomial();	
	polynomialSet[1] = pol1;
	printf("===Polynomial_2===:");
	Polynomial* pol2 = createYourPolynomial();
	polynomialSet[2] = pol2;
	int answer = 0;
	int number = 1;
	int num1 = 1;
	int num2 = 2;
	int amount = 3;
	double x0 = 1;
	int y = 0;
	do
	{
		
		printf("\nWhat now?_");
		scanf("%d",&answer);
		switch (answer)
		{
		case 1:
			{
				break;
			}
		case 2 :
			{
				printf("Enter the number of 1st polynomial_");
				scanf("%d",&num1);
				printf("Enter the number of 2nd polynomial_");
				scanf("%d",&num2);
				if((polynomialSet[num1] != NULL) && (polynomialSet[num2] != NULL))
					if (polynomialsEqual(polynomialSet[num1],polynomialSet[num2]))
						printf("they equal");
					else
						printf("they do not equal");
				break;
			}
		case 3 :
			{
				printf("Enter the number of polynomial_");
				scanf("%d",&number);
				printf("Enter the point_");
				scanf("%lf",&x0);
				if(polynomialSet[number] != NULL)
				{
					double y = valueInPoint(polynomialSet[number],x0);
					printf("%lf",y);
				}
				else
					printf("no such polynomial");
				break;
			}
		case 4 :
			{
				printf("Enter the number of 1st polynomial_");
				scanf("%d",&num1);
				printf("Enter the number of 2nd polynomial_");
				scanf("%d",&num2);
				if((polynomialSet[num1] != NULL) && (polynomialSet[num2] != NULL))
				{
					Polynomial* newPol = mergePolynomials(polynomialSet[num1],polynomialSet[num2]);
					printf("Polynomial %d :",amount);
					printPolynomial(newPol);
					polynomialSet[amount] = newPol;
					++amount;
				}
				else
					printf("one of the polynomials doesn't exsist");
				break;
			}
		case 5 :
			{
				printf("Enter the number of 1st polynomial_");
				scanf("%d",&num1);
				printf("Enter the number of 2nd polynomial_");
				scanf("%d",&num2);
				if((polynomialSet[num1] != NULL) && (polynomialSet[num2] != NULL))
				{
					Polynomial* newPol = multiplyPolynomials(polynomialSet[num1],polynomialSet[num2]);
					printf("Polynomial %d :",amount);
					printPolynomial(newPol);
					polynomialSet[amount] = newPol;
					++amount;
				}
				else
					printf("one of the polynomials doesn't exsist");
				break;
			}
		case 6:
			{
				printf("Enter the number of polynomial_");
				scanf("%d",&number);
				if(polynomialSet[number] != NULL)
					printPolynomial(polynomialSet[number]);
				else
					printf("no such polynomial");
				break;
			}
		default:
			{
				answer = 1;
				break;
			}
		}
	}
	while(answer != 1);

	for(int j = 1 ; j < amount ; j++)
		destroyPolynomial(polynomialSet[j]);
	
	getc(stdin);
}
コード例 #17
0
ファイル: main.c プロジェクト: rarry/it
int main()
{


    char * inFp = "C:\\abc.txt";
    //char * inFpZeroes= "C:\\abc_zeroes.txt";
    char * inFpCrc = "C:\\abc_crc.txt";
    char * outFp = "C:\\abc_compressed.txt";
    char * decompressedFpCrc = "C:\\abc_decompressed_crc.txt";
    char * decompressedFp = "C:\\abc_decompressed.txt";


    copyFile(inFp, inFpCrc);
    //appendZeroes(inFpZeroes, SIZECRC);
    unsigned char * restPoly = calculateCrc(inFp);
    printf("Generated polynomial:\n");
    printPolynomial(restPoly, SIZECRC);

    appendCrcToFile(inFpCrc, SIZECRC, restPoly);

    int lettersFrequencies[LETTERS_COUNT]; // = {81, 15, 28, 43, 128, 23, 20, 61, 71, 2, 1, 40, 24, 69, 76, 20, 1, 61, 64, 91, 28, 10, 24, 1, 20, 1, 130};;
    //char letters[LETTERS_COUNT] = {'?', '?', '?', '?', '?', '?', '?', '?', '?', '?','?', '?', '?', '?', '?','?', '?', '?', '?', '?','?', '?', '?', '?', '?','?', '?', '?', '?', '?', '?', '?', '!', '"', '#', '$', '%', '&', '(', ')', '*', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ' '};
    //printTabInt(lettersFrequencies, LETTERS_COUNT);
    //printTabChar(letters, LETTERS_COUNT);

    //printf("Letter indices: ");

    calculateFreq(inFpCrc, lettersFrequencies);
    //printTabInt(lettersFrequencies, 255);

    Node *nodes[LETTERS_COUNT];
    int i;
    for(i=0; i<LETTERS_COUNT; i++)
    {
        nodes[i] = malloc(sizeof(Node));
        nodes[i]->value = lettersFrequencies[i];
        nodes[i]->letterIndex = i;
        nodes[i]->left = NULL;
        nodes[i]->right = NULL;
    }

    //printLetterIndices(nodes);
    Node *tree = buildHuffmanTree(nodes);

    int codeTable[LETTERS_COUNT];
    int invertedCodeTable2[LETTERS_COUNT];
    resetIntTable(codeTable, LETTERS_COUNT);

    //printf("codeTable: \n");
    //printTabInt(codeTable, LETTERS_COUNT);
    fillTable(codeTable, tree, 0);
    invertCodeTable(codeTable, invertedCodeTable2);


    //printf("codeTable: \n");
    //printTabInt(codeTable, LETTERS_COUNT);

    //printf("inverted codeTable: \n");
    //printTabInt(invertedCodeTable2, LETTERS_COUNT);
    //printCodeTable(letters, codeTable, LETTERS_COUNT);
    //printCodeTableForIdx(codeTable, LETTERS_COUNT);
    //printTabInt(codeTable, LETTERS_COUNT);




    //createCrcFile(inFpCrc, SIZECRC, restPoly);
    //appendFileToFile(inFp, inFpCrc);



    compressFile(inFpCrc, outFp, invertedCodeTable2);
    printf("\n\ndecompressed file:\n");
    decompressFile(outFp, decompressedFpCrc, tree);

    unsigned char * restPolyFromDec = calulateRest(decompressedFpCrc);
    printf("\n\nRest from decopressed file:\n");
    printPolynomial(restPolyFromDec, SIZECRC);

    if(!isIntegral()){
        printf("Integrity check failed!");
        exit(EXIT_FAILURE);
    }else{
        copySkip(decompressedFpCrc, decompressedFp, SIZECRC);
    }

    //checkIntegrity();


    //FILE * output = fopen("C:\\codeblocks\\Huffman\\huffman\\to.txt","w");
    //compressFile(input, output, codeTable);


    return 0;
}
コード例 #18
0
ファイル: project3.c プロジェクト: rtsio/CS313
int main( int argc, char *argv[]) {
 
   // create array of structs and initialize 
   POLYNOMIAL polynomials[MAX_POLYNOMIALS];
   for (int i = 0; i < MAX_POLYNOMIALS; i++) {
      for (int j = 0; j < MAX_TERMS; j++) {
	 polynomials[i].terms[j].coefficient = 0;
	 polynomials[i].terms[j].exponent = 0;
      }
      polynomials[i].size = 0;
   }

   // open file w/ error checking, etc.
   FILE *cmdFile; 
   if (argc != 2) {
      printf("Usage: %s filename\n", argv[0]);
      exit(-1);
   } else {
      cmdFile = fopen(argv[1], "r");
   }
   if (cmdFile == NULL) {
      printf("Error opening the file.\n");
      exit (-1);
   }
   
   // read through each line in the file 
   char line[MAX_COMMAND_LENGTH];
   while ( fgets(line, MAX_COMMAND_LENGTH, cmdFile) != NULL) {
      
      // Check which command is being used
      if (line[0] == 'A' && line[3] == 'T') {

	 // strtok() and atoi() are usually very bad idea, but input is guaranteed to be well formed
	 char *command =  strtok(line," ");
	 char *index = strtok(NULL," ");
	 char *coeff = strtok(NULL," ");
	 char *exp = strtok(NULL," \n");
	 // convert last symbol on line to int to strip any whitespace from input file
	 int exponent = atoi(exp);
	 printf("CMD: %s, Polynominal #: %s, Coefficient: %s, Exponent: %d\n", command, index, coeff, exponent);
	 int integerIndex = atoi(index);
	 // Adding term and printing the new polynomial 
	 polynomials[integerIndex] = addTerm(polynomials[integerIndex], atoi(coeff), atoi(exp) );
	 printPolynomial(integerIndex, polynomials[integerIndex]);

      } else if (line[0] == 'M') {

	 // Scalar multiplication
	 char *command =  strtok(line," ");
	 char *index = strtok(NULL," ");
	 char *value = strtok(NULL," ");
	 int scalar = atoi(value);
	 printf("CMD: %s, Polynominal #: %s, Scalar value: %d\n", command, index, scalar);
	 int integerIndex = atoi(index);
	 polynomials[integerIndex] = multiply(scalar, polynomials[integerIndex]);
	 printPolynomial(integerIndex, polynomials[integerIndex]);

      } else if (line[0] == 'A') {
	 
	 // Summation
	 char *command =  strtok(line," ");
	 char *sumIndex = strtok(NULL," ");
	 char *firstIndex = strtok(NULL, " ");
	 char *secondIndex = strtok(NULL," ");
	 int second = atoi(secondIndex);
	 printf("CMD: %s, Sum goes into index #: %s, First operand: %s, Second operand: %d\n", command, sumIndex, firstIndex, second);
	 int sum = atoi(sumIndex);
	 int first = atoi(firstIndex);
	 polynomials[sum] = add(polynomials[first], polynomials[second]);
	 printPolynomial(sum, polynomials[sum]);

      } else if (line[0] == 'S') {

	 // Subtraction
	 char *command =  strtok(line," ");
	 char *diffIndex = strtok(NULL," ");
	 char *firstIndex = strtok(NULL," ");
	 char *secondIndex = strtok(NULL," ");
	 int second = atoi(secondIndex);
	 printf("CMD: %s, Dif goes into index #: %s, First operand: %s, Second operand: %d\n", command, diffIndex, firstIndex, second);
	 int diff = atoi(diffIndex);
	 int first = atoi(firstIndex);
	 polynomials[diff] = subtract(polynomials[first], polynomials[second]);
	 printPolynomial(diff, polynomials[diff]);
      }
   }

   fclose(cmdFile);
   return 0;
}