Solution to Assignment II-1

--------------------------------
-- In Ada
--------------------------------

--  A term is represented by a record
--  A polynomial is a linked list of terms. The simplest is to equate a list
--  with a pointer to its first element, but representations with headers are
--  also useful. In particular, there are complications with null polynomials
--  if you do not use a header (left to the reader).

Type Term is record
	Coef: Float;
	DegX: Integer;
	DegY: Integer;
end record;

Type node;
Type Polynomial is access node;

Type node is record
	mono: Term;
	next: Polynomial;
end record;

--a function to evaluate a bivariate polynomial at a point:

Function Evaluate (P: in Polynomial; x, y: in Float) return Float is
	Value : Float      := 0.0;
        P1    : Polynomial := P;
begin
    while  P1 /= null  loop
        Value := Value +
             P1.mono.Coef * (x ** P1.mono.DegX) * (y ** P1.mono.DegY);
        P1  := P1.next;
    end loop;

    return value;
end evaluate;

--a function to multiply a polynomial P by a term T

Function multi (P: in Polynomial; T: in Term) return Polynomial is
	temp : Term := (0.0,0,0);
	result, rp : Polynomial := null;
        P1 : Polynomial := P;
begin
    while P1 /= null loop
        temp.Coef := P1.mono.Coef * T.Coef;
        temp.DegX := P1.mono.DegX + T.DegX; 
        temp.DegX := P1.mono.DegY + T.DegY;

        if result = null then                      --  first term of result
        	result := new node'(temp, null);
        	rp := result;
        else
        	rp.next := new node'(temp, null);  --  append to last one
        	rp := rp.next;
        endif;

    	P1 := P1.next;
    end loop;

    return result;

end multi;


/* ------------------------------------
In C: almost identical.
-------------------------------------*/

#include 

struct  term {
	float Coef;
	int	DegX;
	int	DegY;
  };

struct polynomial {
	struct term   		mono;
	struct polynomial   *next;
  };

#define NULL 0
#define LEN sizeof (struct  polynomial)


float  Evaluate (struct polynomial  *P, float x, float y) { 
	float   value = 0.0;

	while (P != NULL) {
		value = value + P->mono.Coef *
				(float)pow((double)x, (double)P->mono.DegX) *
				(float)pow((double)y, (double)P->mono.DegY);
		P = P->next;
	}

	return value;
}

struct polynomial *multi(struct polynomial *P, struct term T)
{
	struct polynomial *result = NULL, *rp = NULL;

	while (P != NULL) {
		if (result == NULL){
			result = (struct polynomial * ) malloc (LEN);
			rp = result;
			rp->next = NULL;
		}
		else {
			rp->next = (struct polynomial * ) malloc (LEN);
			rp->next->next = NULL;
			rp = rp->next;
		}

		rp->mono.Coef = P->mono.Coef * T.Coef;
		rp->mono.DegX = P->mono.DegX + T.DegX;
		rp->mono.DegY = P->mono.DegY + T.DegY;

		P = P->next;
	}

	return result;
}