1 /*
2  * BuildRandomPolynomials.cpp
3  *
4  *  Created on: Nov 30, 2010
5  *      Author: bedutra
6  */
7 
8 #include <vector>
9 #include <sstream>
10 #include "BuildRandomPolynomials.h"
11 #include <cstdlib>
12 
13 /**
14  * makes a random monomial in dim variables of a set degree.
15  * The monomial is monic.
16  * If you want only 1 monomial in your polynomial, you must call makeRandomPolynomial or enclose the string in the final '[]' brackets.
17  */
makeRandomMonomial(const int dim,int totalDegree)18 string makeRandomMonomial(const int dim, int totalDegree)
19 {
20 	//We treat totalDegree as the amount left over...how much powers we still have to add.
21 	const int stepSize = 2; //add no more than 1 powers to a term at a time.
22 	vector<int> powers;
23 	int i; //i = the x_i who will be getting more powers.
24 	int newPower;
25 	stringstream poly;
26 
27 	powers.resize(dim);
28 
29 
30 	while (totalDegree > 0 )
31 	{
32 		i = rand()%dim; //find the x_i who will get more powers.
33 		newPower = rand()%stepSize; //find the additional power.
34 
35 		powers[i] += newPower;
36 		totalDegree -= newPower;
37 	}//add more powers to the polynomial
38 
39 	if (totalDegree < 0)
40 	{
41 		powers[i] += totalDegree; //totalDegree is neg!
42 	}//if we added too much, subtract from the last term we added to.
43 
44 	//now make a string monomial.
45 	poly << "[1,[";
46 	for(size_t j = 0; j < powers.size(); ++j)
47 	{
48 		poly << powers[j];
49 		if (j != powers.size()-1)
50 			poly << ',';
51 	}
52 	poly << "]]";
53 	return poly.str();
54 }
55 
56 
57 /* makes many random monic monomials of the same degree.
58  * If you want 1 monomial, you must use this function and just set numMonomials to 1.
59  *
60  */
makeRandomPolynomial(const int dim,const int totalDegree,const int numMonomials)61 string makeRandomPolynomial(const int dim, const int totalDegree, const int numMonomials)
62 {
63 	stringstream poly;
64 
65 	poly << "[";
66 	for(int i = 0; i < numMonomials; ++i)
67 	{
68 		poly << makeRandomMonomial(dim, totalDegree);
69 		if ( i < numMonomials-1)
70 			poly << ',';
71 	}
72 	poly << "]";
73 	return poly.str();
74 }
75 
76