Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Save New Duplicate & Edit Just Text Twitter
- 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
- package app;
- import java.io.*;
- import java.util.*;
- import java.util.regex.*;
- import structures.Stack;
- public class Expression {
- public static String delims = " \t*+-/()[]";
- /**
- * Populates the vars list with simple variables, and arrays lists with arrays
- * in the expression. For every variable (simple or array), a SINGLE instance is created
- * and stored, even if it appears more than once in the expression.
- * At this time, values for all variables and all array items are set to
- * zero - they will be loaded from a file in the loadVariableValues method.
- *
- * @param expr The expression
- * @param vars The variables array list - already created by the caller
- * @param arrays The arrays array list - already created by the caller
- */
- public static void
- makeVariableLists(String expr, ArrayList<Variable> vars, ArrayList<Array> arrays) {
- /** COMPLETE THIS METHOD **/
- /** DO NOT create new vars and arrays - they are already created before being sent in
- ** to this method - you just need to fill them in.
- **/
- System.out.println(vars+"VAR | ARR"+arrays); //vars and arrays are already created but empty///// can delete after code done
- String exprNew = expr.trim(), currentItem;
- String delims2 = " \t*+-/()";
- StringTokenizer st = new StringTokenizer(exprNew,delims2);
- while(st.hasMoreTokens()){
- currentItem = st.nextToken();
- if ( currentItem.contains("[") ){
- int ArrNameStartingIndex = 0;
- boolean duplicateA = false;
- for (int j = 0; j < currentItem.length(); j ++) {
- if (currentItem.charAt(j)== '[') {
- if (arrays.size() == 0) {
- arrays.add( new Array(currentItem.substring(ArrNameStartingIndex,j)) );
- ArrNameStartingIndex = j + 1;
- }else if (arrays.size() != 0) {
- for (int k = 0; k < arrays.size(); k++) {
- if (arrays.get(k).name.contentEquals( currentItem.substring(ArrNameStartingIndex,j) ) ) {
- ArrNameStartingIndex = j + 1;
- duplicateA = true;
- }
- }
- if (duplicateA == false) {
- arrays.add( new Array(currentItem.substring(ArrNameStartingIndex,j)) );
- ArrNameStartingIndex = j + 1;
- }
- }
- }else {
- continue;
- }
- }
- }else if ( currentItem.matches("^[a-zA-Z]*$") ) {
- //set duplicate boolean to false each time a possible variable is found
- boolean duplicateV = false;
- //if variablelist is empty, need not worry about duplicates
- if (vars.size() == 0) {
- vars.add( new Variable(currentItem) );
- // if variablelist has items, check each of them with current possible variable
- // if no matches found, add current p. var into list
- }else{
- for (int k = 0; k < vars.size(); k++) {
- if (vars.get(k).name.contentEquals(currentItem) ) {
- duplicateV = true;
- }
- }
- if(duplicateV == false) {
- vars.add(new Variable(currentItem));
- }
- }
- }else {
- continue;
- }
- }
- System.out.println(vars+"VAR | ARR"+arrays); // vars and arrays should now be filled/////
- }
- /**
- * Loads values for variables and arrays in the expression
- *
- * @param sc Scanner for values input
- * @throws IOException If there is a problem with the input
- * @param vars The variables array list, previously populated by makeVariableLists
- * @param arrays The arrays array list - previously populated by makeVariableLists
- */
- public static void
- loadVariableValues(Scanner sc, ArrayList<Variable> vars, ArrayList<Array> arrays)
- throws IOException {
- while (sc.hasNextLine()) {
- StringTokenizer st = new StringTokenizer(sc.nextLine().trim());
- int numTokens = st.countTokens();
- String tok = st.nextToken();
- Variable var = new Variable(tok);
- Array arr = new Array(tok);
- int vari = vars.indexOf(var);
- int arri = arrays.indexOf(arr);
- if (vari == -1 && arri == -1) {
- continue;
- }
- int num = Integer.parseInt(st.nextToken());
- if (numTokens == 2) { // scalar symbol
- vars.get(vari).value = num;
- } else { // array symbol
- arr = arrays.get(arri);
- arr.values = new int[num];
- // following are (index,val) pairs
- while (st.hasMoreTokens()) {
- tok = st.nextToken();
- StringTokenizer stt = new StringTokenizer(tok," (,)");
- int index = Integer.parseInt(stt.nextToken());
- int val = Integer.parseInt(stt.nextToken());
- arr.values[index] = val;
- }
- }
- }
- }
- /**
- * Evaluates the expression.
- *
- * @param vars The variables array list, with values for all variables in the expression
- * @param arrays The arrays array list, with values for all array items
- * @return Result of evaluation
- */
- public static float
- evaluate(String expr, ArrayList<Variable> vars, ArrayList<Array> arrays) {
- /** COMPLETE THIS METHOD **/
- String currentItem = "";
- // builds expr array list // treat brackets as letters
- ArrayList<String> exprArrL = new ArrayList<>();
- String matchSet = "[a-zA-Z0-9\\[\\]]*";
- String prev = Character.toString(expr.charAt(0));
- String current = "";
- currentItem += prev;
- for (int i = 1; i < expr.length(); i ++) {
- current = Character.toString(expr.charAt(i));
- //CHARACTER1prev is letter + CHARACTER2curris letter
- if ( current.matches(matchSet) && current.matches(matchSet) ) {
- currentItem += current;
- prev = current;
- //CHARACTER1prev is not letter(operator or parenthesis or bracket) + CHARACTER2curr is letter
- }else if ( current.matches(matchSet) && !current.matches(matchSet)) {
- currentItem += current;
- prev = current;
- //current is not letter(operator or parenthesis or bracket)
- }else if ( !current.matches(matchSet) ) {
- if (currentItem!= "") {
- exprArrL.add(currentItem);
- }
- currentItem = "";
- exprArrL.add(current);
- prev = current;
- }
- }
- if (currentItem!= "") {
- exprArrL.add(currentItem);
- }
- // exprArrList done building / can now evaluate/////////////////////////////////////////////////////
- Stack<String> operators = new Stack<String>();
- Stack<Integer> numbers = new Stack<Integer>();
- for (int x = 0; x < exprArrL.size(); x++) {
- currentItem = exprArrL.get(x);
- if ( currentItem.equals("(") ) {
- operators.push(currentItem);
- }else if (currentItem.equals(")")) {
- if (!operators.peek().equals("(") ) {
- numbers.push(applyOperation(operators.pop(), numbers.pop(), numbers.pop()));
- operators.pop();
- }
- //array needs evaluation before push
- }else if ( currentItem.contains("[") ){
- currentItem = Integer.toString(convertArray(currentItem, arrays, vars)) ;
- pushNum(currentItem,vars,numbers);
- // push operator into ops stack
- }else if (currentItem.equals( "+") || currentItem.equals( "-" )|| currentItem.equals( "*" )|| currentItem.equals( "/")) {
- // While top of 'ops' has same or greater precedence to current
- // token, which is an operator. Apply operator on top of 'ops'
- // to top two elements in values stack
- while (!operators.isEmpty() && hasPrecedence(currentItem, operators.peek()))
- numbers.push(applyOperation(operators.pop(), numbers.pop(), numbers.pop()));
- // Push current token to 'ops'.
- operators.push(currentItem);
- //variable or num, can be pushed in
- }else {
- pushNum(currentItem,vars,numbers);
- }
- }
- while (!operators.isEmpty())
- numbers.push(applyOperation(operators.pop(), numbers.pop(), numbers.pop()));
- // Top of 'values' contains result, return it
- return numbers.pop();
- }
- private static void pushNum(String currentItem, ArrayList<Variable> vars, Stack<Integer> numbers ) {
- //variable -push num value
- if (currentItem.matches("^[a-zA-Z]*$")){
- for(int v = 0; v < vars.size() ; v ++) {
- if (vars.get(v).name.contentEquals( currentItem ) ) {
- numbers.push(vars.get(v).value);
- }
- }
- //is a number - push num value
- }else{
- numbers.push(Integer.parseInt(currentItem));
- }
- }
- private static int convertArray(String inputArrayStr0, ArrayList<Array> arrays, ArrayList<Variable> vars ) {
- int ans = 0;
- while (inputArrayStr0.contains("[") ) {
- int starti = 0, endi = 0, lenName = 0;
- inputArrayStr0 += " ";
- for (int s = 0; s<inputArrayStr0.length(); s++) {
- if ( Character.isLetter(inputArrayStr0.charAt(s) ) || Character.isDigit(inputArrayStr0.charAt(s) ) ){
- lenName++;
- }else if (inputArrayStr0.charAt(s) == '[') {
- starti = s-lenName;
- lenName = 0;
- }else if (inputArrayStr0.charAt(s) == ']') {
- endi = s+1;
- break;
- }
- }
- String inputArrayStr = inputArrayStr0.substring(starti,endi);
- String inputArrayName = "";
- String currentItem = "";
- /////////////////////////////////////gggggggggggggggggggggggggg
- if (inputArrayStr.contains("(") ){
- Stack<String> operators = new Stack<String>();
- Stack<Integer> numbers = new Stack<Integer>();
- StringTokenizer st = new StringTokenizer(inputArrayStr,"");
- while (st.hasMoreTokens()) {
- currentItem = st.nextToken();
- if (currentItem.equals( "+") || currentItem.equals( "-" )|| currentItem.equals( "*" )|| currentItem.equals( "/")) {
- // While top of 'ops' has same or greater precedence to current
- // token, which is an operator. Apply operator on top of 'ops'
- // to top two elements in values stack
- while (!operators.isEmpty() && hasPrecedence(currentItem, operators.peek())) {
- numbers.push(applyOperation(operators.pop(), numbers.pop(), numbers.pop()));
- // Push current token to 'ops'.
- operators.push(currentItem);
- }
- //variable or num, can be pushed in
- }else {
- pushNum(currentItem,vars,numbers);
- }
- }
- while (!operators.isEmpty())
- numbers.push(applyOperation(operators.pop(), numbers.pop(), numbers.pop()));
- int result = numbers.pop();
- }
- // take in something like "b[0]"
- int start = 0, end = 0;
- String numberInBracketS = "";
- int numberInBracket = 0;
- //////////////////////////////////////////////////////////evaluates innermost b[0]
- for (int i = 0; i<inputArrayStr.length(); i++) {
- if (inputArrayStr.charAt(i) == '[') {
- start = i + 1;
- }
- if (inputArrayStr.charAt(i) == ']') {
- end = i;
- }
- }
- numberInBracketS = inputArrayStr.substring(start,end);
- numberInBracket = Integer.parseInt(numberInBracketS);
- inputArrayName = inputArrayStr.substring(0,start-1);
- for (int a = 0; a < arrays.size() ; a ++) {
- if (arrays.get(a).name.equals(inputArrayName) ){
- ans = arrays.get(a).values[numberInBracket];
- }
- }
- ///////////////////////////////////////////////////////////////
- inputArrayStr0= inputArrayStr0.replace(inputArrayStr,Integer.toString(ans));
- }
- return ans;
- }
- private static int applyOperation(String op, int b, int a) {
- switch (op)
- {
- case "+":
- return a + b;
- case "-":
- return a - b;
- case "*":
- return a * b;
- case "/":
- if (b == 0)
- throw new
- UnsupportedOperationException("Cannot divide by zero");
- return a / b;
- }
- return 0;
- }
- private static boolean hasPrecedence(String op1, String op2)
- {
- if (op2.equals("(") || op2.equals( ")"))
- return false;
- if ((op1.equals( "*") || op1.equals( "/")) && (op2.equals( "+" )|| op2.equals( "-")) )
- return false;
- else
- return true;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement