I would need some help with the following code if you are kind.
Basically i have a tree node that remembers it's parent node, depth-level and his current state(a 2D array).
Most variable names are written in my native language, i hope this is not a problem :
public class Nod implements Cloneable {
private Nod parinte;//parent node
private int[][] stare;//state
private int cost;//depth-level
private String actiune;//the action used to obtain this node
private volatile int hashCode = 0;
public boolean equals(Object obj)
{
if(this == obj)
{
return true;
}
if (!(obj instanceof Nod))
{
return false;
}
Nod nod = (Nod)obj;
return cost == nod.getCost() && actiune.equals(nod.getActiune())
&& stare.equals(nod.getStareNod());
}
public int hashCode()
{
StringBuffer strBuff = new StringBuffer();
try
{
int n = Problema.Dimensiune();//returns the dimension of state matrix
for (int i=0;i<n;i++)
for (int j=0;j<n;j++)
strBuff.append(stare[i][j]);
strBuff.append(cost);
strBuff.append(actiune);
String str = strBuff.toString();
hashCode = str.hashCode();
}
catch (IOException e) {
e.printStackTrace();
}
return hashCode;
}
public Object clone() throws CloneNotSupportedException
{
return super.clone();
}
public static boolean goUp(int[][] st) throws IOException
{
int n = Problema.Dimensiune();
boolean ok = false;
int[][] a = st;
for (int i=0;i<n;i++)
for (int j=0;j<n;j++)
{
if (a[i][j] == 0)
if (i != 0)
ok = true;
}
return ok;
}
public static boolean goDown(int[][] st) throws IOException
{
int n = Problema.Dimensiune();
boolean ok = false;
int[][] a = st;
for (int i=0;i<n;i++)
for (int j=0;j<n;j++)
{
if (a[i][j] == 0)
if (i != (n-1))
ok = true;
}
return ok;
}
public static boolean goLeft(int[][] st) throws IOException
{
int n = Problema.Dimensiune();
boolean ok = false;
int[][] a = st;
for (int i=0;i<n;i++)
for (int j=0;j<n;j++)
{
if (a[i][j] == 0)
if (j != 0)
ok = true;
}
return ok;
}
public static boolean goRight(int[][] st) throws IOException
{
int n = Problema.Dimensiune();
boolean ok = false;
int[][] a = st;
for (int i=0;i<n;i++)
for (int j=0;j<n;j++)
{
if (a[i][j] == 0)
if (j != (n-1))
ok = true;
}
return ok;
}
public static int[] Zero(int[][] st) throws IOException
{
int[][] a = st;
int n = Problema.Dimensiune();
int[] b = new int[2];
for (int i=0;i<n;i++)
for (int j=0;j<n;j++)
if (a[i][j] == 0)
{
b[0] = i;
b[1] = j;
}
return b;
}
public static int[][] Actiune(int[][] st, String s) throws IOException
{
int[][] a = st;
int[] b = Zero(st);
if ((goRight(st) == true) && (s == "right"))
{
a[b[0]][b[1]] = a[b[0]][b[1]+1];
a[b[0]][b[1]+1] = 0;
}
if ((goLeft(st) == true) && (s == "left"))
{
a[b[0]][b[1]] = a[b[0]][b[1]-1];
a[b[0]][b[1]-1] = 0;
}
if ((goUp(st) == true) && (s == "up"))
{
a[b[0]][b[1]] = a[b[0]-1][b[1]];
a[b[0]-1][b[1]] = 0;
}
if ((goDown(st) == true) && (s == "down"))
{
a[b[0]][b[1]] = a[b[0]+1][b[1]];
a[b[0]+1][b[1]] = 0;
}
return a;
}
public Nod(){}
public Nod (int[][] st)
{
parinte = null;
stare = st;
cost = 0;
actiune = null;
}
public Nod (Nod nod)
{
parinte = nod.parinte;
stare = nod.stare;
cost = nod.cost;
actiune = nod.actiune;
}
public Nod(Nod nodp, String ac) throws IOException
{
this.parinte = nodp;
this.cost = parinte.getCost()+1;
this.actiune = ac;
this.stare = Actiune(parinte.getStareNod(),actiune);
}
public void setCost(int cost)
{
this.cost = cost;
}
public int getCost(){
return this.cost;
}
public void setStareNod(int[][] stare)
{
this.stare = stare;
}
public int[][] getStareNod(){
return this.stare;
}
public void setNodParinte(Nod parinte)
{
this.parinte = parinte;
}
public Nod getNodParinte() throws IOException{
return this.parinte;
}
public void setActiune(String actiune)
{
this.actiune = actiune;
}
public String getActiune()
{
return this.actiune;
}
}
Now, i create an initial node and after, a child-node from it. The problem is that when i create the child-node, the parent's 2D array becomes identical with the child's array. I tried to clone the node object but it didn't fix it. I would appreciate if someone has an ideea how to fix it and shares it.
public class test {
public static void main(String[] args) throws IOException, CloneNotSupportedException
{
int[][] p = Problema.stareInitiala();
Nod nod = new Nod(p);
Nod nodc = (Nod) nod.clone();
Nod nod1 = new Nod(nodc,"right");
Nod nod1c = (Nod) nod1.clone();
Nod nod2 = new Nod(nod1c,"up");
if (nod.getStareNod().equals(nod.getStareNod()))
System.out.print("ok");
else
System.out.print("not ok");
}
}
So if p = {{7,2,4},{5,0,6},{8,3,1}} the if statement should return "not ok", but instead i get the "ok" message.
There is nothing broken or wrong about the clone mechanism. Just a bunch or programmers who don't understand it, here's a valid one for you class.
public Object clone() {
try {
Nod clone = (Nod)super.clone();
clone.stare = (int[][])stare.clone();
return clone;
} catch (CloneNotSupportedException cnse) {
//won't happen;
throw new RuntimeError("Won't happen");
}
}
This implementation assumes that the clone wants to use the same parent as the original. If this is not the case, you will need to clone that as well, or perhaps set the parent to null.
You may want to look at the documentation of the clone() method of Object. Default clone implementation (that is if you implemented Cloneable, which you did) performs shallow copy. This is probably not what you want, you may be better off by writing your own copying method.
Related
Code: Search word in Trie
Implement the function SearchWord for the Trie class.
For a Trie, write the function for searching a word. Return true if the word is found successfully, otherwise return false.
Note: main function is given for your reference which we are using internally to test the code.
class TrieNode{
char data;
boolean isTerminating;
TrieNode children[];
int childCount;
public TrieNode(char data) {
this.data = data;
isTerminating = false;
children = new TrieNode[26];
childCount = 0;
}
}
public class Trie {
private TrieNode root;
public int count;
public Trie() {
root = new TrieNode('\0');
count = 0;
}
private boolean add(TrieNode root, String word){
if(word.length() == 0){
if (!root.isTerminating) {
root.isTerminating = true;
return true;
} else {
return false;
}
}
int childIndex = word.charAt(0) - 'a';
TrieNode child = root.children[childIndex];
if(child == null){
child = new TrieNode(word.charAt(0));
root.children[childIndex] = child;
root.childCount++;
}
return add(child, word.substring(1));
}
public void add(String word){
if (add(root, word)) {
this.count++;
}
}
public boolean search(String word){
// add your code here
return search(root,word);
}
private boolean search(TrieNode root, String word){
if(word.length()==0){
return true;
}
int childIndex = word.charAt(0) -'a';
TrieNode child = root.children[childIndex];
if(child==null){
return false;
}
return search(child, word.substring(1));
}
}
//Main Function
code
import java.io.*;
public class Runner {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws IOException{
Trie t = new Trie();
String[] string = br.readLine().split("\\s");
int choice = Integer.parseInt(string[0]);
String word = "Null";
if (string.length!=1)
{
word = string[1];
}
while(choice != -1) {
switch(choice) {
case 1 : // insert
t.add(word);
break;
case 2 : // search
System.out.println(t.search(word));
break;
default :
return;
}
string = br.readLine().split("\\s");
choice = Integer.parseInt(string[0]);
if (string.length!=1)
{
word = string[1];
}
}
}
}
You need to make use of the isTerminating information. In search, change:
if(word.length()==0){
return true;
}
To:
if(word.length()==0){
return root.isTerminating;
}
I'm trying to write a code that split a spaceless string into meaningful words but when I give sentence like "arealways" it returns ['a', 'real', 'ways'] and what I want is ['are', 'always'] and my dictionary contains all this words. How can I can write a code that keep backtracking till find the best matching?
the code that returns 'a', 'real', 'ways':
splitter.java:
public class splitter {
HashMap<String, String> map = new HashMap<>();
Trie dict;
public splitter(Trie t) {
dict = t;
}
public String split(String test) {
if (dict.contains(test)) {
return (test);
} else if (map.containsKey(test)) {
return (map.get(test));
} else {
for (int i = 0; i < test.length(); i++) {
String pre = test.substring(0, i);
if (dict.contains(pre)) {
String end = test.substring(i);
String fixedEnd = split(end);
if(fixedEnd != null){
map.put(test, pre + " " + fixedEnd);
return pre + " " + fixedEnd;
}else {
}
}
}
}
map.put(test,null);
return null;
}
}
Trie.java:
public class Trie {
public static class TrieNode {
private HashMap<Character, TrieNode> charMap = new HashMap<>();
public char c;
public boolean endOWord;
public void insert(String s){
}
public boolean contains(String s){
return true;
}
}
public TrieNode root;
public Trie() {
root = new TrieNode();
}
public void insert(String s){
TrieNode p = root;
for(char c : s.toCharArray()) {
if(! p.charMap.containsKey(c)) {
TrieNode node = new TrieNode();
node.c = c;
p.charMap.put(c, node);
}
p = p.charMap.get(c);
}
p.endOWord = true;
}
public boolean contains(String s){
TrieNode p = root;
for(char c : s.toCharArray()) {
if(!p.charMap.containsKey(c)) {
return false;
}
p = p.charMap.get(c);
}
return p.endOWord;
}
public void insertDictionary(String filename) throws FileNotFoundException{
File file = new File(filename);
Scanner sc = new Scanner(file);
while(sc.hasNextLine())
insert(sc.nextLine());
}
public void insertDictionary(File file) throws FileNotFoundException{
Scanner sc = new Scanner(file);
while(sc.hasNextLine())
insert(sc.nextLine());
}
}
WordSplitter class:
public class WordSplitter {
public static void main(String[] args) throws FileNotFoundException {
String test = "arealways";
String myFile = "/Users/abc/Desktop/dictionary.txt";
Trie dict = new Trie();
dict.insertDictionary(myFile);
splitter sp = new splitter(dict);
test = sp.split(test);
if(test != null)
System.out.println(test);
else
System.out.println("No Splitting Found.");
}
}
Using the OP's split method and the implementation of Trie found in The Trie Data Structure in Java Baeldung's article, I was able to get the following results:
realways=real ways
arealways=a real ways
However, if I remove the word "real" or "a" from the dictionary, I get the following results:
realways=null
arealways=are always
Here's the entire code I used to get these results:
public class Splitter {
private static Map<String, String> map = new HashMap<>();
private Trie dict;
public Splitter(Trie t) {
dict = t;
}
/**
* #param args
*/
public static void main(String[] args) {
List<String> words = List.of("a", "always", "are", "area", "r", "way", "ways"); // The order of these words does not seem to impact the final result
String test = "arealways";
Trie t = new Trie();
for (String word : words) {
t.insert(word);
}
System.out.println(t);
Splitter splitter = new Splitter(t);
splitter.split(test);
map.entrySet().forEach(System.out::println);
}
public String split(String test) {
if (dict.find(test)) {
return (test);
} else if (map.containsKey(test)) {
return (map.get(test));
} else {
for (int i = 0; i < test.length(); i++) {
String pre = test.substring(0, i);
if (dict.find(pre)) {
String end = test.substring(i);
String fixedEnd = split(end);
if (fixedEnd != null) {
map.put(test, pre + " " + fixedEnd);
return pre + " " + fixedEnd;
} else {
}
}
}
}
map.put(test, null);
return null;
}
public static class Trie {
private TrieNode root = new TrieNode();
public boolean find(String word) {
TrieNode current = root;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
TrieNode node = current.getChildren().get(ch);
if (node == null) {
return false;
}
current = node;
}
return current.isEndOfWord();
}
public void insert(String word) {
TrieNode current = root;
for (char l : word.toCharArray()) {
current = current.getChildren().computeIfAbsent(l, c -> new TrieNode());
}
current.setEndOfWord(true);
}
#Override
public String toString() {
return toString(root);
}
/**
* #param root2
* #return
*/
private String toString(TrieNode node) {
return node.toString();
}
public static class TrieNode {
private Map<Character, TrieNode> children = new HashMap<>() ;
private String contents;
private boolean endOfWord;
public Map<Character, TrieNode> getChildren() {
return children;
}
public void setEndOfWord(boolean endOfWord) {
this.endOfWord = endOfWord;
}
public boolean isEndOfWord() {
return endOfWord;
}
#Override
public String toString() {
StringBuilder sbuff = new StringBuilder();
if (isLeaf()) {
return sbuff.toString();
}
children.entrySet().forEach(entry -> {
sbuff.append(entry.getKey() + "\n");
});
sbuff.append(" ");
return children.toString();
}
private boolean isLeaf() {
return children.isEmpty();
}
}
public void delete(String word) {
delete(root, word, 0);
}
private boolean delete(TrieNode current, String word, int index) {
if (index == word.length()) {
if (!current.isEndOfWord()) {
return false;
}
current.setEndOfWord(false);
return current.getChildren().isEmpty();
}
char ch = word.charAt(index);
TrieNode node = current.getChildren().get(ch);
if (node == null) {
return false;
}
boolean shouldDeleteCurrentNode = delete(node, word, index + 1) && !node.isEndOfWord();
if (shouldDeleteCurrentNode) {
current.getChildren().remove(ch);
return current.getChildren().isEmpty();
}
return false;
}
}
}
I improved the original code by adding a toString() method to the Trie and TrieNode. Now, when I print out the Trie object "t", I get the following result:
{a={r={e={a=}}, l={w={a={y={s=}}}}}, w={a={y={s=}}}}
My conclusion is that the OP's TrieNode implementation is incorrect. The way the Trie is built, given the inputted string value, the behavior described by the OP seems to be correct.
I am working on a project with a datatructure that is deeper than 1 level and I try to box different user-defined datatypes to hold information of all levels.
First Level: A class that has only an ArrayList of level 2 datatype and some functions to access the data of all Levels.
Second Level: A class that has some standard variables and an ArrayList of Level 3 datatype and also some functions .
Third Level: A class / record of some standard variables
The instance of the first-level datatype should be used by more than one activity of my application (almost all).
Here is my problem: I can initialize the first-level and add some objects to the list, but I could not do so with the second level. If I add some object in the list of the second level all seems to be good, but when I access this data a NullPointerException occurs.
Here is my question: Is it possible to box datatypes in more than 1 level? And where I should search for the error.
For better understanding the sources:
modulData.java (First Level)
package de.myApp.dataholder;
import java.util.ArrayList;
import android.util.Log;
public class modulData {
// Constructor
private static final modulData mainModulDataHolder = new modulData();
public static modulData getInstance() {return mainModulDataHolder;}
// Data
private ArrayList<isModulData> mIsModulData;
// Functions
public void init() {
this.mIsModulData = new ArrayList<isModulData>();
}
public isModulData getModul(int mID) {
isModulData result = null;
int i;
for (i = 0; i < mIsModulData.size(); i++) {
if (mIsModulData.get(i).ID() == mID) {
result = mIsModulData.get(i);
break;
}
}
return result;
}
public isCatData getCategory(int mID, int cID) {
isCatData result = new isCatData();
isCatData buffer = new isCatData();
int i,j ;
for (i = 0; i < mIsModulData.size(); i++) {
if (mIsModulData.get(i).ID() == mID) {
for(j = 0; j < mIsModulData.get(i).CountCategorys(); j++) {
buffer = mIsModulData.get(i).getCategory(j);
if (buffer.ID() == cID) {
result = buffer;
break;
}
}
}
}
return result;
}
public int ModulCount() {
int result = 0;
if (mIsModulData != null) { result = mIsModulData.size(); }
return result;
}
public int CategoryCount(int mID) {
int result = -1;
int i;
for (i = 0; i < mIsModulData.size(); i++) {
if (mIsModulData.get(i).ID() == mID) {
result = mIsModulData.get(i).CountCategorys();
break;
}
}
return result;
}
public int addModulWithJSON(String jsonString) {
int result = -1;
isModulData newModul = new isModulData();
newModul.initCategorys();
if (mIsModulData == null) { this.init(); }
result = newModul.decodeFromJSON(jsonString);
mIsModulData.add(newModul);
return result;
}
public int addCategoryWithJSON(int mID, String jsonString) {
int result = -1;
int i;
for (i = 0; i < mIsModulData.size(); i++){
if (mIsModulData.get(i).ID() == mID) {
result = mIsModulData.get(i).addCategoryWithJSON(jsonString);
Log.i("AddCategoryWithJSON","Add Category "+ String.valueOf(result));
// Here is the Problem: Added but no access to Data. Null Object reference !!!!
Log.i("AddCategoryWithJSON", mIsModulData.get(mID).getCategory(result).Title());
break;
}
}
return result;
}
}
isModulData.java (second level)
package de.myApp.dataholder;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import android.util.Log;
public class isModulData {
// Constructor
private static final isModulData modulDataHolder = new isModulData();
public static isModulData getInstance() {return modulDataHolder;}
// Data
private ArrayList<isCatData> mIsCatData;
private int mID;
private String mTitle;
private boolean misActive;
private int mBackgroundID;
// Functions
public int ID() { return this.mID; }
public String Title() { return this.mTitle; }
public boolean ActiveState() { return this.misActive; }
public int BackgroundID() { return this.mBackgroundID; }
public int decodeFromJSON(String jsonString) {
int result;
try {
JSONArray jArray = new JSONArray(jsonString);
this.mID = Integer.parseInt(jArray.getString(0).toString());
this.mTitle = jArray.getString(1).toString();
this.misActive = Boolean.parseBoolean(jArray.getString(2).toString());
this.mBackgroundID = Integer.parseInt(jArray.getString(3).toString());
result = this.mID;
} catch (JSONException e) {
e.printStackTrace();
Log.w("JSONDecode CMD801","Decode raised in JSONException ["+e.toString()+"]");
result = -1;
}
return result;
}
public int addCategoryWithJSON(String jsonString) {
int result = -1;
if (this.mIsCatData == null) { this.initCategorys(); }
isCatData cNewCategory = new isCatData();
result = cNewCategory.decodeFromJSON(jsonString);
this.mIsCatData.add(cNewCategory);
return result;
}
public isCatData getCategory(int cID) {
isCatData result = new isCatData();
if (cID < mIsCatData.size() -1) {
result = mIsCatData.get(cID);
} else {
result = null;
}
return result;
}
public void initCategorys() {
this.mIsCatData = new ArrayList<isCatData>();
}
public int CountCategorys() {
return this.mIsCatData.size();
}
}
isCatData.java (third level)
package de.myApp.dataholder;
import org.json.JSONArray;
import org.json.JSONException;
import android.util.Log;
public class isCatData {
// Constructor
private static final isCatData catDataHolder = new isCatData();
public static isCatData getInstance() {return catDataHolder;}
// Data
private int cID;
private String cTitle;
private boolean cisActive;
private boolean cisWriteEnable;
private int cBackgroundID;
// Functions
public int ID() { return this.cID; }
public String Title() { return this.cTitle; }
public boolean ActiveState() { return this.cisActive; }
public boolean WriteEnableState() { return this.cisWriteEnable; }
public int BackgroundID() { return this.cBackgroundID; }
public int decodeFromJSON(String jsonString) {
int result;
try {
JSONArray jArray = new JSONArray(jsonString);
this.cID = Integer.parseInt(jArray.getString(0).toString());
this.cTitle = jArray.getString(1).toString();
this.cisActive = Boolean.parseBoolean(jArray.getString(2).toString());
this.cisWriteEnable = Boolean.parseBoolean(jArray.getString(3).toString());
this.cBackgroundID = Integer.parseInt(jArray.getString(4).toString());
result = this.cID;
} catch (JSONException e) {
e.printStackTrace();
Log.w("JSONDecode CMD801","Decode raised in JSONException ["+e.toString()+"]");
result = -1;
}
return result;
}
}
Am really new to Java, started to study it on my own.... I downloaded netbeans and Eclipse and the two gave me the same result.. they don't run the code (stuck on running) neither let me debug it - Eclipse debugger and Netbeans - was not responding :? I don't whats wrong.. and I got no clue as I can't debug..
Here's my code: am tryin to check for palindrome:
package ClassQueue;
class Stack {
private Object[] Stack_Array = null;
public int top = 0;
public Stack(int size) {
top = 0;
Stack_Array = new Object[size];
}
public Stack() {
this(100);
}
protected void finalizer() {
Stack_Array = null;
}
final public boolean empty() {
return top == 0;
}
final public boolean full() {
return top == Stack_Array.length;
}
public void push(Object token) {
if (!full()) {
Stack_Array[top] = token;
top++;
}
}
public Object pop() {
Object Value_return = -999;
if (!empty()) {
Value_return = Stack_Array[top];
top--;
}
return Value_return;
}
}//end of Class_Stack
class Queue {
private Object[] Queue_Array = null;
private int Front = 0;
private int Rear = 0;
public Queue(int size) {
Front = Rear = 0;
Queue_Array = new Object[size];
}
public Queue() {
this(100);
}
protected void finalizer() {
Front = Rear = 0;
Queue_Array = null;
}
final public boolean empty() {
return Front == Rear;
}
final public boolean full() {
return Rear == Queue_Array.length;
}
public void queueAdd(Object token) {
if (!full()) {
Queue_Array[Rear] = token;
Rear++;
}
}
public Object queueDelete() {
Object Value_return = -999;
if (!empty()) {
Value_return = Queue_Array[Front];
Front++;
return Value_return;
}
return Value_return;
}
}//end of Class_Queue
public class ClassQueue {
public static void main(String[] args) {
int i = 0;
String Value_1 = "ABBA";
Stack Value_1_Stack = new Stack(Value_1.length());
Queue Value_1_Queue = new Queue(Value_1.length());
while (i < Value_1.length()) {
Value_1_Stack.push(Value_1.charAt(i));
Value_1_Queue.queueAdd(Value_1.charAt(i));
}
i = 0;
while (Value_1_Stack.pop() == Value_1_Queue.queueDelete()) {
i++;
}
if (i == Value_1.length()) {
System.out.println("Palindrome");
} else {
System.out.println("NOT");
}
}//end of main
}//end of ClassQueue
You've got an infinite loop here as i is never incremented:
while (i < Value_1.length()) {
Value_1_Stack.push(Value_1.charAt(i));
Value_1_Queue.queueAdd(Value_1.charAt(i));
}
Also don't exceed the length of the String Value_1:
while (i < Value_1.length() - 1) {
Value_1_Stack.push(Value_1.charAt(i));
Value_1_Queue.queueAdd(Value_1.charAt(i));
i++;
}
Aside: Use Java naming conventions for variable names.
You cannot create class with the name of package name.
To run your program
change the package name.
For ClassQueue create another ClassQueue.java file in same package.
To Debug program: Run>Debug
This will give you environment for debugging
Change view: Window>Show View>Debug
I'm writing program with several different algorithms for solving n-puzzle problem. I have problem with DFS algorithm, as it only finds solution for simplest combinations of depth 1 to 4, then it shows stack overflow error. Also, for depth 4 it shows solution of length 2147, which is obviously wrong. I ran out of ideas what is the problem.
I use HashMap to keep explored nodes and to retrace path. Here is my code for DFS:
public class DFS extends Path{
Node initial;
Node goal;
String order;
boolean isRandom = false;
ArrayList<Node> Visited = new ArrayList<Node>();
boolean goalFound=false;
public DFS(Node initial, String order, byte [][] goal_state){
this.initial=initial;
goal=new Node(goal_state);
this.order=order;
if(order.equals("Random"))isRandom=true;
Visited.add(initial);
path.put(this.initial, "");
runDFS(initial);
}
public void runDFS(Node current){
if(current.equals(goal))
{
goalFound=true;
System.out.println("Goal");
retracePath(current,true);
return;
}
if(!current.equals(goal) && goalFound==false)
{
Node child;
Moves m = new Moves(current);
if(isRandom)order=randomOrder("LRUD");
for (int i=0; i<4; i++)
{
String s = order.substring(i,i+1);
if(m.CanMove(s)==true)
{
child=m.move();
if(Visited.contains(child))
{
continue;
}
else
{
path.put(child,s);
Visited.add(child);
runDFS(child);
}
}
}
}
}
}
Node:
public class Node {
public byte[][] status;
private int pathcost;
public int getPathcost() {
return pathcost;
}
public void setPathcost(int pathcost) {
this.pathcost = pathcost;
}
public Node(byte[][] status)
{
this.status=new byte[status.length][status[0].length];
for(int i=0;i<status.length;i++){
for(int j=0;j<status[0].length;j++){
this.status[i][j]=status[i][j];
} }
}
#Override
public boolean equals(Object other)
{
if (!(other instanceof Node))
{
return false;
}
return Arrays.deepEquals(status, ((Node)other).status);
}
#Override
public int hashCode()
{
return Arrays.deepHashCode(status);
}
}
and Path:
public class Path {
public HashMap<Node,String> path;
public Path(){
path=new HashMap<Node, String>(100);
}
public void retracePath(Node nstate, boolean print){
String dir=path.get(nstate);
String textPath="";
int i=0;
while(!dir.equals("")){
textPath+=dir + ", ";
boolean changed=false;
if(dir.equals("L")) {dir="R"; changed=true;}
if(dir.equals("R") && changed==false) {dir="L";}
if(dir.equals("U")) {dir="D"; changed=true;}
if(dir.equals("D") && changed==false) {dir="U";}
Moves m=new Moves(nstate);
m.CanMove(dir);
nstate=new Node(m.move().status);
dir=path.get(nstate);
i++;
}
if(print==true) {textPath=textPath.substring(0,(textPath.length()-2));
System.out.println(i);
System.out.print(new StringBuffer(textPath).reverse().toString());}
}
public Node getParent(Node n){
String dir=path.get(n);
boolean changed=false;
if(dir.equals("L")) {dir="R"; changed=true;}
if(dir.equals("R") && changed==false) {dir="L";}
if(dir.equals("U")) {dir="D"; changed=true;}
if(dir.equals("D") && changed==false) {dir="U";}
Moves m=new Moves(n);
m.CanMove(dir);
n=new Node(m.move().status);
return n;
}
public String randomOrder(String order) {
ArrayList<Character> neworder = new ArrayList<Character>();
for(char c : order.toCharArray()) {
neworder.add(c);
}
Collections.shuffle(neworder);
StringBuilder newstring = new StringBuilder();
for(char c : neworder) {
newstring.append(c);
}
return newstring.toString();
}
}
If you have any ideas what is the problem and where is mistake I would be very thankful!