예제 #1
0
  /**
   * Backtracking function that finds the location of the queens and back tracks if an acceptable
   * solution cannot be found
   *
   * @param startx x coordinate of the starting location
   * @param starty y coordinate of the starting location
   * @return
   */
  public boolean backTrack(int startx, int starty) {
    int j = startx;
    for (int i = starty; i < gridLength; ) {

      for (; j < gridLength; j++) {
        if (!killList.contains(i + "," + j)) {
          grid[i][j] = addToKillList(i, j);
          myStack.push(i + "," + j);
          continue;
        }
      }
      /*
       * Here we check if there are i queens in i rows, else we backtrack to the
       * previous decision point by assigning the values to i,j
       * Else we continue
       */
      if (myStack.size() > 0 && (i + 1) != myStack.size()) {
        String[] temp = myStack.pop().split(",");
        int x = Integer.parseInt(temp[0]);
        int y = Integer.parseInt(temp[1]);
        removeFromKillList(x, y);
        grid[x][y] = 0;

        i = x;
        j = y + 1;
      } else {
        i++;
        j = 0;
      }
    }

    if (numberofSpaces() == gridLength) return true;

    return false;
  }
 /**
  * Record the current state of the tree walk which includes the current node and stack state as
  * well as the lookahead buffer.
  */
 public int mark() {
   if (markers == null) {
     markers = new ArrayList();
     markers.add(null); // depth 0 means no backtracking, leave blank
   }
   markDepth++;
   TreeWalkState state = null;
   if (markDepth >= markers.size()) {
     state = new TreeWalkState();
     markers.add(state);
   } else {
     state = (TreeWalkState) markers.get(markDepth);
   }
   state.absoluteNodeIndex = absoluteNodeIndex;
   state.currentChildIndex = currentChildIndex;
   state.currentNode = currentNode;
   state.previousNode = previousNode;
   state.nodeStackSize = nodeStack.size();
   state.indexStackSize = indexStack.size();
   // take snapshot of lookahead buffer
   int n = getLookaheadSize();
   int i = 0;
   state.lookahead = new Object[n];
   for (int k = 1; k <= n; k++, i++) {
     state.lookahead[i] = LT(k);
   }
   lastMarker = markDepth;
   return markDepth;
 }
 private void checkForCollisionsWithTowers(Ring ring) {
   Stack stack = null;
   Sprite tower = null;
   if (ring.collidesWith(mTower1)
       && (mStack1.size() == 0 || ring.getmWeight() < ((Ring) mStack1.peek()).getmWeight())) {
     stack = mStack1;
     tower = mTower1;
   } else if (ring.collidesWith(mTower2)
       && (mStack2.size() == 0 || ring.getmWeight() < ((Ring) mStack2.peek()).getmWeight())) {
     stack = mStack2;
     tower = mTower2;
   } else if (ring.collidesWith(mTower3)
       && (mStack3.size() == 0 || ring.getmWeight() < ((Ring) mStack3.peek()).getmWeight())) {
     stack = mStack3;
     tower = mTower3;
   } else {
     stack = ring.getmStack();
     tower = ring.getmTower();
   }
   ring.getmStack().remove(ring);
   if (stack != null && tower != null && stack.size() == 0) {
     ring.setPosition(
         tower.getX() + tower.getWidth() / 2 - ring.getWidth() / 2,
         tower.getY() + tower.getHeight() - ring.getHeight());
   } else if (stack != null && tower != null && stack.size() > 0) {
     ring.setPosition(
         tower.getX() + tower.getWidth() / 2 - ring.getWidth() / 2,
         ((Ring) stack.peek()).getY() - ring.getHeight());
   }
   stack.add(ring);
   ring.setmStack(stack);
   ring.setmTower(tower);
 }
예제 #4
0
  public static String reverseWord(String words) {
    if (words == null || words.equalsIgnoreCase("")) return "";
    else {
      char[] chs = words.toCharArray();
      // System.out.println(new String(chs));
      Stack stack = new Stack();
      StringBuilder sb = new StringBuilder();
      for (int i = 0; i < chs.length; i++) {
        if (isChar(chs[i])) {
          stack.push(chs[i]);
        } else {
          while (stack.size() > 0) {
            sb.append(stack.pop());
          }
          sb.append(chs[i]);
        }
      }
      if (stack.size() > 0) {
        while (stack.size() > 0) {
          sb.append(stack.pop());
        }
      }

      return sb.toString();
    }
  }
예제 #5
0
  public int longestValidParentheses(String s) {
    Stack<String> paren = new Stack<String>();
    Stack<Integer> indexes = new Stack<Integer>();

    for (int i = 0; i < s.length(); i++) {
      if (paren.isEmpty()) {
        paren.push(String.valueOf((s.charAt(i))));
        indexes.push(i);
      } else if (s.charAt(i) == ')' && paren.peek().equals("(")) {
        paren.pop();
        indexes.pop();
      } else {
        paren.push(String.valueOf((s.charAt(i))));
        indexes.push(i);
      }
    }
    int rmax = 0;
    if (indexes.size() == 0) return s.length();
    for (int i = 0; i < indexes.size(); i++) {
      if (i == 0) {
        if (indexes.get(i) > rmax) rmax = indexes.get(i);
      } else {
        if (indexes.get(i) - indexes.get(i - 1) > rmax) rmax = indexes.get(i) - indexes.get(i - 1);
      }
      if (i == indexes.size() - 1) {
        if (s.length() - 1 - indexes.get(i) > rmax) rmax = s.length() - 1 - indexes.get(i);
      }
    }
    // System.out.println(indexes.size());
    return (rmax > 1) ? rmax : 0;
  }
예제 #6
0
  private void getIndentFromState(
      List<IndentCommand> iis, boolean updateState, int lineStartOffset) {
    Stack<TplStackItem> blockStack = getStack();

    int lastUnprocessedItem = blockStack.size();
    for (int i = blockStack.size() - 1; i >= 0; i--) {
      if (!blockStack.get(i).processed) {
        lastUnprocessedItem = i;
      } else {
        break;
      }
    }
    for (int i = lastUnprocessedItem; i < blockStack.size(); i++) {
      TplStackItem item = blockStack.get(i);
      assert !item.processed : item;
      if (item.state == StackItemState.IN_BODY) {
        IndentCommand ii = new IndentCommand(IndentCommand.Type.INDENT, lineStartOffset);
        if (item.indent != -1) {
          ii.setFixedIndentSize(item.indent);
        }
        iis.add(ii);
        if (updateState) {
          item.processed = Boolean.TRUE;
        }
      } else if (item.state == StackItemState.BODY_FINISHED) {
        IndentCommand ii = new IndentCommand(IndentCommand.Type.RETURN, lineStartOffset);
        iis.add(ii);
        if (updateState) {
          item.processed = Boolean.TRUE;
          blockStack.remove(i);
          i--;
        }
      }
    }
  }
  /**
   * &quot;Normalize&quot; the given absolute path.
   *
   * <p>This includes:
   *
   * <ul>
   *   <li>Uppercase the drive letter if there is one.
   *   <li>Remove redundant slashes after the drive spec.
   *   <li>Resolve all ./, .\, ../ and ..\ sequences.
   *   <li>DOS style paths that start with a drive letter will have \ as the separator.
   * </ul>
   *
   * Unlike {@link File#getCanonicalPath()} this method specifically does not resolve symbolic
   * links.
   *
   * @param path the path to be normalized.
   * @return the normalized version of the path.
   * @throws java.lang.NullPointerException if path is null.
   */
  public static File normalize(final String path) {
    Stack s = new Stack();
    String[] dissect = dissect(path);
    s.push(dissect[0]);

    StringTokenizer tok = new StringTokenizer(dissect[1], File.separator);
    while (tok.hasMoreTokens()) {
      String thisToken = tok.nextToken();
      if (".".equals(thisToken)) {
        continue;
      }
      if ("..".equals(thisToken)) {
        if (s.size() < 2) {
          // Cannot resolve it, so skip it.
          return new File(path);
        }
        s.pop();
      } else { // plain component
        s.push(thisToken);
      }
    }
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < s.size(); i++) {
      if (i > 1) {
        // not before the filesystem root and not after it, since root
        // already contains one
        sb.append(File.separatorChar);
      }
      sb.append(s.elementAt(i));
    }
    return new File(sb.toString());
  }
  @Override
  public void onClick(View v) {
    switch (v.getId()) {
      case R.id.back:
        prevId.pop();
        prevPath.pop();
        String present_path = prevPath.elementAt(prevPath.size() - 1);

        if (present_path.equalsIgnoreCase("HOME")) back.setEnabled(false);
        else back.setEnabled(true);
        int present_id = prevId.elementAt(prevId.size() - 1);
        Log.i("id", "" + present_id);
        Log.i("path", present_path);

        ArrayList<SearchResults> Results = getData(String.valueOf(present_id));
        adapt = new MyCustomBaseAdapter(SkydriveFolderList.this, Results);

        lv.setAdapter(adapt);
        adapt.notifyDataSetChanged();

        path.setText(present_path);

        break;
      case R.id.search:

        // getResult(et.getText().toString());

        break;
    }
    // TODO Auto-generated method stub

  }
  /** @see org.geotools.filter.FilterVisitor#visit(org.geotools.filter.FunctionExpression) */
  public Object visit(Function expression, Object notUsed) {
    if (!fcs.supports(expression.getClass())) {
      postStack.push(expression);
      return null;
    }

    if (expression.getName() == null) {
      postStack.push(expression);
      return null;
    }

    int i = postStack.size();
    int j = preStack.size();

    for (int k = 0; k < expression.getParameters().size(); k++) {
      ((Expression) expression.getParameters().get(i)).accept(this, null);

      if (i < postStack.size()) {
        while (j < preStack.size()) preStack.pop();
        postStack.pop();
        postStack.push(expression);

        return null;
      }
    }
    while (j < preStack.size()) preStack.pop();
    preStack.push(expression);
    return null;
  }
예제 #10
0
  public static void reset(boolean useMoreBuildings, boolean useEvenMoreBuildings) {
    GeneralSupply.useMoreBuildings = useMoreBuildings;
    GeneralSupply.useEvenMoreBuildings = useEvenMoreBuildings;
    stallsLeft.clear();
    stallsLeft.addAll(Arrays.asList(STALLS));
    if (!useEvenMoreBuildings) {
      stallsLeft.remove(stallsLeft.size() - 1);
    }
    if (!useMoreBuildings) {
      stallsLeft.remove(stallsLeft.size() - 1);
    }
    if (Main.DEBUG) {
      stallsLeft.clear();
      stallsLeft.add(STALLS[0]);
      stallsLeft.add(STALLS[1]);
    }
    Collections.shuffle(stallsLeft);

    troughsLeft = MAX_TROUGHS;

    extsLeft.clear();
    extsLeft.addAll(Arrays.asList(EXTS));
    if (!useEvenMoreBuildings) {
      extsLeft.remove(extsLeft.size() - 1);
    }
    if (!useMoreBuildings) {
      extsLeft.remove(extsLeft.size() - 1);
    }
    Collections.shuffle(extsLeft);
    extsUsed.clear();

    SPECIAL_BUILDINGS.clear(); // clear building instances
    randomizeBuildings(INITIAL_BUILDING_COUNTS);
  }
예제 #11
0
  private int recursive(
      Transaction txn,
      final String endProt,
      Stack<String> path,
      int bestDepth,
      final int maxDepth) {
    DatabaseEntry key = new DatabaseEntry();
    DatabaseEntry data = new DatabaseEntry();
    StringBinding.stringToEntry(path.lastElement(), key);
    if (this.database.get(txn, key, data, null) == OperationStatus.SUCCESS) {
      Set<String> partners = this.bindingSet.entryToObject(data);
      for (String prot2 : partners) {
        int depth = -1;
        if (prot2.equals(endProt)) {
          depth = path.size() - 1;
        } else if (path.size() < maxDepth && !path.contains(prot2)) {
          path.push(prot2);
          depth = recursive(txn, endProt, path, bestDepth, maxDepth);
          path.pop();
        }

        if (depth != -1 && (bestDepth == -1 || bestDepth > depth)) {
          bestDepth = depth;
        }
      }
    }
    return bestDepth;
  }
예제 #12
0
 public ListNode FindFirstCommonNode_01(ListNode pHead1, ListNode pHead2) {
   if (pHead1 == null || pHead2 == null) {
     return null;
   }
   Stack<ListNode> p1 = new Stack<ListNode>();
   Stack<ListNode> p2 = new Stack<ListNode>();
   ListNode h1 = pHead1;
   ListNode h2 = pHead2;
   while (h1 != null || h2 != null) { // 入栈操作O(n)
     if (h1 != null) {
       p1.push(h1);
       h1 = h1.next;
     }
     if (h2 != null) {
       p2.push(h2);
       h2 = h2.next;
     }
   }
   ListNode pre = null;
   while (p1.size() != 0 && p2.size() != 0) { // 寻找相同节点O(m)
     ListNode t1 = p1.pop();
     ListNode t2 = p2.pop();
     if (t1 == t2) {
       pre = t1;
     } else {
       break;
     }
   }
   return pre;
 }
예제 #13
0
  public static double postFixEvaluate(String input) {
    String input1 = infixToPostfix(input);
    System.out.println("Post fix expression: " + input1);

    Stack<Double> comp = new Stack<Double>(); // computation stack.
    Scanner scan = new Scanner(input1 + " $");
    while (true) {
      if (scan.hasNextDouble()) {
        comp.push(scan.nextDouble());
      } else if (scan.hasNext(opPattern)) {
        char op = scan.next().charAt(0);
        if (op == '$') {
          break;
        }
        if (comp.size() < 2) {
          throw new RuntimeException("invalid expression evaluation");
        }
        double b = comp.pop();
        double a = comp.pop();
        comp.push(eval(op, a, b));
      }
    }
    if (comp.size() == 1) return comp.pop();
    else throw new RuntimeException("invalid expression evaluation");
  }
예제 #14
0
  protected void handleTagEnd(
      List<BBCodeItem> bbCodeItems, Stack<String> tags, BBCodeToken bbCodeToken) {

    int size = 0;

    if (bbCodeToken != null) {
      String endTag = bbCodeToken.getEndTag();

      for (size = tags.size() - 1; size >= 0; size--) {
        if (endTag.equals(tags.elementAt(size))) {
          break;
        }
      }
    }

    if (size >= 0) {
      for (int i = tags.size() - 1; i >= size; i--) {
        BBCodeItem bbCodeItem = new BBCodeItem(TYPE_TAG_END, null, tags.elementAt(i));

        bbCodeItems.add(bbCodeItem);
      }

      tags.setSize(size);
    }
  }
예제 #15
0
  public static boolean match(String filename, String wildcardMatcher) {
    if (filename == null && wildcardMatcher == null) {
      return true;
    }
    if (filename == null || wildcardMatcher == null) {
      return false;
    }
    filename = convertCase(filename.replace('\\', '/'));
    wildcardMatcher = convertCase(wildcardMatcher.replace('\\', '/'));
    String[] wcs = splitOnTokens(wildcardMatcher);
    boolean anyChars = false;
    int textIdx = 0;
    int wcsIdx = 0;
    Stack<int[]> backtrack = new Stack<int[]>();

    do {
      if (backtrack.size() > 0) {
        int[] array = backtrack.pop();
        wcsIdx = array[0];
        textIdx = array[1];
        anyChars = true;
      }

      while (wcsIdx < wcs.length) {

        if (wcs[wcsIdx].equals("?")) {
          textIdx++;
          anyChars = false;
        } else if (wcs[wcsIdx].equals("*")) {
          anyChars = true;
          if (wcsIdx == wcs.length - 1) {
            textIdx = filename.length();
          }
        } else {
          if (anyChars) {
            textIdx = filename.indexOf(wcs[wcsIdx], textIdx);
            if (textIdx == -1) {
              break;
            }
            int repeat = filename.indexOf(wcs[wcsIdx], textIdx + 1);
            if (repeat >= 0) {
              backtrack.push(new int[] {wcsIdx, repeat});
            }
          } else {
            if (!filename.startsWith(wcs[wcsIdx], textIdx)) {
              break;
            }
          }
          textIdx += wcs[wcsIdx].length();
          anyChars = false;
        }
        wcsIdx++;
      }
      if (wcsIdx == wcs.length && textIdx == filename.length()) {
        return true;
      }
    } while (backtrack.size() > 0);

    return false;
  }
예제 #16
0
    @Override
    public Object process(
        Node nd, Stack<Node> stack, NodeProcessorCtx procCtx, Object... nodeOutputs)
        throws SemanticException {

      JoinTypeCheckCtx ctx = (JoinTypeCheckCtx) procCtx;
      if (ctx.getError() != null) {
        return null;
      }

      ASTNode expr = (ASTNode) nd;
      ASTNode parent = stack.size() > 1 ? (ASTNode) stack.get(stack.size() - 2) : null;

      if (expr.getType() != HiveParser.TOK_TABLE_OR_COL) {
        ctx.setError(ErrorMsg.INVALID_COLUMN.getMsg(expr), expr);
        return null;
      }

      assert (expr.getChildCount() == 1);
      String tableOrCol = BaseSemanticAnalyzer.unescapeIdentifier(expr.getChild(0).getText());

      boolean qualifiedAccess = (parent != null && parent.getType() == HiveParser.DOT);

      ColumnInfo colInfo = null;
      if (!qualifiedAccess) {
        colInfo = getColInfo(ctx, null, tableOrCol, expr);
        // It's a column.
        return new ExprNodeColumnDesc(colInfo);
      } else if (hasTableAlias(ctx, tableOrCol, expr)) {
        return null;
      } else {
        // Qualified column access for which table was not found
        throw new SemanticException(ErrorMsg.INVALID_TABLE_ALIAS.getMsg(expr));
      }
    }
예제 #17
0
 public List<Interval> merge(List<Interval> intervals) {
   if (intervals == null) return null;
   Collections.sort(intervals, new IntervalComparator());
   Stack<Interval> stack = new Stack<Interval>();
   for (Interval i : intervals) {
     if (stack.isEmpty()) {
       stack.push(i);
     } else {
       Interval t = stack.peek();
       if (hasOverlap(t, i)) {
         Interval newInterval = new Interval(t.start, Math.max(t.end, i.end));
         stack.pop();
         stack.push(newInterval);
       } else {
         stack.push(i);
       }
     }
   }
   int length = stack.size() - 1;
   Interval[] intervalArray = new Interval[stack.size()];
   for (int i = length; i >= 0; i--) {
     intervalArray[i] = stack.pop();
   }
   return Arrays.asList(intervalArray);
 }
예제 #18
0
  /**
   * Build an array of the folios that constitute this Manuscript
   *
   * @return array of folios in correct order
   * @throws SQLException
   */
  public Folio[] getFolios() throws SQLException {
    Connection j = null;
    PreparedStatement stmt = null;
    try {

      j = DatabaseWrapper.getConnection();

      String qry = "select * from folios where msID=? order by sequence,pageNumber ";
      if (this.getArchive().compareTo("Stanford") == 0)
        qry = "select * from folios where msID=? order by sequence";
      stmt = j.prepareStatement(qry);

      stmt.setInt(1, id);

      ResultSet rs = stmt.executeQuery();
      Stack<String> pageNames = new Stack();
      Stack<Integer> pageNumbers = new Stack();

      while (rs.next()) {
        // toret+="<option
        // value=\""+rs.getInt("pageNumber")+"\">"+textdisplay.archive.getShelfMark(rs.getString("archive"))+" "+rs.getString("collection")+" "+rs.getString("pageName")+"</option>";
        // pageNames.add(rs.getString("pageName"));
        pageNames.add(
            Folio.zeroPadLastNumberFourPlaces(rs.getString("pageName").replace("-000", "")));
        pageNumbers.add(rs.getInt("pageNumber"));
      }
      int[] pageNumbersArray = new int[pageNumbers.size()];
      String[] paddedPageNameArray = new String[pageNames.size()];

      for (int i = 0; i < paddedPageNameArray.length; i++) {
        paddedPageNameArray[i] = pageNames.elementAt(i);
        pageNumbersArray[i] = pageNumbers.get(i);
      }
      if (this.getArchive().compareTo("Stanford") != 0) {
        // sort the pages according to the zero padded names of the pages
        for (int i = 0; i < paddedPageNameArray.length; i++) {
          for (int k = 0; k < paddedPageNameArray.length - 1; k++) {
            if (paddedPageNameArray[k].compareTo(paddedPageNameArray[k + 1]) > 0) {
              String tmpStr = paddedPageNameArray[k];
              paddedPageNameArray[k] = paddedPageNameArray[k + 1];
              paddedPageNameArray[k + 1] = tmpStr;
              int tmpInt = pageNumbersArray[k];
              pageNumbersArray[k] = pageNumbersArray[k + 1];
              pageNumbersArray[k + 1] = tmpInt;
            }
          }
        }
      }
      Folio[] toret = new Folio[pageNumbersArray.length];
      for (int i = 0; i < toret.length; i++) {
        toret[i] = new Folio(pageNumbersArray[i]);
      }

      return toret;
    } finally {
      DatabaseWrapper.closeDBConnection(j);
      DatabaseWrapper.closePreparedStatement(stmt);
    }
  }
예제 #19
0
 public int pop() {
   if (stack1.size() == 1 && stack2.size() == 0) {
     return stack1.pop();
   } else if (stack2.size() == 0) {
     popToOtherStack(stack1, stack2);
   }
   return stack2.pop();
 }
  /**
   * This method attempts to solve the RPN equation given as a string
   *
   * @param calculation - String containing the RPN formatted string.
   * @return An Integer object containing the result, or null if something is wrong.
   */
  public Integer doCalculation(String calculation) {
    String[] calculationSplit = calculation.split(" ");

    for (String str : calculationSplit) {
      log.debug(str);

      if (str.matches("\\d.*")) {
        // Number, push it onto the stack.
        numbersStack.push(new Integer(str));
      } else if (str.length() == 1) {
        if (numbersStack.size() >= 2) {
          Integer n3 = null;
          Integer n2 = numbersStack.pop();
          Integer n1 = numbersStack.pop();

          switch (str.charAt(0)) {
            case '-':
              n3 = n1 - n2;
              break;
            case '+':
              n3 = n1 + n2;
              break;
            case '*':
              n3 = n1 * n2;
              break;
            case '/':
              if (n2 == 0) return null;
              n3 = n1 / n2;
              break;
              // For some reason we got an operator that there is no logic for
            default:
              return null;
          }

          if (n3 != null) {
            numbersStack.push(n3);
          }
        } else { // There aren't enough numbers to operate on, this means the RPN equation is
                 // illegal/incorrect
          return null;
        }
      } else {
        return null;
      }
    }

    // Check to see how many numbers are left in the stack...
    if (numbersStack.size() > 1) {
      return null;
    } else {
      int returnResult = numbersStack.pop();

      log.info("Returning result: " + returnResult);
      return new Integer(returnResult);
    }
  }
예제 #21
0
 public void restoreVertex() {
   if (this.vertexStore == null || this.vertexStore.size() == 0)
     throw new RuntimeException("Nothing to restore");
   int prevVertex = this.vertexStore.pop();
   if (prevVertex > edgeStack.size())
     throw new RuntimeException("Cannot restore vertex from backtrack");
   while (prevVertex < edgeStack.size()) {
     popVertex();
   }
 }
예제 #22
0
파일: GMLHandler.java 프로젝트: ebocher/jts
 /**
  * Gets the geometry parsed by this handler. This method should only be called AFTER the parser
  * has completed execution
  *
  * @return the parsed Geometry, or a GeometryCollection if more than one geometry was parsed
  * @throws IllegalStateException if called before the parse is complete
  */
 public Geometry getGeometry() {
   if (stack.size() == 1) {
     Handler h = (Handler) stack.peek();
     if (h.children.size() == 1) return (Geometry) h.children.get(0);
     return gf.createGeometryCollection(
         (Geometry[]) h.children.toArray(new Geometry[stack.size()]));
   }
   throw new IllegalStateException(
       "Parse did not complete as expected, there are " + stack.size() + " elements on the Stack");
 }
 public void addBufferLine() {
   checkState(itemStack.size() > 0);
   if (itemStack.size() > 1) {
     StackItem child = itemStack.pop();
     StackItem parent = itemStack.pop();
     buffer.append(StringUtils.join(parent.getId(), " -> ", child.getId(), ";\n"));
     itemStack.push(parent);
     itemStack.push(child);
   }
 }
예제 #24
0
 public void saveState(Bundle outState) {
   outState.putInt("cmdStack.size", mCommandStack.size());
   for (int i = 0; i < mCommandStack.size(); i++) {
     AbstractCommand command = mCommandStack.get(i);
     Bundle commandState = new Bundle();
     commandState.putString("commandClass", command.getCommandClass());
     command.saveState(commandState);
     outState.putBundle("cmdStack." + i, commandState);
   }
 }
예제 #25
0
 public int[][] getArrayOfStates() { // gets array of states in sequence to reach the final state
   int temp;
   int[][] statesSequence = new int[stack.size()][numberOfStates];
   for (int i = stack.size() - 1; i >= 0; i--) {
     temp = (int) stack.pop();
     for (int j = 0; j < numberOfStates; j++) {
       statesSequence[i][j] = states.get(temp)[j];
     }
   }
   return statesSequence;
 }
예제 #26
0
  /**
   * Create new instance from top two elements of stack.
   *
   * @param stack stack
   * @return new instance
   */
  public static Rule getRule(final Stack<Object> stack) {
    if (stack.size() < 2) {
      throw new IllegalArgumentException(
          "Invalid EQUALS rule - expected two parameters but received " + stack.size());
    }

    String p2 = stack.pop().toString();
    String p1 = stack.pop().toString();

    return getRule(p1, p2);
  }
예제 #27
0
 /**
  * Compare the content of the current path and the specified path to decide weather they are equal
  * or not.
  *
  * @param p A path to compare to the curent one.
  * @return True if both paths are equal.
  */
 public boolean equals(Path p) {
   if (nodePath.size() != p.nodePath.size()) {
     return false;
   } else {
     for (int i = 0; i < nodePath.size(); i++) {
       if (nodePath.get(i) != p.nodePath.get(i)) {
         return false;
       }
     }
   }
   return true;
 }
예제 #28
0
 public void doWait() {
   if (pStack.size() == 0) return;
   Debug.println("trace", "Waiting for process " + pStack.size());
   try {
     pStack.peek().waitFor();
     // wait for process to complete (does not work as expected for Windows programs)
     Debug.println("trace", "Process " + pStack.size() + " is done");
   } catch (Exception ex) {
     JOptionPane.showMessageDialog(this, "Error" + ex, "Error", JOptionPane.ERROR_MESSAGE);
   }
   pStack.pop();
 }
예제 #29
0
  // update doc tree according to open stack emlement
  void updateDoc() {
    Node root = (Node) doc;
    Stack<Node> shadow = new Stack<Node>();

    // get html Element
    Node rightMost = null;
    for (int i = 0; i < root.childNodesAsArray().length; i++) {
      if (root.childNode(i).nodeName().endsWith("html")) {
        rightMost = root.childNode(i);
        break;
      }
    }

    shadow.push(rightMost);
    // get body Element, considering body1
    while (rightMost.childNodesAsArray().length > 0) {
      rightMost = rightMost.childNodesAsArray()[rightMost.childNodesAsArray().length - 1];
      shadow.push(rightMost);
    }
    shadow.push(rightMost);

    // pop out the elements those are supposed to be complete
    while (shadow.size() > stack.size()) shadow.pop();

    while (shadow.size() > 0) {
      Node current = shadow.pop();
      // System.out.println("stack.peekLast().nodeName(): "+stack.peekLast().nodeName());
      // System.out.println("current.nodeName()         : "+current.nodeName());
      if (stack.peekLast().nodeName().equals("body")
          || stack.peekLast().nodeName().equals("head")
          || current.nodeName().equals("body")
          || current.nodeName().equals("head")) break;

      if (current.nodeName().equals(stack.peekLast().nodeName())) {
        stack.pollLast();
        ((Element) current).onlyStartTag = true;
      } else {
        System.out.println(
            Thread.currentThread().getName() + " err: stack doesn't match with shadow stack");
      }
    }

    // FileWriter file = null;
    // try {
    // file = new FileWriter(Thread.currentThread().getName()+"doc.html");
    // } catch (IOException e) {
    // e.printStackTrace();
    // }
    // PrintWriter out = new PrintWriter(file);
    // out.println(doc);
    // out.close();
  }
예제 #30
0
  private void generateMoveForPosition(int color, int position) {

    Stack<Integer> flipStack = new Stack<Integer>(); // list of all flips found for position
    int pointer; // pointer to position that is currently being evaluated

    // loop through each possible line radiating from position
    for (int i = 0; i < ADJACENT_ADDERS.length; i++) {
      Stack<Integer> lineStack = new Stack<Integer>(); // list of flips found on individual radial
      pointer = position + ADJACENT_ADDERS[i];
      boolean foundSameColor = false;

      // loop through each position in the line
      // end loop if same color, edge, or empty space found
      boolean loop = true;
      while (loop) {
        int stateAtPointer = this.positions[pointer];
        switch (stateAtPointer) {
          case 0:
            loop = false;
            break; // found empty
          case -2:
            loop = false;
            break; // found edge
          default:
            int colorEvaluate = color * stateAtPointer;
            switch (colorEvaluate) {
              case 1: // found same color
                foundSameColor = true;
                loop = false;
                break;
              case -1: // found opposite color
                lineStack.push(pointer);
                pointer += ADJACENT_ADDERS[i];
                break;
            }
            break;
        }
      }
      if (foundSameColor && lineStack.size() > 0) {
        flipStack.addAll(
            lineStack); // join lineStack with flipStack if flips found along current radial
      }
    }
    // push the move on to legalMovesList if valid flips found.  otherwise do nothing.
    switch (flipStack.size()) {
      case 0:
        break; // do nothing
      default:
        this.legalMovesList.push(new Move(position, flipStack));
        break;
    }
  }