Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package heuristicSearch;
- import java.util.ArrayList;
- import java.util.Collection;
- public class FractionPuzzleNode extends Node{
- private String numerators;
- private String denominator;
- double value;
- FractionPuzzleNode parent;
- private FractionPuzzleNode goal;
- ArrayList<String> stringList = new ArrayList <String>();
- /*
- * Constructor. Init the numerator, denominator and the goal.
- */
- public FractionPuzzleNode (String numerator, String denominator, FractionPuzzleNode goal){
- super();
- this.denominator = denominator;
- this.numerators = numerator;
- this.goal = goal;
- calculateValue();
- }
- /*
- * Calculating the real value of the node
- */
- public void calculateValue(){
- double num = Integer.parseInt(numerators);
- double den = Integer.parseInt(denominator);
- value = num/den;
- }
- public double getValue(){
- return this.value;
- }
- @Override
- public int hashCode() {
- // TODO Auto-generated method stub
- return 0;
- }
- @Override
- public boolean equals(Object o) {
- if (((FractionPuzzleNode) o).getValue() == this.value) {
- return true;
- }else {
- return false;
- }
- }
- /*
- * Returning the cost so far, based on how many parent node this node has.
- */
- @Override
- public int getCostSoFar() {
- if (!this.lineage().isEmpty()){
- return this.lineage().size()-1;
- }
- else
- return 0;
- }
- /*
- * Constructing all permutations of a string, and adds it to the stringlist.
- */
- public void showPattern(String st, String chars) {
- if (chars.length() <= 1) {
- this.stringList.add(st + chars);
- }else{
- for (int i = 0; i < chars.length(); i++) {
- try {
- String newString = chars.substring(0, i) + chars.substring(i + 1);
- showPattern(st + chars.charAt(i), newString);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- }
- private FractionPuzzleNode createNewFractionPuzzleNode(String string){
- FractionPuzzleNode node = new FractionPuzzleNode(string.substring(0, 4),string.substring(4, 9), this.goal);
- node.parent = this;
- return node;
- }
- @Override
- public Collection<FractionPuzzleNode> children() {
- Collection<FractionPuzzleNode> childrenList = new ArrayList<FractionPuzzleNode>();
- showPattern("",(numerators+denominator));
- for (int i = 0; i < stringList.size(); i++) {
- childrenList.add(createNewFractionPuzzleNode(stringList.get(i)));
- }
- return childrenList;
- }
- @Override
- protected int heuristic() {
- return (int) ((this.goal.getValue() - this.value));
- }
- @Override
- protected Node getParent() {
- return parent;
- }
- public String toString(){
- String s = "";
- s += this.value;
- return s;
- }
- }
Add Comment
Please, Sign In to add comment