about summary refs log tree commit diff
path: root/usth/ICT2.1/labwork/2/Ex2.c
blob: 8f32134d9c196bf78eaee7d2edfb174abe6d0a05 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/*
 * Polynomial represented using linked list, with free coefficient at last.
 * This is free and unencumbered software released into the public domain.
 */

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

#include "construct.h"

#define COEFF_MOD 42

/*
 * Add addition to the coefficient of power n of poly if it already exists.
 * Return the mutated polynomial on success and NULL otherwise.
 */
construct *add_term(construct *poly, double addition, size_t n)
{
	double *term = nth(poly, length(poly) - n - 1);
	if (term == NULL)
		return NULL;
	*term += addition;
	return poly;
}

/* Remove the nth term and return the mutated polynomial. */
construct *remove_term(construct *poly, size_t n)
{
	if (poly == NULL)
		return NULL;
	size_t len = length(poly);
	if (++n == len) {
		construct *rest = cdr(poly);
		free(car(poly));
		free(poly);
		return rest;
	}

	double *term = nth(poly, len - n);
	if (term == NULL)
		return poly;
	*term = 0;
	return poly;
}

/*  Evaluate the polynomial poly of the length len at the specified value. */
double polyval(construct *poly, double value, size_t len)
{
	if (!len--)
		return 0;
	double coeff = *(double *) car(poly);
	return pow(value, len) * coeff + polyval(cdr(poly), value, len);
}

/* Print the polynomial poly of the length len using the specified varname. */
void polyprint(construct *poly, char *varname, size_t len)
{
	if (len--) {
		printf(len ? "%g%s^%zu + " : "%g",
		       *(double *) car(poly), varname, len);
		polyprint(cdr(poly), varname, len);
	} else {
		putchar(10);
	}
}

int main()
{
	construct *polynomial = NULL;
	srand(time(NULL));
	int len = rand() % 4 + 3;

	for (int i = 0; i < len; ++i) {
		double *coeff = malloc(sizeof(double));
		*coeff = rand() % COEFF_MOD;
		polynomial = cons(coeff, polynomial);
	}

	puts("Initial polynomial:");
	polyprint(polynomial, "x", len);

	double x = rand() % COEFF_MOD;
	int n = rand() % len;
	polynomial = add_term(polynomial, x, n);
	printf("The polynomial after adding %g to the number %d term:\n", x, n);
	polyprint(polynomial, "x", len);

	polynomial = remove_term(polynomial, --len);
	printf("The polynomial after removing the number %d term:\n", len);
	polyprint(polynomial, "x", len);

	n = rand() % (len - 1);
	polynomial = remove_term(polynomial, n);
	printf("The polynomial after removing the number %d term:\n", n);
	polyprint(polynomial, "x", len);

	puts("Evaluation of the polynomial using x from stdin:");
	scanf("%lf", &x);
	printf("%g\n", polyval(polynomial, x, len));

	return 0;
}