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
105
106
107
108
109
110
|
import org.junit.Test;
import java.util.Random;
import java.util.Arrays;
import static org.junit.Assert.assertEquals;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
public class PolinomioShould {
@Test
public void test4 (){
assertThat("error when pol={}",Polinomio.convertString(new int[]{}), is("") );
assertThat("error when pol={0,1}",Polinomio.convertString(new int[]{0,1}), is("x") );
assertThat("error when pol={-1,0}",Polinomio.convertString(new int[]{-1,0}), is("-1") );
assertThat("error when pol={-1,0,0,0,0,0}",Polinomio.convertString(new int[]{-1,0,0,0,0,0}), is("-1") );
assertThat("error when pol={-1,1,1}",Polinomio.convertString(new int[]{-1,1,1}), is("x^2+x-1") );
assertThat("error when pol={3,0,2}",Polinomio.convertString(new int[]{3,0,2}),is("2x^2+3"));
assertThat("error when pol={0,-1,0,0,3}",Polinomio.convertString(new int[]{0,-1,0,0,3}), is("3x^4-x"));
assertThat("error when pol={0,1,-2,4,0,0,-1,1}",Polinomio.convertString(new int[]{0,1,-2,4,0,0,-1,1}), is("x^7-x^6+4x^3-2x^2+x"));
assertThat("error when pol={1,1,-2,4,0,0,-1,1}",Polinomio.convertString(new int[]{1,1,-2,4,0,0,-1,1}), is("x^7-x^6+4x^3-2x^2+x+1"));
assertThat("error when pol={1,0,0,0,0,0}",Polinomio.convertString(new int[]{1,0,0,0,0,0}), is("1"));
}
@Test
public void randomTests(){
Random rnd = new Random();
Polinomiop po=new Polinomiop();
for(int j=0; j<25; j++){
int[] pol = new int[(int) (rnd.nextDouble() * 10 + 0)];
for(int i=0; i<pol.length; i=i+2)
pol[i]=((int) (rnd.nextDouble() * 10 -rnd.nextDouble()*10));
assertEquals("error when pol = "+Arrays.toString(pol),
po.convertString(pol), Polinomio.convertString(pol));
}
}
}
class Polinomiop {
static String convertString(int[] pol){
String result="";
for(int i = pol.length-1; i>=0; i--) {
if (pol[i] == 0){
continue;
}
if (i == 0) {
if (pol[i] < 0) {
result += "" + pol[i];
} else {
if(result.isEmpty()){
result+=pol[i];
continue;
}
result += "+" + pol[i];
}
continue;
} else if (i == pol.length - 1) {
if (pol[i] > 0) {
if (i == 1){
result += "" + dame(pol[i]) + "x";
continue;
}
result += "" + dame(pol[i]) + "x^" + i;
} else {
if (i == 1){
result += dame(pol[i]) + "x";
continue;
}
result += "" + dame(pol[i]) + "x^" + i;
}
continue;
}
if (pol[i] < 0){
if(i==1){
result += dame(pol[i]) + "x";
continue;
}
result += dame(pol[i]) + "x^" + i;
continue;
}
if(i==1){
result += "+" + dame(pol[i])+ "x";
continue;
}
if(result.isEmpty()){
result += "" + dame(pol[i])+ "x^" + i;
continue;
}
result += "+" + dame(pol[i])+ "x^" + i;
}
return result;
}
private static String dame(int n){
if(n<0){
return n==-1 ? "-":n+"";
}else{
return n==1 ? "":n+"";
}
}
}
|