-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCalculate.java
More file actions
446 lines (412 loc) · 17.1 KB
/
Copy pathCalculate.java
File metadata and controls
446 lines (412 loc) · 17.1 KB
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
import java.util.ArrayList;
import java.util.Arrays;
import util.ReadTextFile;
//import java.util.Scanner;
import java.io.File;
public class Calculate
{
private Figure basic;
private String solveFor;
private ArrayList<Equation> equations;
private Equation currEq;
/**
* @param base The figure to calculate on
* @param solve The variable to solve for
*/
public Calculate(Figure base, String solve)
{
basic = base;
equations = getFormulasFromFile();
setUnknownVariable(solve.trim());
}
public Calculate(Figure base)
{
basic = base;
equations = getFormulasFromFile();
setUnknownVariable("mass");
}
/**
* Reads all formulas fromthe file
*
* @return A list of Equations
*/
public ArrayList<Equation> getFormulasFromFile()
{
ReadTextFile read_file = new ReadTextFile("formulas3.txt");
ArrayList<Equation> vvv = new ArrayList<Equation>();
String currEq = read_file.readLine();
while(!read_file.EOF())
{
vvv.add(new Equation(new ArrayList<String>(Arrays.asList(currEq.split(",")))));
currEq = read_file.readLine();
}
read_file.close();
return vvv;
}
public ArrayList<Equation> getAllFormulas()
{
return equations;
}
public Equation getCurrEq()
{
return currEq;
}
public void setUnknownVariable(String solveFor)
{
this.solveFor = solveFor.trim();
int uk = 99999;
Equation blank = currEq;
for(Equation e: equations)
{
if(e.countUnknowns(basic) < uk && e.hasVariable(solveFor))
blank = e;
}
currEq = blank;
}
public Equation getEquationToUse()
{
for(Equation e: equations)
{
if(e.hasVariable(solveFor))
{
e.switchBase(solveFor);
boolean use = true;
for(String parts:e.getRequiredVars())
{
if(basic.getVar(parts) == null || parts.equals(solveFor))
use = false;
else if(!basic.getVar(parts).isKnown())
use = false;
}
if(use) return e;
}
}
return null;
}
public boolean solve()
{
Equation solutionGuide = getEquationToUse();
if(solutionGuide == null)
return false;
//gettting equation to use ***IF MORE THAN 1 EQUATION HAS SOLVEFOR, THIS METHOD WILL TAKE FIRST EQUATION***
currEq = solutionGuide;
currEq.switchBase(solveFor);
//determining vectors or not
String result = "";
Double angle = basic.getVar(solveFor).getAngle();
if(currEq.isVector(basic))
{
ArrayList<String> directions = solutionGuide.getCompForms();
ArrayList<String> ans = new ArrayList<String>(2);
for(int index = 0; index < directions.size(); index++)
{
String modified = variableReplaceBefore(directions.get(index));
ans.add(index,findValueOfEquation(modified));
}
Double tmpResult = 0.0;
for(String comp:ans)
{
if(Variable.canBeDouble(comp))
tmpResult += Double.parseDouble(comp) * Double.parseDouble(comp);
else
return false;
}
result = Math.sqrt(tmpResult)+"";
angle = Math.toDegrees(Math.atan2(Double.parseDouble(ans.get(0)),Double.parseDouble(ans.get(1))));
}
else
{
result = findValueOfEquation(variableReplaceBefore(solutionGuide.getEq()));
}
if(Variable.canBeDouble(result))
{
basic.getVar(solveFor).setVandA(result,angle);
basic.getVar(solveFor).setSolved(true);
}
return true;
}
public String findValueOfEquation(String eq)
{
String partToMessWith = eq;
boolean go = true;
while(partToMessWith.lastIndexOf("[") >= 0 && go)
{
String original = partToMessWith;
String fx = partToMessWith.substring(partToMessWith.lastIndexOf("[")-3,partToMessWith.lastIndexOf("["));
partToMessWith = partToMessWith.substring(0,partToMessWith.lastIndexOf("[")-3) + partToMessWith.substring(partToMessWith.lastIndexOf("["));
int index2 = partToMessWith.lastIndexOf("[");
String s2 = partToMessWith.substring(index2+1,partToMessWith.substring(index2).indexOf("]")+index2);
String ns2 = partToMessWith.substring(0,partToMessWith.lastIndexOf("["+s2+"]"))+partToMessWith.substring(partToMessWith.lastIndexOf("["+s2+"]")+s2.length()+2);
//Here, we decide whether or not we need to sovle before running the fucntion, or we need the actual variable name
if(fx.equals("dot") || fx.equals("crs") || fx.equals("ang")|| fx.equals("der")) // <-- Inner function non-numerical
partToMessWith = ns2.substring(0,index2) + solveFunc(fx,s2)+ns2.substring(index2);
else
partToMessWith = ns2.substring(0,index2) + solveFunc(fx,findValueOfEquation(s2))+ns2.substring(index2);
if(partToMessWith.equals(original))
go = false;
}
go = true;
while(partToMessWith.lastIndexOf("(") >=0 && go)
{
String original = partToMessWith;
int indx = partToMessWith.lastIndexOf("(");
String solve = partToMessWith.substring(indx+1,partToMessWith.substring(indx).indexOf(")")+indx);
//Got to replace replace
//String nosolve = partToMessWith.replace("("+solve+")","");
String nosolve = partToMessWith.substring(0,indx)+partToMessWith.substring(indx+solve.length()+2);
String valueToGet = getFinalVarValue(solve,"");
partToMessWith = nosolve.substring(0,indx)+getValue(valueToGet)+nosolve.substring(indx);
if(partToMessWith.equals(original))
go = true;
}
return getValue(getFinalVarValue(partToMessWith,""));
}
/**
* This parses functions such as trigonometrics(in degrees),
* various roots, and others.
*
* @param fx The function in question
* @param value The parameter of fx
* @return The function's value
*/
public String solveFunc(String fx, String value)
{
try{
//Value is non numeric cases
if(fx.equals("ang"))
return ""+basic.getVar(value).getAngle();
else if(fx.equals("dot"))
{
String[] products = value.split("\\*");
return "("+value+"*cos[ang["+products[0]+"]-ang["+products[1]+"]])";
}
else if(fx.equals("crs"))
{
String[] products = value.split("\\*");
return "("+value+"*sin[ang["+products[0]+"]-ang["+products[1]+"]])";
}
else if(fx.equals("der"))
{
Equation e = new Equation("null="+variableReplaceBefore(value));
Derivative ddx = new Derivative(e, "time");
return ddx.getDerivative();
}
double val = Double.parseDouble(getValue(value));
if(fx.equals("sqt"))
return ""+Math.sqrt(val);
else if(fx.equals("cos"))
return ""+Math.cos(Math.toRadians(val));
else if(fx.equals("sin"))
return ""+Math.sin(Math.toRadians(val));
else if(fx.equals("tan"))
return ""+Math.tan(Math.toRadians(val));
else if(fx.equals("sec"))
return ""+(1/Math.cos(Math.toRadians(val)));
else if(fx.equals("cot"))
return ""+(1/Math.tan(Math.toRadians(val)));
else if(fx.equals("csc"))
return ""+(1/Math.sin(Math.toRadians(val)));
else if(fx.equals("log"))
return ""+Math.log(val);
else if(fx.substring(0,2).equals("lg"))
return ""+Math.log(val)/Math.log(Double.parseDouble(fx.substring(2)));
}catch(Exception e){e.printStackTrace(); return fx+"["+value+"]";}
return fx+"["+value+"]";
}
public String getValue(String eq)
{
// Return eq if double
try{
Double.parseDouble(eq);
return eq;
}catch(Exception e){}
// Operation Division
// Fixes -- or +-
for(int i = 0; i < eq.length()-1; i++)
{
if(eq.charAt(i) == '-' && eq.charAt(i+1) == '+')
eq = eq.substring(0,i+1)+eq.substring(i+2);
else if(eq.charAt(i) == '-' && eq.charAt(i+1) == '-')
eq = eq.substring(0,i)+"+"+eq.substring(i+2);
else if(eq.charAt(i) == '+' && eq.charAt(i+1) == '-')
eq = eq.substring(0,i)+eq.substring(i+1);
}
//Case for extra stuff that prohibits solving (should be no more of these at this point)
if(eq.indexOf("[") > -1)
{
String eq1 = "";
String funct = eq.substring(eq.indexOf("[")-3, eq.indexOf("["));
eq = findValueOfEquation(eq);
}
if(eq.indexOf("(") > -1)
return eq;
ArrayList<String> tmpArray = Equation.splitEquation(eq);
for(int i=1; i< tmpArray.size()-1;i++)
{
Object result;
if(tmpArray.get(i).equals("*"))
{
try{
result = Double.parseDouble(tmpArray.get(i-1)) * Double.parseDouble(tmpArray.get(i+1));
}catch(Exception e){ result = tmpArray.get(i-1) + "*" + tmpArray.get(i+1);}
tmpArray.set(i+1, result.toString());
tmpArray.remove(i-1); tmpArray.remove(i-1);
i-=2;
}
else if(tmpArray.get(i).equals("/"))
{
try{
result = Double.parseDouble(tmpArray.get(i-1)) / Double.parseDouble(tmpArray.get(i+1));
}catch(Exception e){result = tmpArray.get(i-1) + "/" + tmpArray.get(i+1); }
tmpArray.set(i+1, result.toString());
tmpArray.remove(i-1);
tmpArray.remove(i-1);
i-=2;
}
}
//System.out.println(tmpArray.toString());
for(int i=1; i < tmpArray.size()-1; i++)
{
Object result;
if(tmpArray.get(i).equals("+"))
{
try{
result = Double.parseDouble(tmpArray.get(i-1)) + Double.parseDouble(tmpArray.get(i+1));
}catch(Exception e){result = tmpArray.get(i-1) + "+" + tmpArray.get(i+1); }
tmpArray.set(i+1, result.toString());
}
else if(tmpArray.get(i).equals("-"))
{
try{
result = Double.parseDouble(tmpArray.get(i-1)) - Double.parseDouble(tmpArray.get(i+1));
}catch(Exception e){ result = tmpArray.get(i-1) + "-" + tmpArray.get(i+1);}
tmpArray.set(i+1, result.toString());
}
}
return tmpArray.get(tmpArray.size()-1);
}
public String getFinalVarValue(String eq, String origin)
{
ArrayList<String> partsOfEq = Equation.splitEquation(eq);
String depth = "";
for(String k: partsOfEq)
{
Variable v = basic.getVar(k);
if(origin.equals(""))
depth = k;
else
depth = origin;
if(v == null || v.canBeDouble(k) || v.getValue().toString().contains(k))
{/*Dont do anything*/}
else if(v.canBeDouble(v.getValue().toString()))
{
partsOfEq.set(partsOfEq.indexOf(k), Double.parseDouble(v.getValue().toString())+"");
}
else
{
//Possible Recursion for when a varaible is equal to another variable
if(!v.getValue().toString().contains(depth))
{
String blanket = v.getValue().toString();
partsOfEq.set(partsOfEq.indexOf(k),getFinalVarValue(blanket,depth));
}
else
{
if(partsOfEq.size() == 1)
return depth;
else
{
String combined = "";
for(String part: partsOfEq)
combined+=part;
return combined;
}
}
}
}
String combined = "";
for(String part: partsOfEq)
combined+=part;
return combined;
}
/**
* Takes all the varaibles on the figure, and combines them all
* into one variable to be used for calculations
*/
public void combineVariables()
{
ArrayList<Variable> allVars = basic.getVars();
for(int indexOfBase = 0; indexOfBase < allVars.size(); indexOfBase++)
{
Variable base = allVars.get(indexOfBase);
for(int indexOfCheck = 0; indexOfCheck < allVars.size(); indexOfCheck++)
{
Variable check = allVars.get(indexOfCheck);
// IF VARIABLE DEFINED AS STRING i.e. "time"
//Why does trim need to be called?
if(((base.isConstant() ||base.isSolved()) && (check.isConstant()||check.isSolved())) && !(base.getAngle() == null || check.getAngle() == null))
{
//To eliminate the ammount of time spent in recusriveCall/getFinalVarValue
String baseV = getFinalVarValue((base.getValue()+"").trim(),"");
String checkV = getFinalVarValue((check.getValue()+"").trim(),"");
if(base.canBeDouble(baseV) && check.canBeDouble(checkV) && (base.getName()+"").trim().equals((check.getName()+"").trim()) && !(indexOfBase == indexOfCheck))
{
base.setValue(baseV);
check.setValue(checkV);
double finalAnswer = 0.0;
Double finalAngle = 0.0;
//If the variables have the same angle, they can just be added together. (Even if they are scalars)
if(base.getAngle() == check.getAngle())
{
finalAngle = base.getAngle();
finalAnswer = Double.parseDouble(base.getValue()+"") + Double.parseDouble(check.getValue()+""); //Combine into first variable
}
else
{
double x = Double.parseDouble(base.getValue().toString()) * Math.cos(Math.toRadians(base.getAngle())) + Double.parseDouble(check.getValue().toString()) * Math.cos(Math.toRadians(check.getAngle()));
double y = Double.parseDouble(base.getValue().toString()) * Math.sin(Math.toRadians(base.getAngle())) + Double.parseDouble(check.getValue().toString()) * Math.sin(Math.toRadians(check.getAngle()));
finalAnswer = Math.sqrt((x*x) + (y*y));
finalAngle = Math.atan2(y,x);
}
//Combine into second var
//Making a new variable that has no ties to check
/*if(base.getAllComponents().size() == 0)
{
Variable whyCantIClone = new Variable(base.getName(), base.getVariableName(),base.getValue(),base.isConstant(),base.isEnvironmental());
whyCantIClone.setSolved(base.isSolved());
whyCantIClone.setUnits(base.getUnits());
whyCantIClone.setAngle(base.getAngle());
base.addOldVariable(whyCantIClone);
}*/
base.addOldVariable(check);
//Remove first instance
basic.getVars().remove(check);
//NEW METHOD FIX REMOVING INCORRECT
ArrayList<Variable> all = basic.getAllSameVars(base.getName()+"");
for(Variable opt: all)
{
if(opt == base)
{
opt.setVandA(finalAnswer, Math.toDegrees(finalAngle));
break;
}
}
}
}
}
}
}
public String variableReplaceBefore(String eq)
{
String newEq = eq;
Equation usedOnlyForReq = new Equation(newEq);
for(String req: usedOnlyForReq.getRequiredVars())
{
if(!Variable.canBeDouble(req) && !(!basic.getVar(req).isKnown() || Variable.canBeDouble(basic.getVar(req).getValue()+"")))
{
newEq = newEq.replace(req, basic.getVar(req).getValue()+"");
}
}
return newEq;
}
}