Esempio n. 1
0
  protected void split() {
    int halfGuides = guides.size() / 2;
    int halfKids = halfGuides + 1;
    GuideNode<K, V> left =
        new GuideNode<K, V>(comparator, guides.subList(0, halfGuides), kids.subList(0, halfKids));
    GuideNode<K, V> right =
        new GuideNode<K, V>(
            comparator,
            guides.subList(halfGuides + 1, guides.size()),
            kids.subList(halfKids, kids.size()));
    left.setLeft(getLeft());
    left.setRight(right);
    getLeft().setRight(left);
    left.setParent(getParent());
    for (Node<K, V> kid : left.kids) {
      kid.setParent(left);
    }

    right.setLeft(left);
    right.setRight(getRight());
    getRight().setLeft(right);
    right.setParent(getParent());
    for (Node<K, V> kid : right.kids) {
      kid.setParent(right);
    }

    parent.insertKid(this, guides.get(halfGuides), left, right);
  }
Esempio n. 2
0
  public void right_rotate(Node curr) {
    if (curr != null) {
      if (curr.getLeftChild() == null) {
        System.out.println("Cannot rotate right since left child is not present");
        return;
      }

      Node rotateWith = curr.getLeftChild();
      rotateWith.setParent(curr.getParent());

      if (curr.getParent() != null) {
        Node currParent = curr.getParent();
        if (curr == currParent.getLeftChild()) currParent.setLeftChild(rotateWith);
        else currParent.setRightChild(rotateWith);
      } else {
        root = rotateWith;
      }

      curr.setLeftChild(rotateWith.getRightChild());

      if (rotateWith.getRightChild() != null) rotateWith.getRightChild().setParent(curr);

      rotateWith.setRightChild(curr);
      curr.setParent(rotateWith);
    }
  }
Esempio n. 3
0
 @Override
 protected void setupAST() {
   left.setParent(this);
   right.setParent(this);
   left.setStatement(getStatement());
   right.setStatement(getStatement());
   left.setupAST();
   right.setupAST();
 }
  public InternalNode(int d, Node p0, int k1, Node p1, Node n, Node p) {

    super(d, n, p);
    ptrs[0] = p0;
    keys[1] = k1;
    ptrs[1] = p1;
    lastindex = 1;

    if (p0 != null) p0.setParent(new Reference(this, 0, false));
    if (p1 != null) p1.setParent(new Reference(this, 1, false));
  }
Esempio n. 5
0
 @Override
 protected void removeParent() {
   final Node parent = getParent();
   if (parent instanceof Level) ((Level) parent).removeComment(this);
   else ((ContentSpec) parent).removeComment(this);
   super.setParent(null);
 }
  public void insert(int val, Node ptr) {
    // find correct position to insert
    int p = this.findKeyIndex(val);

    // if node is not full
    if (!full()) {
      // if val is larger than last key, increment p
      if (val > this.getKey(this.getLast())) {
        p++;
      }
      // insertion for simple case
      this.insertSimple(val, ptr, p);
    } else {
      // create a neighbor node with val and ptr
      Node split = new InternalNode(degree, null, val, ptr, this.getNext(), this);
      // set split to be next node of current node
      this.setNext(split);
      // get val to be inserted into parent
      int parentVal = this.redistribute();

      // if current node has a parent, insert value into parent
      if (this.getParent() != null) {
        this.getParent().getNode().insert(parentVal, split);
        // if no parent for current node, create a new root
      } else {
        Node newRoot = new InternalNode(degree, this, parentVal, split, null, null);
        // set parent references
        this.setParent(new Reference(newRoot, 0, false));
        split.setParent(new Reference(newRoot, 1, false));
      }
    }
  }
  // Another BFS path-finding implementation
  // This one doesn't rely on getting all reachable nodes through BFS
  // Instead, it stops once it finds the node during BFS.
  // Also, the queue keeps track of paths instead of individual nodes
  public static List<Node> BFS2(Node root, Node find) {
    Node.resetTree(root);

    LinkedList<ArrayList<Node>> queue = new LinkedList<ArrayList<Node>>();
    root.setDistance(0);

    ArrayList<Node> path = new ArrayList<Node>();
    path.add(root);

    queue.add(path);

    while (queue.size() > 0) {
      ArrayList<Node> curPath = queue.remove();
      Node endNode = curPath.get(curPath.size() - 1);
      if (endNode == find) {
        return curPath;
      } else {
        List<Node> endNodeChildren = endNode.getChildren();
        for (Node node : endNodeChildren) {
          if (node.getDistance() == Double.POSITIVE_INFINITY) {
            node.setDistance(endNode.getDistance() + 1);
            node.setParent(endNode);
            ArrayList<Node> newPath = new ArrayList<Node>(curPath);
            newPath.add(node);
            queue.add(newPath);
          }
        }
      }
    }

    return Collections.emptyList();
  }
  // Breadth first search
  // Returns a list of all reachable nodes in the order visited
  public static List<Node> BFS(Node root) {
    Node.resetTree(root);
    List<Node> reachable = new ArrayList<Node>();
    LinkedList<Node> queue = new LinkedList<Node>();

    root.setDistance(0);
    queue.add(root);

    reachable.add(root);

    while (queue.size() > 0) {
      Node cur = queue.remove();
      List<Node> children = cur.getChildren();
      for (Node node : children) {
        if (node.getDistance() == Double.POSITIVE_INFINITY) {
          node.setDistance(cur.getDistance() + 1);
          node.setParent(cur);
          queue.add(node);
          reachable.add(node);
        }
      }
    }

    return reachable;
  }
Esempio n. 9
0
  public static void main(String args[]) {

    String str =
        "bbb0www"; // "087465132";		054832761			// Initial Board State as a String with 0 as the
                   // Blank Space

    Node top = new Node();
    Node node = new Node();
    System.out.println("Start state: " + str);
    /*for(int i=0;i<str.length();i++){
    	if(i%3==0){
    		System.out.println("");
    	}
    	System.out.print(str.charAt(i)+"\t");
    }*/
    SlidingTileDFS e = new SlidingTileDFS();
    node.setState(str);
    node.setParent(null);

    e.add(node, 0);

    // e.s.push(str);
    while (!(e.s.empty())) {
      top = e.s.pop();
      // node.setState(top);
      // node.setParent(null);
      e.left(top); // Move the blank space up and add new state to queue
      e.leftjump1(top);
      e.leftjump2(top);
      e.right(top); // Move the blank space down
      e.rightjump1(top); // Move left
      e.rightjump2(top); // Move right and remove the current node from Queue
    }
    System.out.println("Solution doesn't exist");
  }
Esempio n. 10
0
  void left(Node node) {
    String str = node.getState();
    String parent = node.getParent();
    Node newState = new Node();
    int a = str.indexOf("0");
    char temp;
    char[] s = str.toCharArray();
    String newStr;

    if (a != 0) {
      temp = s[a - 1];
      s[a - 1] = '0';
      s[a] = temp;
      newStr = this.gString(s);
      newState.setState(newStr);
      newState.setParent(str);
      // newState.setLevel(node.getLevel()+1);
      // newState.setHeuristic(newState.calculateHeuristic(goal));
      // newState.setFvalue(newState.getHeuristic() + newState.getLevel());
      add(newState, map.get(str) + 1);
      // add(s,map.get(str)+1);
      if (newStr.equals("www0bbb")) {
        System.out.println(
            "Solution found after searching through " + map.get(newStr) + " states of the tree");
        printSolution();
        System.exit(0);
      }
    }
  }
Esempio n. 11
0
  /** Removes all child nodes from this element. */
  public void removeChildren() {
    for (int i = 0; i < getChildCount(); ++i) {
      Node child = getChild(i);
      child.setParent(null);
    }

    clearChildren();
  }
Esempio n. 12
0
 /**
  * Adds the node to this parent. Children must be stored in the order in which they were added.
  * Otherwise various operators will perform incorrectly (such as - % / and others).
  *
  * @param node child node.
  */
 public void addChild(Node node) {
   ParentNode parent = node.getParent();
   if (parent != null) {
     parent.children.remove(node);
   }
   children.add(node);
   node.setParent(this);
 } // addChild
Esempio n. 13
0
 // encapsulated/private working method
 private void insert(Node newNode, Node currRoot) {
   if (newNode.getKey() <= currRoot.getKey()) {
     if (currRoot.getLeftChild() != null) {
       insert(newNode, currRoot.getLeftChild());
     } else {
       currRoot.setLeftChild(newNode);
       newNode.setParent(currRoot);
     }
   } else {
     if (currRoot.getRightChild() != null) {
       insert(newNode, currRoot.getRightChild());
     } else {
       currRoot.setRightChild(newNode);
       newNode.setParent(currRoot);
     }
   }
 }
Esempio n. 14
0
 public void transplant(Node curr, Node replace) {
   if (curr.getParent() == null) root = replace;
   else if (curr == curr.getParent().getLeftChild()) {
     curr.getParent().setLeftChild(replace);
   } else {
     curr.getParent().setRightChild(replace);
   }
   if (replace != null) replace.setParent(curr.getParent());
 }
 @Override
 public Node copyTree() {
   BodyNode newThis = new BodyNode();
   for (Node child : this) {
     Node newChild = child.copyTree();
     newChild.setParent(newThis);
     newThis.addChild(newChild);
   }
   return newThis;
 }
Esempio n. 16
0
  /**
   * Replace two nodes
   *
   * @param x node
   * @param n node
   * @throws HsqlException
   */
  private void replace(Session session, Node x, Node n) throws HsqlException {

    if (x.equals(getRoot(session))) {
      setRoot(session, n);

      if (n != null) {
        n.setParent(null);
      }
    } else {
      set(x.getParent(), x.isFromLeft(), n);
    }
  }
Esempio n. 17
0
  /**
   * Set a node as child of another
   *
   * @param x parent node
   * @param isleft boolean
   * @param n child node
   * @throws HsqlException
   */
  private void set(Node x, boolean isleft, Node n) throws HsqlException {

    if (isleft) {
      x.setLeft(n);
    } else {
      x.setRight(n);
    }

    if (n != null) {
      n.setParent(x);
    }
  }
Esempio n. 18
0
 public void optimizeRoot() {
   List<Node> list = getChildren();
   if (list.size() == 1) {
     Node node = list.get(0);
     List<Node> children = node.getChildren();
     this.children.remove(0);
     for (Node child : children) {
       this.children.add(child);
       child.setParent(null);
     }
   }
 }
Esempio n. 19
0
 public Node(
     String name, Vector3f pos, Vector3f scale, Quat4f rot, List<Node<?>> nodes, K kind) {
   this.name = name;
   this.pos = pos;
   this.scale = scale;
   this.rot = rot;
   this.nodes = buildNodeMap(nodes);
   this.kind = kind;
   kind.setParent(this);
   for (Node<?> child : this.nodes.values()) {
     child.setParent(this);
   }
 }
Esempio n. 20
0
 private static void buildSubtreeFromNewick(Node parent, String subTreeStr) {
   ArrayList<String> kids = getChildStrings(0, subTreeStr);
   for (String kidStr : kids) {
     stripSpaces(kidStr);
     Node kid = new Node();
     if (hasKids(kidStr)) buildSubtreeFromNewick(kid, kidStr);
     else {
       kid.setId(kidStr.substring(0, kidStr.indexOf(":")));
     }
     parent.addChild(kid);
     kid.setDistToParent(subTreeDistFromParent(kidStr));
     kid.setParent(parent);
     //				System.out.println("dist from parent is : " + kid.getDistToParent());
     //				System.out.println("dist to root is : " + getDistToRoot(kid));
   }
 }
Esempio n. 21
0
  /**
   * (Deep) Clone Method, Returns An Object Equal To This One
   *
   * @return a clone of this object
   */
  @Override
  public Object clone() {

    Node<T> nodeTMP = new Node<T>((T) this.value, this.fixedValue);

    nodeTMP.setColor(this.getColor());

    nodeTMP.setDiscoveryTIME(this.getDiscoveryTIME());

    nodeTMP.setDistance(this.getDistance());

    nodeTMP.setFinalTIME(this.getFinalTIME());

    nodeTMP.setParent(this.parent);

    return nodeTMP;
  }
Esempio n. 22
0
  /**
   * Expands the node's state therefore generating a list of successor nodes. Expansion takes place
   * by invoking the problem's operators apply() method on the node's state.
   *
   * @param node node whose state is to be expanded.
   * @param problem problem to solve
   * @param generatedStates List<State> the nodes that are in the frontier of the search algorithm.
   * @param expandedStates List<State> the states that have been expended so far along the search
   *     process.
   * @return List<Node> containing the successor nodes.
   */
  public List<Node> expand(
      Node node, Problem problem, List<State> generatedStates, List<State> expandedStates) {
    List<Node> successorNodes = new ArrayList<Node>();
    Node successorNode = null;
    State currentState = null;
    State successorState = null;

    // If neither node or problem are null
    if (node != null && problem != null) {
      // Get the node's state.
      currentState = node.getState();
      // Remove current state from the list of generated states.
      generatedStates.remove(currentState);
      // Insert current state to the list of generated states.
      expandedStates.add(currentState);
      // If the state is not null
      if (currentState != null) {
        // Go over the list of problem operators
        for (Operator operator : problem.getOperators()) {
          // Apply the operator to the current state
          successorState = operator.apply(currentState);
          // If the operator has been successfully applied and the resulting successor
          // state hadn't been previously generated nor expanded
          if (successorState != null
              && !generatedStates.contains(successorState)
              && !expandedStates.contains(successorState)) {
            // make a new node to contain the new successor state
            successorNode = new Node(successorState);
            successorNode.setOperator(operator.getName());
            successorNode.setParent(node);
            successorNode.setDepth(node.getDepth() + 1);
            // add the newly created node to the list of successor nodes.
            successorNodes.add(successorNode);
            // Insert current successor State to the list of generated states
            generatedStates.add(successorState);
          }
        }
      }
    }

    return successorNodes;
  }
Esempio n. 23
0
  // 处理只有一个儿子的文件夹
  private void move1ChildFolder(Node node) {
    if ("folder".equals(node.getType())) {
      if (node.getSize() == 1) {
        Node child = node.getChildren().get(0);

        Node parent = node.getParent();
        if (parent != null) {
          // 将单个儿子节点往上移动
          parent.getChildren().add(child);
          child.setParent(parent);

          // 并从当前节点中移除
          node.getChildren().remove(0);
          parent.getChildren().remove(node);

          // 继续网上移动单个儿子节点
          move1ChildFolder(child);
        }
      }
    }
  }
Esempio n. 24
0
  // returns the root
  public static Node buildTreeFromNewick(String treeStr) {
    Node root = new Node("root");
    treeStr =
        treeStr.replaceAll("\\[&[^\\]]+\\]", ""); // Used to strip off beast-style annotations,

    int first = treeStr.indexOf("(");
    int last = treeStr.lastIndexOf(");");

    treeStr = treeStr.substring(first, last + 1);
    treeStr = stripSpaces(treeStr);

    buildSubtreeFromNewick(root, treeStr);

    // Sometimes we'll get an extra node at the root, so strip it off
    // Will we ever want to preserve these?
    while (root.numChildren() == 1) {
      root = root.getChild(0);
      root.setDistToParent(0);
      root.setParent(null);
    }
    return root;
  }
Esempio n. 25
0
  private Node makeCrunchNode(Node topologicalNode) {
    // copy the intrinsic properties: id, weights, relationship, and selectors will be set
    Node node = new Node(topologicalNode);
    // assign the id from the name hash
    node.setId(computeId(node));
    if (!topologicalNode.isLeaf()) {
      List<Node> newChildren = new ArrayList<Node>();
      List<Node> children = topologicalNode.getChildren();
      for (Node child : children) {
        // depth-first traversal
        Node newChild = makeCrunchNode(child);
        // set the child-parent relationship
        newChildren.add(newChild);
        newChild.setParent(node);
      }
      node.setChildren(newChildren);

      // weights and selector should be set after all lower nodes are crunched
      computeWeightAndSelector(node);
    }
    return node;
  }
  public void addResult(Cursor cursor, Set<EventBean> lookupResults, int resultStream) {
    if (lookupResults.isEmpty()) {
      throw new IllegalArgumentException("Attempting to add zero results");
    }

    Node parentNode = cursor.getNode();
    if (parentNode == null) {
      Node leafNode = new Node(resultStream);
      leafNode.setEvents(lookupResults);

      if (nodesPerStream == null) {
        nodesPerStream = new List[numStreams];
      }

      List<Node> nodes = nodesPerStream[resultStream];
      if (nodes == null) {
        nodes = new LinkedList<Node>();
        nodesPerStream[resultStream] = nodes;
      }
      leafNode.setParentEvent(rootEvent);

      nodes.add(leafNode);
      return;
    }

    Node leafNode = new Node(resultStream);
    leafNode.setEvents(lookupResults);
    leafNode.setParent(cursor.getNode());
    leafNode.setParentEvent(cursor.getTheEvent());

    List<Node> nodes = nodesPerStream[resultStream];
    if (nodes == null) {
      nodes = new LinkedList<Node>();
      nodesPerStream[resultStream] = nodes;
    }

    nodes.add(leafNode);
  }
Esempio n. 27
0
  /**
   * parse sentence and generate .trees file
   *
   * @param en
   * @param align
   * @param out
   */
  public static void parse(String en, String align, String out, boolean verbose) {

    // use alignments?
    boolean use_alignments = true;
    if (align.startsWith("no_align")) {
      use_alignments = false;
      System.err.println("Not using alignments.");
    } else {
      System.err.println("Using alignments from " + align);
    }

    // setup stanfordparser
    String grammar = "edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz";
    String[] options = {"-outputFormat", "wordsAndTags, typedDependencies"};
    LexicalizedParser lp = LexicalizedParser.loadModel(grammar, options);
    TreebankLanguagePack tlp = lp.getOp().langpack();
    java.util.function.Predicate<java.lang.String> punctuationFilter = x -> true;

    GrammaticalStructureFactory gsf =
        new edu.stanford.nlp.trees.EnglishGrammaticalStructureFactory(punctuationFilter);

    // read document
    Iterable<List<? extends HasWord>> sentences;
    Reader r = new Reader(en);
    String line = null;
    List<List<? extends HasWord>> tmp = new ArrayList<List<? extends HasWord>>();
    while ((line = r.getNext()) != null) {
      Tokenizer<? extends HasWord> token =
          tlp.getTokenizerFactory().getTokenizer(new StringReader(line));
      List<? extends HasWord> sentence = token.tokenize();
      tmp.add(sentence);
    }
    sentences = tmp;

    // set up alignment file reader
    Reader alignment = new Reader();
    if (use_alignments) {
      alignment = new Reader(align);
    }

    // set up tree file writer
    Writer treeWriter = new Writer(out);

    // parse
    long start = System.currentTimeMillis();
    // System.err.print("Parsing sentences ");
    int sentID = 0;
    for (List<? extends HasWord> sentence : sentences) {
      Tree t = new Tree();
      // t.setSentID(++sentID);
      System.err.println("parse Sentence :" + sentence + "...");
      // System.err.print(".");
      System.err.println("-----------------------------------------------------------------------");
      edu.stanford.nlp.trees.Tree parse = lp.parse(sentence);
      // parse.pennPrint();

      // List for root node and lexical nodes
      List<Node> loneNodes = new LinkedList<Node>();
      List<Node> governingNodes = new LinkedList<Node>();

      // ROOT node
      Node root = new Node(true, true);
      root.setTag("ROOT");
      t.setRoot(root);
      loneNodes.add(root);
      governingNodes.add(root);

      // tagging

      int counter = 0;
      String surface = "";
      String tag = "";

      for (TaggedWord tw : parse.taggedYield()) {
        Node n = new Node();
        Node governingNode = new Node();
        n.setNodeID(++counter);
        surface = tw.value();
        tag = tw.tag();
        if (surface.startsWith("-LRB-")) {
          surface = "(";
        } else if (surface.startsWith("-RRB-")) {
          surface = ")";
          // } else if (surface.startsWith("-LSB-")){
          //    surface = "[";
          // } else if (surface.startsWith("-RSB-")){
          //    surface = "]";
          // } else if (surface.startsWith("-LCB-")){
          //    surface = "{";
          // } else if (surface.startsWith("-RCB-")){
          //    surface = "}";
        } else if (surface.startsWith("''")) {
          surface = "\"";
        }
        tag = tag.replaceAll("#", "-NUM-");
        surface = surface.replaceAll("&", "-AMP-");
        surface = surface.replaceAll("#", "-NUM-");
        surface = surface.replaceAll(">", "-GRE-");
        surface = surface.replaceAll("=", "-EQU-");
        n.setInitialLexicalIndex(counter);
        governingNode.setInitialLexicalIndex(counter);
        n.setSurface(surface);
        // System.out.print("("+tw.value()+" : ");
        n.setTag(tag);
        governingNode.setTag("_" + tag);
        governingNode.setLabel("_gov");
        // System.out.print(tw.tag()+")");
        loneNodes.add(n);
        governingNodes.add(governingNode);
        governingNode.setChild(n);
      }

      // System.out.println("");

      // t.setSentLength(t.getNodes().size() - 1);
      // List<Node> loneNodes = new LinkedList<Node>();
      Node[] nodes = new Node[2000];
      // labeling
      int depIndex;
      int govIndex;
      String[] depInfo;
      String[] govInfo;
      GrammaticalStructure gs = gsf.newGrammaticalStructure(parse);
      List<TypedDependency> tdl = gs.typedDependencies(false);
      // List<TypedDependency> tdl = gs.typedDependenciesCCprocessed();
      for (TypedDependency td : tdl) {
        depIndex = td.dep().index();
        govIndex = td.gov().index();
        // System.out.println("Index1:"+depIndex);
        // System.out.println("Index2:"+govIndex);
        // if (nodes[depIndex] == null){
        //	System.out.println("Making node!");
        //	nodes[depIndex] = new Node();
        // }
        // if (nodes[govIndex] == null){
        //	System.out.println("Making node!");
        //	nodes[govIndex] = new Node();
        // }
        Node dep = loneNodes.get((depIndex));
        Node gov = governingNodes.get((govIndex));
        Node depcopy = governingNodes.get((depIndex));
        Node govcopy = loneNodes.get((govIndex));
        dep.setLabel(td.reln().toString());
        depcopy.setLabel(td.reln().toString());
        govcopy.setLabel("head");
        // System.out.println(td.toString());
        govInfo = td.gov().toString().split("/");
        depInfo = td.dep().toString().split("/");
        // System.out.println(td.gov().toString());
        // System.out.println(td.dep().toString());
        // dep.setSurface(depInfo[0]);
        // dep.setTag(depInfo[1]);
        gov.setChild(governingNodes.get(depIndex));
        governingNodes.get(depIndex).setParent(gov);
        // gov.setChild(dep);
        dep.setParent(governingNodes.get(depIndex));
      }
      // t.setRoot(nodes[0]);

      // Collapse tree to remove unneeded governing nodes:

      Node gov;
      Node dep;
      Node parent;
      List<Node> children;

      for (int i = 1; i < governingNodes.size(); i++) { // start with index 1 to skip root
        gov = governingNodes.get(i);
        dep = loneNodes.get(i);
        if (gov.getChildren().size() <= 1) {
          int k = 0;
          parent = gov.getParent();
          children = parent.getChildren();

          for (Node n : children) {
            if (n == gov) {
              gov.getParent().replaceChild(k, dep);
              dep.setParent(gov.getParent());
            }
            k++;
          }
        }
      }
      // Mark head nodes with appropriate label:
      int k = 0;
      for (Node n : loneNodes) {
        if (k != 0) {
          if (n.getLabel() == n.getParent().getLabel()) {
            n.setLabel("head");
          }
        } else {
          n.setLabel("null");
        }
        k++;
      }
      // Sort lexical children of each governing node in lexical order

      for (Node n : governingNodes) {
        n.sortChildrenByInitialIndex();
      }

      // combine with alignment
      if (use_alignments) {
        t.initialize(alignment.readNextAlign());
      } else {
        t.initializeUnaligned();
      }

      // write tree to file
      treeWriter.write(t);

      // print tree to console

      System.out.println(t.toSentence());
      if (verbose) {
        System.err.println(t.toString());
        // t.recursivePrint();
      }
      System.err.println("#######################################################################");
    }
    long stop = System.currentTimeMillis();
    System.err.println("...done! [" + (stop - start) / 1000 + " sec].");

    treeWriter.close();
  }
Esempio n. 28
0
 public void setRoot(Node root) {
   this.root = root;
   root.setParent(null);
 }
Esempio n. 29
0
 /** Test parent/child relationships */
 public void testChildNodes() {
   Node net = Node.ROOT_NODE.newInstance(testLibrary, "net");
   Node rect = Node.ROOT_NODE.newInstance(testLibrary, "rect");
   rect.setParent(net);
   assertTrue(net.contains("rect"));
 }
  public int findBestMove(Node currentNode, int best) {
    int turn = currentNode.getBoard().CurrentPlayer();

    // set the current value of the current node to compare with children node
    if (turn != player) currentNode.setValue(Float.POSITIVE_INFINITY);
    else currentNode.setValue(Float.NEGATIVE_INFINITY);

    // Check each pit on your side to find the best move. */
    for (int i = 0; i < 6; i++)
      if (currentNode.getBoard().validMove(i)) {
        try {
          MancalaGameState newBoard = currentNode.getBoard().copy();
          try {
            newBoard.play(i);
          } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }

          Node newNode = new Node(newBoard, currentNode.getDepth() + 1);

          newNode.setParent(currentNode);
          currentNode.setChild(newNode, i);

          // CUT OFF
          if (newNode.getBoard().checkEndGame() || (newNode.getDepth() >= cutoffDepth)) {

            RegressionState aState = new RegressionState(newNode.getBoard(), player);
            newNode.setValue(predictedValue(aState, weight));

          } else findBestMove(newNode, best);

          // alpha-beta pruning
          // AI = MAX
          // pick the child with larger value
          if (currentNode.getBoard().CurrentPlayer() == player) {
            if (currentNode.getChild(i) != null) {
              if (currentNode.getChild(i).getValue() > currentNode.getValue()) {
                currentNode.setValue(currentNode.getChild(i).getValue());
                best = i;
              }
            }
            currentNode.deleteChild(i);

            // alpha cut off if our value is greater than ANY
            // player/MIN parent value

            Node nodePtr = currentNode;
            while (nodePtr.getParent() != null) {
              nodePtr = nodePtr.getParent();
              if ((nodePtr.getBoard().CurrentPlayer != player)
                  && (currentNode.getValue() > nodePtr.getValue())) {
                nodePtr = null;
                return best;
              }
            }

            nodePtr = null;
          }

          // Player = MIN
          // pick the child with smaller value
          if (currentNode.getBoard().CurrentPlayer() != player) {
            if (currentNode.getChild(i) != null) {
              if (currentNode.getChild(i).getValue() < currentNode.getValue()) {
                currentNode.setValue(currentNode.getChild(i).getValue());
                best = i;
              }
            }
            currentNode.deleteChild(i);

            // beta cut off if our value is less than ANY
            // computer/MAX parent value
            Node nodePtr = currentNode;
            while (nodePtr.getParent() != null) {
              nodePtr = nodePtr.getParent();
              if ((nodePtr.getBoard().CurrentPlayer() == player)
                  && (currentNode.getValue() < nodePtr.getValue())) {
                nodePtr = null;
                return best;
              }
            }
            nodePtr = null;
          }
        } catch (java.lang.OutOfMemoryError e) {
          System.out.println("OUT OF MEM");
          return -1;
        }
      }
    return best; // return the best move
  }