Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2019
276
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 14.91 KB | None | 0 0
  1.  
  2. Save New Duplicate & Edit Just Text Twitter
  3. 1
  4. 2
  5. 3
  6. 4
  7. 5
  8. 6
  9. 7
  10. 8
  11. 9
  12. 10
  13. 11
  14. 12
  15. 13
  16. 14
  17. 15
  18. 16
  19. 17
  20. 18
  21. 19
  22. 20
  23. 21
  24. 22
  25. 23
  26. 24
  27. 25
  28. 26
  29. 27
  30. 28
  31. 29
  32. 30
  33. 31
  34. 32
  35. 33
  36. 34
  37. 35
  38. 36
  39. 37
  40. 38
  41. 39
  42. 40
  43. 41
  44. 42
  45. 43
  46. 44
  47. 45
  48. 46
  49. 47
  50. 48
  51. 49
  52. 50
  53. 51
  54. 52
  55. 53
  56. 54
  57. 55
  58. 56
  59. 57
  60. 58
  61. 59
  62. 60
  63. 61
  64. 62
  65. 63
  66. 64
  67. 65
  68. 66
  69. 67
  70. 68
  71. 69
  72. 70
  73. 71
  74. 72
  75. 73
  76. 74
  77. 75
  78. 76
  79. 77
  80. 78
  81. 79
  82. 80
  83. 81
  84. 82
  85. 83
  86. 84
  87. 85
  88. 86
  89. 87
  90. 88
  91. 89
  92. 90
  93. 91
  94. 92
  95. 93
  96. 94
  97. 95
  98. 96
  99. 97
  100. 98
  101. 99
  102. 100
  103. 101
  104. 102
  105. 103
  106. 104
  107. 105
  108. 106
  109. 107
  110. 108
  111. 109
  112. 110
  113. 111
  114. 112
  115. 113
  116. 114
  117. 115
  118. 116
  119. 117
  120. 118
  121. 119
  122. 120
  123. 121
  124. 122
  125. 123
  126. 124
  127. 125
  128. 126
  129. 127
  130. 128
  131. 129
  132. 130
  133. 131
  134. 132
  135. 133
  136. 134
  137. 135
  138. 136
  139. 137
  140. 138
  141. 139
  142. 140
  143. 141
  144. 142
  145. 143
  146. 144
  147. 145
  148. 146
  149. 147
  150. 148
  151. 149
  152. 150
  153. 151
  154. 152
  155. 153
  156. 154
  157. 155
  158. 156
  159. 157
  160. 158
  161. 159
  162. 160
  163. 161
  164. 162
  165. 163
  166. 164
  167. 165
  168. 166
  169. 167
  170. 168
  171. 169
  172. 170
  173. 171
  174. 172
  175. 173
  176. 174
  177. 175
  178. 176
  179. 177
  180. 178
  181. 179
  182. 180
  183. 181
  184. 182
  185. 183
  186. 184
  187. 185
  188. 186
  189. 187
  190. 188
  191. 189
  192. 190
  193. 191
  194. 192
  195. 193
  196. 194
  197. 195
  198. 196
  199. 197
  200. 198
  201. 199
  202. 200
  203. 201
  204. 202
  205. 203
  206. 204
  207. 205
  208. 206
  209. 207
  210. 208
  211. 209
  212. 210
  213. 211
  214. 212
  215. 213
  216. 214
  217. 215
  218. 216
  219. 217
  220. 218
  221. 219
  222. 220
  223. 221
  224. 222
  225. 223
  226. 224
  227. 225
  228. 226
  229. 227
  230. 228
  231. 229
  232. 230
  233. 231
  234. 232
  235. 233
  236. 234
  237. 235
  238. 236
  239. 237
  240. 238
  241. 239
  242. 240
  243. 241
  244. 242
  245. 243
  246. 244
  247. 245
  248. 246
  249. 247
  250. 248
  251. 249
  252. 250
  253. 251
  254. 252
  255. 253
  256. 254
  257. 255
  258. 256
  259. 257
  260. 258
  261. 259
  262. 260
  263. 261
  264. 262
  265. 263
  266. 264
  267. 265
  268. 266
  269. 267
  270. 268
  271. 269
  272. 270
  273. 271
  274. 272
  275. 273
  276. 274
  277. 275
  278. 276
  279. 277
  280. 278
  281. 279
  282. 280
  283. 281
  284. 282
  285. 283
  286. 284
  287. 285
  288. 286
  289. 287
  290. 288
  291. 289
  292. 290
  293. 291
  294. 292
  295. 293
  296. 294
  297. 295
  298. 296
  299. 297
  300. 298
  301. 299
  302. 300
  303. 301
  304. 302
  305. 303
  306. 304
  307. 305
  308. 306
  309. 307
  310. 308
  311. 309
  312. 310
  313. 311
  314. 312
  315. 313
  316. 314
  317. 315
  318. 316
  319. 317
  320. 318
  321. 319
  322. 320
  323. 321
  324. 322
  325. 323
  326. 324
  327. 325
  328. 326
  329. 327
  330. 328
  331. 329
  332. 330
  333. 331
  334. 332
  335. 333
  336. 334
  337. 335
  338. 336
  339. 337
  340. 338
  341. 339
  342. 340
  343. 341
  344. 342
  345. 343
  346. 344
  347. 345
  348. 346
  349. 347
  350. 348
  351. 349
  352. 350
  353. 351
  354. 352
  355. 353
  356. 354
  357. 355
  358. 356
  359. 357
  360. 358
  361. 359
  362. 360
  363. 361
  364. 362
  365. 363
  366. 364
  367. 365
  368. 366
  369. 367
  370. 368
  371. 369
  372. 370
  373. 371
  374. 372
  375. 373
  376. 374
  377. 375
  378. 376
  379. 377
  380. 378
  381. 379
  382. 380
  383. 381
  384. 382
  385. package app;
  386.  
  387. import java.io.*;
  388. import java.util.*;
  389. import java.util.regex.*;
  390.  
  391. import structures.Stack;
  392.  
  393. public class Expression {
  394.  
  395.     public static String delims = " \t*+-/()[]";
  396.            
  397.     /**
  398.      * Populates the vars list with simple variables, and arrays lists with arrays
  399.      * in the expression. For every variable (simple or array), a SINGLE instance is created
  400.      * and stored, even if it appears more than once in the expression.
  401.      * At this time, values for all variables and all array items are set to
  402.      * zero - they will be loaded from a file in the loadVariableValues method.
  403.      *
  404.      * @param expr The expression
  405.      * @param vars The variables array list - already created by the caller
  406.      * @param arrays The arrays array list - already created by the caller
  407.      */
  408.     public static void
  409.     makeVariableLists(String expr, ArrayList<Variable> vars, ArrayList<Array> arrays) {
  410.         /** COMPLETE THIS METHOD **/
  411.         /** DO NOT create new vars and arrays - they are already created before being sent in
  412.          ** to this method - you just need to fill them in.
  413.          **/
  414.         System.out.println(vars+"VAR | ARR"+arrays); //vars and arrays are already created but empty///// can delete after code done
  415.        
  416.         String exprNew = expr.trim(), currentItem;
  417.        
  418.         String delims2 = " \t*+-/()";
  419.         StringTokenizer st = new StringTokenizer(exprNew,delims2);
  420.        
  421.         while(st.hasMoreTokens()){
  422.             currentItem = st.nextToken();
  423.            
  424.              if ( currentItem.contains("[") ){
  425.                 int ArrNameStartingIndex = 0;
  426.                 boolean duplicateA = false;
  427.                  
  428.                 for (int j = 0; j < currentItem.length(); j ++) {
  429.                      
  430.                     if (currentItem.charAt(j)== '[') {
  431.                        
  432.                         if (arrays.size() == 0) {
  433.                                 arrays.add( new Array(currentItem.substring(ArrNameStartingIndex,j)) );
  434.                                 ArrNameStartingIndex = j + 1;
  435.                        
  436.                         }else if (arrays.size() != 0) {
  437.                             for (int k = 0; k < arrays.size(); k++) {
  438.                                 if (arrays.get(k).name.contentEquals(  currentItem.substring(ArrNameStartingIndex,j) ) ) {
  439.                                     ArrNameStartingIndex = j + 1;
  440.                                     duplicateA = true;
  441.                                 }
  442.                             }
  443.                             if (duplicateA == false) {
  444.                                 arrays.add( new Array(currentItem.substring(ArrNameStartingIndex,j)) );
  445.                                 ArrNameStartingIndex = j + 1;
  446.                             }
  447.                         }
  448.                      }else {
  449.                          continue;
  450.                      }
  451.                  }
  452.                  
  453.              }else if ( currentItem.matches("^[a-zA-Z]*$") ) {
  454.                
  455.                  //set duplicate boolean to false each time a possible variable is found
  456.                  boolean duplicateV = false;
  457.                  
  458.                  //if variablelist is empty, need not worry about duplicates
  459.                  if (vars.size() == 0) {
  460.                      vars.add( new Variable(currentItem) );
  461.                      
  462.                 // if variablelist has items, check each of them with current possible variable
  463.                      // if no matches found, add current p. var into list
  464.                  }else{
  465.                      for (int k = 0; k < vars.size(); k++) {
  466.                             if (vars.get(k).name.contentEquals(currentItem) ) {
  467.                                 duplicateV = true;
  468.                             }
  469.                     }
  470.                      if(duplicateV == false) {
  471.                         vars.add(new Variable(currentItem));
  472.                     }
  473.                  }
  474.                      
  475.              }else {
  476.                  continue;
  477.              }
  478.                      
  479.         }
  480.        
  481.         System.out.println(vars+"VAR | ARR"+arrays); // vars and arrays should now be filled/////
  482.     }
  483.    
  484.     /**
  485.      * Loads values for variables and arrays in the expression
  486.      *
  487.      * @param sc Scanner for values input
  488.      * @throws IOException If there is a problem with the input
  489.      * @param vars The variables array list, previously populated by makeVariableLists
  490.      * @param arrays The arrays array list - previously populated by makeVariableLists
  491.      */
  492.     public static void
  493.     loadVariableValues(Scanner sc, ArrayList<Variable> vars, ArrayList<Array> arrays)
  494.     throws IOException {
  495.         while (sc.hasNextLine()) {
  496.             StringTokenizer st = new StringTokenizer(sc.nextLine().trim());
  497.             int numTokens = st.countTokens();
  498.             String tok = st.nextToken();
  499.             Variable var = new Variable(tok);
  500.             Array arr = new Array(tok);
  501.             int vari = vars.indexOf(var);
  502.             int arri = arrays.indexOf(arr);
  503.             if (vari == -1 && arri == -1) {
  504.                 continue;
  505.             }
  506.             int num = Integer.parseInt(st.nextToken());
  507.             if (numTokens == 2) { // scalar symbol
  508.                 vars.get(vari).value = num;
  509.             } else { // array symbol
  510.                 arr = arrays.get(arri);
  511.                 arr.values = new int[num];
  512.                 // following are (index,val) pairs
  513.                 while (st.hasMoreTokens()) {
  514.                     tok = st.nextToken();
  515.                     StringTokenizer stt = new StringTokenizer(tok," (,)");
  516.                     int index = Integer.parseInt(stt.nextToken());
  517.                     int val = Integer.parseInt(stt.nextToken());
  518.                     arr.values[index] = val;              
  519.                 }
  520.             }
  521.         }
  522.     }
  523.    
  524.     /**
  525.      * Evaluates the expression.
  526.      *
  527.      * @param vars The variables array list, with values for all variables in the expression
  528.      * @param arrays The arrays array list, with values for all array items
  529.      * @return Result of evaluation
  530.      */
  531.     public static float
  532.     evaluate(String expr, ArrayList<Variable> vars, ArrayList<Array> arrays) {
  533.         /** COMPLETE THIS METHOD **/
  534.         String currentItem = "";
  535.        
  536.        
  537.         // builds expr array list // treat brackets as letters
  538.         ArrayList<String> exprArrL = new ArrayList<>();
  539.         String matchSet = "[a-zA-Z0-9\\[\\]]*";
  540.        
  541.         String prev = Character.toString(expr.charAt(0));
  542.         String current = "";
  543.         currentItem += prev;
  544.        
  545.         for (int i = 1; i < expr.length(); i ++) {
  546.            
  547.             current = Character.toString(expr.charAt(i));
  548.            
  549.             //CHARACTER1prev is letter + CHARACTER2curris letter
  550.             if ( current.matches(matchSet) && current.matches(matchSet) ) {
  551.            
  552.                 currentItem += current;
  553.                 prev = current;
  554.                    
  555.             //CHARACTER1prev is not letter(operator or parenthesis or bracket) + CHARACTER2curr is letter
  556.             }else if ( current.matches(matchSet) && !current.matches(matchSet)) {
  557.                
  558.                 currentItem += current;
  559.                 prev = current;
  560.            
  561.             //current is not letter(operator or parenthesis or bracket)
  562.             }else if ( !current.matches(matchSet) )  {
  563.                
  564.                 if (currentItem!= "") {
  565.                     exprArrL.add(currentItem);
  566.                 }
  567.                 currentItem = "";
  568.                 exprArrL.add(current);
  569.                 prev = current;
  570.             }  
  571.         }
  572.         if (currentItem!= "") {
  573.             exprArrL.add(currentItem);
  574.         }
  575.            
  576.         // exprArrList done building / can now evaluate/////////////////////////////////////////////////////
  577.        
  578.         Stack<String> operators = new Stack<String>();
  579.         Stack<Integer> numbers = new Stack<Integer>();
  580.        
  581.        
  582.        
  583.             for (int x = 0; x < exprArrL.size(); x++) {
  584.                    
  585.                 currentItem = exprArrL.get(x);
  586.                
  587.                
  588.                 if ( currentItem.equals("(") ) {
  589.                 operators.push(currentItem);
  590.                
  591.                 }else if (currentItem.equals(")")) {
  592.                       if (!operators.peek().equals("(") ) {
  593.                          numbers.push(applyOperation(operators.pop(), numbers.pop(), numbers.pop()));
  594.                          operators.pop();
  595.                        }
  596.                        
  597.                       //array needs evaluation before push
  598.                 }else if ( currentItem.contains("[") ){
  599.                     currentItem = Integer.toString(convertArray(currentItem, arrays, vars)) ;
  600.                     pushNum(currentItem,vars,numbers);
  601.                    
  602.                     // push operator into ops stack
  603.                 }else if (currentItem.equals( "+") || currentItem.equals( "-" )|| currentItem.equals( "*" )|| currentItem.equals( "/")) {
  604.                        // While top of 'ops' has same or greater precedence to current
  605.                        // token, which is an operator. Apply operator on top of 'ops'
  606.                        // to top two elements in values stack
  607.                        while (!operators.isEmpty() && hasPrecedence(currentItem, operators.peek()))
  608.                            numbers.push(applyOperation(operators.pop(), numbers.pop(), numbers.pop()));
  609.          
  610.                        // Push current token to 'ops'.
  611.                        operators.push(currentItem);
  612.                
  613.                        //variable or num, can be pushed in
  614.                 }else {
  615.                     pushNum(currentItem,vars,numbers);
  616.                    
  617.                 }
  618.                
  619.             }
  620.             while (!operators.isEmpty())
  621.                 numbers.push(applyOperation(operators.pop(), numbers.pop(), numbers.pop()));
  622.      
  623.             // Top of 'values' contains result, return it
  624.             return numbers.pop();
  625.            
  626.         }
  627.        
  628.    
  629.    
  630.     private static void pushNum(String currentItem, ArrayList<Variable> vars, Stack<Integer> numbers ) {
  631.        
  632.         //variable -push num value
  633.         if (currentItem.matches("^[a-zA-Z]*$")){
  634.             for(int v = 0; v < vars.size() ; v ++) {
  635.                 if (vars.get(v).name.contentEquals( currentItem ) ) {
  636.                     numbers.push(vars.get(v).value);
  637.                 }
  638.             }
  639.    
  640.         //is a number - push num value
  641.         }else{
  642.             numbers.push(Integer.parseInt(currentItem));
  643.         }
  644.     }
  645.    
  646.     private static int convertArray(String inputArrayStr0, ArrayList<Array> arrays, ArrayList<Variable> vars ) {
  647.         int ans = 0;
  648.        
  649.         while (inputArrayStr0.contains("[") ) {
  650.             int starti = 0, endi = 0, lenName = 0;
  651.            
  652.             inputArrayStr0 += " ";
  653.            
  654.             for (int s = 0; s<inputArrayStr0.length(); s++) {
  655.                 if ( Character.isLetter(inputArrayStr0.charAt(s) ) ||  Character.isDigit(inputArrayStr0.charAt(s) ) ){
  656.                     lenName++;
  657.                 }else if (inputArrayStr0.charAt(s) == '[') {
  658.                     starti = s-lenName;
  659.                     lenName = 0;
  660.                 }else if (inputArrayStr0.charAt(s) == ']') {
  661.                     endi = s+1;
  662.                     break;
  663.                 }
  664.             }
  665.            
  666.             String inputArrayStr =  inputArrayStr0.substring(starti,endi);
  667.             String inputArrayName = "";
  668.             String currentItem = "";
  669.            
  670.             /////////////////////////////////////gggggggggggggggggggggggggg
  671.             if (inputArrayStr.contains("(") ){
  672.                 Stack<String> operators = new Stack<String>();
  673.                 Stack<Integer> numbers = new Stack<Integer>();
  674.                
  675.                 StringTokenizer st = new StringTokenizer(inputArrayStr,"");
  676.                    
  677.                     while (st.hasMoreTokens()) {
  678.                         currentItem = st.nextToken();
  679.                        
  680.                         if (currentItem.equals( "+") || currentItem.equals( "-" )|| currentItem.equals( "*" )|| currentItem.equals( "/")) {
  681.                            // While top of 'ops' has same or greater precedence to current
  682.                            // token, which is an operator. Apply operator on top of 'ops'
  683.                            // to top two elements in values stack
  684.                            while (!operators.isEmpty() && hasPrecedence(currentItem, operators.peek())) {
  685.                                numbers.push(applyOperation(operators.pop(), numbers.pop(), numbers.pop()));
  686.              
  687.                            // Push current token to 'ops'.
  688.                            operators.push(currentItem);
  689.                            }
  690.                
  691.                        //variable or num, can be pushed in
  692.                         }else {
  693.                             pushNum(currentItem,vars,numbers);
  694.                         }
  695.                     }
  696.                     while (!operators.isEmpty())
  697.                         numbers.push(applyOperation(operators.pop(), numbers.pop(), numbers.pop()));
  698.              
  699.                     int result = numbers.pop();
  700.                    
  701.                 }
  702.    
  703.            
  704.        
  705.            
  706.             // take in something like "b[0]"
  707.             int start = 0, end = 0;
  708.             String numberInBracketS = "";
  709.             int numberInBracket = 0;
  710.            
  711.             //////////////////////////////////////////////////////////evaluates innermost b[0]
  712.             for (int i = 0; i<inputArrayStr.length(); i++) {
  713.                 if (inputArrayStr.charAt(i) == '[') {
  714.                     start = i + 1;
  715.                 }
  716.                 if (inputArrayStr.charAt(i) == ']') {
  717.                     end = i;
  718.                 }
  719.             }
  720.             numberInBracketS = inputArrayStr.substring(start,end);
  721.             numberInBracket = Integer.parseInt(numberInBracketS);
  722.             inputArrayName = inputArrayStr.substring(0,start-1);
  723.            
  724.             for (int a = 0; a < arrays.size() ; a ++) {
  725.                 if (arrays.get(a).name.equals(inputArrayName) ){
  726.                             ans = arrays.get(a).values[numberInBracket];   
  727.                 }
  728.             }
  729.             ///////////////////////////////////////////////////////////////
  730.            
  731.             inputArrayStr0= inputArrayStr0.replace(inputArrayStr,Integer.toString(ans));
  732.         }
  733.         return ans;
  734.     }
  735.    
  736.     private static int applyOperation(String op, int  b, int a) {
  737.        
  738.        
  739.         switch (op)
  740.         {
  741.         case "+":
  742.             return a + b;
  743.         case "-":
  744.             return a - b;
  745.         case "*":
  746.             return a * b;
  747.         case "/":
  748.             if (b == 0)
  749.                 throw new
  750.                 UnsupportedOperationException("Cannot divide by zero");
  751.             return a / b;
  752.         }
  753.         return 0;
  754.     }
  755.    
  756.     private static boolean hasPrecedence(String op1, String op2)
  757.     {
  758.         if (op2.equals("(") || op2.equals( ")"))
  759.             return false;
  760.         if ((op1.equals( "*") || op1.equals( "/")) && (op2.equals( "+" )|| op2.equals( "-")) )
  761.             return false;
  762.         else
  763.             return true;
  764.     }
  765. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement