Advertisement
Guest User

Untitled

a guest
Oct 13th, 2015
277
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.26 KB | None | 0 0
  1. package apps;
  2.  
  3. import java.io.IOException;
  4. import java.util.ArrayList;
  5. import java.util.NoSuchElementException;
  6. import java.util.Scanner;
  7. import java.util.StringTokenizer;
  8.  
  9. import structures.Stack;
  10.  
  11. public class Expression {
  12.  
  13. /**
  14. * Expression to be evaluated
  15. */
  16. String expr;
  17.  
  18. /**
  19. * Scalar symbols in the expression
  20. */
  21. ArrayList<ScalarSymbol> scalars;
  22.  
  23. /**
  24. * Array symbols in the expression
  25. */
  26. ArrayList<ArraySymbol> arrays;
  27.  
  28. /**
  29. * Positions of opening brackets
  30. */
  31. ArrayList<Integer> openingBracketIndex;
  32.  
  33. /**
  34. * Positions of closing brackets
  35. */
  36. ArrayList<Integer> closingBracketIndex;
  37.  
  38. /**
  39. * String containing all delimiters (characters other than variables and constants),
  40. * to be used with StringTokenizer
  41. */
  42. public static final String delims = " \t*+-/()[]";
  43.  
  44. /**
  45. * Initializes this Expression object with an input expression. Sets all other
  46. * fields to null.
  47. *
  48. * @param expr Expression
  49. */
  50. public Expression(String expr) {
  51. this.expr = expr;
  52. scalars = null;
  53. arrays = null;
  54. openingBracketIndex = null;
  55. closingBracketIndex = null;
  56. }
  57.  
  58. /**
  59. * Matches parentheses and square brackets. Populates the openingBracketIndex and
  60. * closingBracketIndex array lists in such a way that closingBracketIndex[i] is
  61. * the position of the bracket in the expression that closes an opening bracket
  62. * at position openingBracketIndex[i]. For example, if the expression is:
  63. * <pre>
  64. * (a+(b-c))*(d+A[4])
  65. * </pre>
  66. * then the method would return true, and the array lists would be set to:
  67. * <pre>
  68. * openingBracketIndex: [0 3 10 14]
  69. * closingBracketIndex: [8 7 17 16]
  70. * </pre>
  71. *
  72. * See the FAQ in project description for more details.
  73. *
  74. * @return True if brackets are matched correctly, false if not
  75. */
  76. public boolean isLegallyMatched() { // TODO: IDK if this is working 100% properly
  77. openingBracketIndex = new ArrayList<Integer>();
  78. closingBracketIndex = new ArrayList<Integer>();
  79.  
  80. matchParens(this.expr, 0);
  81.  
  82. return openingBracketIndex.size() == closingBracketIndex.size();
  83. }
  84.  
  85. private void matchParens(String expr, int orig) {
  86.  
  87. for(int i = 0; i < expr.length(); i++) {
  88.  
  89.  
  90. if(expr.charAt(i) == '(') {
  91. while(expr.charAt(i) != ')') {
  92.  
  93. }
  94. }
  95.  
  96.  
  97. }
  98. }
  99.  
  100. /**
  101. * Populates the scalars and arrays lists with symbols for scalar and array
  102. * variables in the expression. For every variable, a SINGLE symbol is created and stored,
  103. * even if it appears more than once in the expression.
  104. * At this time, the constructors for ScalarSymbol and ArraySymbol
  105. * will initialize values to zero and null, respectively.
  106. * The actual values will be loaded from a file in the loadSymbolValues method.
  107. */
  108. public void buildSymbols() {
  109. scalars = new ArrayList<ScalarSymbol>();
  110. arrays = new ArrayList<ArraySymbol>();
  111.  
  112. for (int i = 0; i < expr.length(); i++){
  113. if (Character.isLetter(expr.charAt(i))) {
  114. String currentSymbol = "";
  115. boolean isArray = false;
  116.  
  117. while (i < expr.length() && Character.isLetter(expr.charAt(i))){
  118. currentSymbol += expr.charAt(i);
  119. i++;
  120. }
  121.  
  122. if (i<expr.length() && expr.charAt(i) == '[') {
  123. arrays.add(new ArraySymbol(currentSymbol));
  124. } else {
  125. scalars.add(new ScalarSymbol(currentSymbol));
  126. }
  127. }
  128. }
  129. }
  130.  
  131. /**
  132. * Loads values for symbols in the expression
  133. *
  134. * @param sc Scanner for values input
  135. * @throws IOException If there is a problem with the input
  136. */
  137. public void loadSymbolValues(Scanner sc)
  138. throws IOException {
  139. while (sc.hasNextLine()) {
  140. StringTokenizer st = new StringTokenizer(sc.nextLine().trim());
  141. int numTokens = st.countTokens();
  142. String sym = st.nextToken();
  143. ScalarSymbol ssymbol = new ScalarSymbol(sym);
  144. ArraySymbol asymbol = new ArraySymbol(sym);
  145. int ssi = scalars.indexOf(ssymbol);
  146. int asi = arrays.indexOf(asymbol);
  147. if (ssi == -1 && asi == -1) {
  148. continue;
  149. }
  150. int num = Integer.parseInt(st.nextToken());
  151. if (numTokens == 2) { // scalar symbol
  152. scalars.get(ssi).value = num;
  153. } else { // array symbol
  154. asymbol = arrays.get(asi);
  155. asymbol.values = new int[num];
  156. // following are (index,val) pairs
  157. while (st.hasMoreTokens()) {
  158. String tok = st.nextToken();
  159. StringTokenizer stt = new StringTokenizer(tok," (,)");
  160. int index = Integer.parseInt(stt.nextToken());
  161. int val = Integer.parseInt(stt.nextToken());
  162. asymbol.values[index] = val;
  163. }
  164. }
  165. }
  166. }
  167.  
  168. /**
  169. * Evaluates the expression, using RECURSION to evaluate subexpressions and to evaluate array
  170. * subscript expressions. (Note: you can use one or more private helper methods
  171. * to implement the recursion.)
  172. *
  173. * @return Result of evaluation
  174. */
  175. public float evaluate() {
  176. // COMPLETE THIS METHOD
  177. printScalars();
  178. printArrays();
  179. String expression = expr;
  180. float ans = evaluate(expression);
  181.  
  182. try {
  183. return ans;
  184. } catch (Exception e){
  185. return 0;
  186. }
  187. }
  188.  
  189. private float evaluate(String expr) {
  190. StringTokenizer tokens= new StringTokenizer(expr, delims);
  191. Stack<String> expressions = new Stack<String>();
  192.  
  193. while(tokens.hasMoreTokens()){
  194. System.out.println(tokens.nextToken());
  195. }
  196. return 0.0f;
  197. }
  198.  
  199. // private float evaluate(String expr) { // private method made for recursive purposes
  200. // if(expr.length() == 1 && Character.isDigit(expr.charAt(0))) {
  201. // return (float) Character.getNumericValue(expr.charAt(0));
  202. // }
  203. //
  204. // Stack<Float> numStack = new Stack<Float>(); // num stack
  205. // Stack<Character> opStack = new Stack<Character>(); // char stack
  206. //
  207. // for (int i=0; i<expr.length();i++) {
  208. // if (expr.charAt(i) == '(') {
  209. // System.out.println("Before expr: " + expr);
  210. // int removed = openingBracketIndex.remove(0);
  211. // int openIdx = i;
  212. // int closeIdx = closingBracketIndex.remove(0);
  213. // int distance = closeIdx-removed;
  214. // int replacement = (int) evaluate(expr.substring(openIdx + 1, distance));
  215. // System.out.println(replacement);
  216. // expr = expr.substring(0, openIdx) + replacement + expr.substring(distance+1);
  217. // System.out.println("After expr: " + expr);
  218. // }
  219. //
  220. // if (Character.isDigit(expr.charAt(i))) {
  221. // String num = "";
  222. // int len = expr.length();
  223. // while((i < len) && (Character.isDigit(expr.charAt(i)))){
  224. // num += expr.charAt(i);
  225. // i++;
  226. // }
  227. //
  228. // numStack.push((float) Integer.parseInt(num));
  229. //
  230. // if(i == expr.length()) {
  231. // break;
  232. // }
  233. // }
  234. //
  235. // if (isOperand(expr.charAt(i))) {
  236. // opStack.push(expr.charAt(i));
  237. // }
  238. //
  239. // if (variableIndex(expr.charAt(i)) != -1 ) {
  240. // int num = variableIndex(expr.charAt(i));
  241. // numStack.push((float) scalars.get(num).value);
  242. // }
  243. // }
  244. //
  245. //
  246. // while(!(opStack.isEmpty())) {
  247. // float first = numStack.pop();
  248. // float second = numStack.pop();
  249. // switch(opStack.pop()) {
  250. // case '+':
  251. // // add
  252. // int addResult = (int) (second + first);
  253. // numStack.push((float) addResult);
  254. // break;
  255. // case '-':
  256. // // subtract
  257. // int subtractResult = (int) (second - first);
  258. // numStack.push((float) subtractResult);
  259. // break;
  260. // case '*':
  261. // // multiply
  262. // int multiplyResult = (int) (second * first);
  263. // numStack.push((float) multiplyResult);
  264. // break;
  265. // case '/':
  266. // // divide
  267. // int divideResult = (int) (second / first);
  268. // numStack.push((float) divideResult);
  269. // break;
  270. // default:
  271. // // do nothing
  272. // break;
  273. // };
  274. // }
  275. //
  276. // return numStack.pop();
  277. //
  278. // }
  279. //
  280.  
  281. private int variableIndex(char ch) {
  282. for (int i=0;i<scalars.size();i++) {
  283. if (Character.toString(ch).equals(scalars.get(i).name)) {
  284. return i;
  285. }
  286. }
  287.  
  288. return -1;
  289. }
  290.  
  291. private boolean isOperand(char ch) {
  292. return ch == '+' || ch == '-' || ch == '*' || ch == '/';
  293. }
  294.  
  295. /**
  296. * Utility method, prints the symbols in the scalars list
  297. */
  298. public void printScalars() {
  299. for (ScalarSymbol ss: scalars) {
  300. System.out.println(ss);
  301. }
  302. }
  303.  
  304. /**
  305. * Utility method, prints the symbols in the arrays list
  306. */
  307. public void printArrays() {
  308. for (ArraySymbol as: arrays) {
  309. System.out.println(as);
  310. }
  311. }
  312.  
  313. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement