solving a maze in java - java

i am trying to solve a maze using either BFS or DFS, the maze numbers are given in a text file so i have to read line by line then convert each string to integers and store each line in an array of size 2 then i store this array in an arraylist.
secondly in the findRow method i try to search each element in the array and print out the numbers related to it either left or right.
but my main goal is to use any search method print out the fastest way to the end of the maze. the text file is in this format 0 and 1 is the starting and ending node.
11 3
2 3
0 3
1 4
5 4
5 7
6 7
7 8
8 9
9 10
0 5
================
my code
public class Mazes {
ArrayList<int[]> collections = new ArrayList();
public String toString() {
String result = "";
for (int i = 0; i < collections.size(); i++) {
result += collections.get(i)[0];
result += " ";
result += collections.get(i)[1];
result += "\n";
}
return result;
}
public void getMazes() throws Exception{
try{
FileInputStream fstream = new FileInputStream("C:\\csd3939\\maze1.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while((strLine = br.readLine()) != null){
String[] splitStringArray = strLine.split(" ");
int[] intElementArray = new int[2];
for(int i=0; i<splitStringArray.length; i++){
intElementArray[i] = Integer.parseInt(splitStringArray[i]); }
collections.add(intElementArray);
}
System.out.print("\n");
in.close();
}catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
}
public ArrayList<Integer> findRowConnection(int rowID){
ArrayList<Integer> connectRow = new ArrayList();
for(int i=0; i<collections.size(); i++){
int[] searching = collections.get(i);
if(rowID == searching[0]){
connectRow.add(searching[1]);
}
if(rowID == searching[1]){
connectRow.add(searching[0]);
}
}
return connectRow;
}
}
===========
main method
===========
public class MazeMain {
public static void main(String[] args)throws Exception{
Mazes mainmaze = new Mazes();
mainmaze.getMazes();
System.out.println(mainmaze);
ArrayList<Integer> searchResult = mainmaze.findRowConnection(0);
System.out.println("Connected Rows are :");
for(int i=0; i<searchResult.size(); i++){
System.out.println(searchResult.get(i));
}
}
}

Related

Read the data from the file and store it in two arrays

hello I am having trouble with trying to read a file and take the two columns of the file and put them respectively in their own arrays. Any help would be appreciated! Thanks!
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
// TODO Auto-generated method stub
System.out.println("Please enter the name of the file to be read");
String fileName = keyboard.nextLine();
Scanner chirping = null;//user input for file name
boolean fileValue = false; //this makes the value false until the correct file name is inputed
while(!fileValue) {
try {
FileReader dates = new FileReader(fileName); // connects to the user inputted file
chirping = new Scanner(dates); //scans the file
fileValue = true; //turns file value to true which takes us out of the while loop
}//end try
catch(IOException e) {
System.out.println("File Not Found, Please Try Again: ");
fileName = keyboard.nextLine();
}//end catch
}// end while
double[] dataSet = new double[30];
double[] chirpFreq = new double[30];
double[] temp = new double[30];
//double[] temp = new double[chirping.nextInt()];
for(int i = 0; chirping.hasNextDouble(); i++) {
dataSet[i] = chirping.nextDouble();
}
for(int j = 0; j <= dataSet.length; j++) {
if(j%2 == 0) {
chirpFreq[j] = dataSet[j];
}
else {
temp[j] = dataSet[j];
}
}
for(int i = 0; i <= chirpFreq.length; i++) {
System.out.print(chirpFreq[i]+ " ");
}
chirping.close();
}
//These are the values i am trying to sort into two separate arrays
20 88.6
16 71.6
19.8 93.3
18.4 84.3
17.1 80.6
15.5 75.2
14.7 69.7
17.1 82
15.4 69.4
16.2 83.3
15 79.6
17.2 82.6
16 80.6
17 83.5
14.4 76.3
I don't usually use nextDouble() to read files so i don't know what your problem is exactly, but you can refactor your code to this:
double[] firstColumn = new double[30];
double[] secondColumn = new double[30];
String line = "";
int i = 0;
// keep reading until there is nothing to read
while( (line = chirping.nextLine()) != null ) {
// this is a regex that splits the line into an array based on whitespace
// just use " " if your data is separated by space or "\t" if tab
String[] columns = line.split("\\s+");
firstColumn[i] = Double.parseDouble(columns[0]);
secondColumn[i++] = Double.parseDouble(columns[1]);
}
chirping.close();

Reading two matrices from the same file in java

Hello guys and thank you in advance for your help!
I am trying to do a matrice calculator in java
that reads two matrices from the same file like this:
2 2
34 78
89 -12
#
2 2
67 76
123 5
first line is the rank
second and third line are the first matrix
the "#" splits the first and the second matrix
and that's the code I came up with and I didn't
find anything similar to this problem... can someone help me please?
String [] line = new String[30];
int counter = 2;
int rank[] = new int[2];
int matrixa[][] = new int [3][3];
try {
BufferedReader MyReader = new BufferedReader(new FileReader("matrix.txt"));
while(line != null) {
line = MyReader.readLine().split(" ");
}
rank[0] = Integer.parseInt(line[0]);
rank[1] = Integer.parseInt(line[1]);
for(int i = 0; i <rank[0];i++) {
for (int j=0;j<rank[1];j++) {
matrixa[i][j] = Integer.parseInt(line[counter]);
counter++;
System.out.print(matrixa[i][j] + " ");
}
System.out.println();
} }catch (Exception e) {}
Leaving a ticker variable at when your lines is equal to "#"
int ticker;
for(int i = 0; i < lines.length; i++){
if(lines[i].equals("#")) ticker = i;
}
This ticker then can be used to break the array. This could also be used earlier to break up the array into 2 separate arrays if that is expected.
String currentLine;
String[] line = new String[15];
String[] line2 = new String[15];
int i = 0;
while(line != null && !currentLine.equals("#")){
line = MyReader.readLine().split("");
currentLine = line[i];
if(currentLine.equals("#")) line[i] = null;
i++;
}
while(line2 != null)){
line2 = MyReader.readLine().split("");
}
They can be parsed into matrices and then math can be done on them from there.
Best of luck with your endeavors.

Java read file and write into array

--------------- SOLVED !!! -----------------------
I would like to thank you, everyone, for your help !
I have to read a file where I have nxm elements, and then put those elements into 2D array, and then print it out. I'm a little bit stuck at printing my array out. In file.txt I have 2x2 => 2 lines and 2 columns, and elements are:1 2 3 4.
Here is my code:
public class ex_1
{
public static void main(String args[])
{
FileReader fr = new FileReader("FirstMatrix.txt");
BufferedReader br = new BufferedReader(fr);
String s = br.readLine();
String[] split = s.split("x");
int k=Integer.parseInt(split[0]);
int l=Integer.parseInt(split[1]);
System.out.println("Matrix dimensions: "+k+" lines, "+l+" columns si "+k*l+" elements");
System.out.print("Elements in matrix are: \n");
int[][] FirstMatrix = new int [k][l];
while ((s = br.readLine()) != null)
{
for(int i=0; i<FirstMatrix.length; i++)
for(int j=0; j<FirstMatrix[i].length;j++)
{
FirstMatrix[i][j] = Integer.parseInt(s);
System.out.println("FirstMatrix["+i+"]["+j+"]="+FirstMatrix[i][j]);
}
}
br.close();
My output, how it is:
FirstMatrix[0][0]=1
FirstMatrix[0][1]=1
FirstMatrix[1][0]=1
FirstMatrix[1][1]=1
FirstMatrix[0][0]=2
FirstMatrix[0][1]=2
FirstMatrix[1][0]=2
FirstMatrix[1][1]=2
FirstMatrix[0][0]=3
FirstMatrix[0][1]=3
FirstMatrix[1][0]=3
FirstMatrix[1][1]=3
FirstMatrix[0][0]=4
FirstMatrix[0][1]=4
FirstMatrix[1][0]=4
FirstMatrix[1][1]=4
How I want it to be:
FirstMatrix[0][0]=1
FirstMatrix[0][1]=2
FirstMatrix[1][0]=3
FirstMatrix[1][1]=4
Does anyone know how I can fix this print out please?
EDIT!!
If I change code like this
int[][] FirstMatrix = new int [k][l];
while ((s = br.readLine()) != null)
{
for(int i=0; i<k;i++)
for(int j=0; j<l; j++)
{
FirstMatrix[i][j] = Integer.parseInt(s);
}
}
br.close();
for(int i=0; i<FirstMatrix.length; i++)
for(int j=0; j<FirstMatrix[i].length;j++)
{
System.out.println("FirstMatrix["+i+"]["+j+"]="+FirstMatrix[i][j]);
}
I get this output:
FirstMatrix[0][0]=4
FirstMatrix[0][1]=4
FirstMatrix[1][0]=4
FirstMatrix[1][1]=4
You're doing n*n times the loop. Because everytime that you read the file are entering the loop. If you know that every line is a number, you could read only one time and print each row.
Try it and let me know what happen.
Best regards from Mexico
After this line System.out.print("Elements in matrix are: \n");
paste this code.
int[][] FirstMatrix = new int [l][k];
for(int j=0; j<l;j++)
{
for(int i=0; i<k; i++) {
s = br.readLine());
FirstMatrix[j][i] = Integer.parseInt(s);
System.out.println("FirstMatrix["+j+"]["+i+"]="+FirstMatrix[j][i]);
}
}
Don't use while loop.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ex_1 {
public static void main(String args[]) throws IOException {
FileReader fr = new FileReader("FirstMatrix.txt");
BufferedReader br = new BufferedReader(fr);
String s = br.readLine();
String[] split = s.split("x");
int k = Integer.parseInt(split[0]);
int l = Integer.parseInt(split[1]);
System.out.println("Matrix dimensions: " + k + " lines, " + l + " columns si " + k * l + " elements");
System.out.print("Elements in matrix are: \n");
int[][] FirstMatrix = new int[k][l];
for (int lineIndex = 0; lineIndex < k; lineIndex++) {
for (int columnIndex = 0; columnIndex < l; columnIndex++) {
s = br.readLine();
FirstMatrix[lineIndex][columnIndex] = Integer.valueOf(s);
}
}
for (int a = 0; a < k; a++) {
for (int b = 0; b < l; b++)
System.out.print(FirstMatrix[a][b] + " ");
System.out.println();
}
br.close();
}
}

How do I read each column of a txt file, and place them in separate arrays?

I'm doing a Programming Assignment and basically I need to read from a txt file and sort everything in there in different arrays allowing me to display everything in the cmd prompt neatly and be able to delete stuff.
h Vito 123
d Michael 234 Heart
s Vincent 345 Brain Y
n Sonny 456 6
a Luca 567 Business
r Tom 678 Talking Y
j Anthony 789 Maintenance N
d Nicos 891 Bone
n Vicky 911 7
First column needs to be the employeeRole (employee, doctor). The second column being the employeeName. Third column being the employeeNumber and some of them have have a fourth column (if it's a number it's number of patients. Y is for like sweeping, or answering calls)
So my thought process was put each column into it's own array and then writing it out that way. I was able to put each row into its own array with
public class ReadingFile {
// String test;
// char[] employeeRole = new char[9];
String[] employeeRole = new String[9];
String[] employeeName = new String[9], specialty;
String[] wholeLine = new String[9];
// String word;
int[] employeeNum = new int[9];
int r, n, l, num;
public void Reader()
{
Scanner inputStream = null;
Scanner inputStream2 = null;
Scanner inputStream4 = null;
try
{
BufferedReader inputStream3 =
new BufferedReader(new FileReader("data.txt"));
inputStream = new Scanner(new FileInputStream("data.txt"));
inputStream =
new Scanner(new FileInputStream("data.txt"));
inputStream2 =
new Scanner(new FileInputStream("data.txt"));
inputStream4 =
new Scanner(new FileInputStream("data.txt"));
System.out.println("Yeah");
}
catch(FileNotFoundException e){
System.out.println("File Not found");
System.exit(1);
}
for (l=0; l<9; l++)
{
wholeLine[l] = inputStream2.nextLine();
System.out.println(wholeLine[l]);
}
But I couldn't figure out what to do from there. Doing a split would then put an array into an array? Which means I would put each line into an array and then each word into an array?
So I tried something else, anything with the length not equal to 1 would be the employeeNum, but then they there were the N's and Y's and the number of pateints.
for(r=0; r<9; r++) //role
{
String next = inputStream4.next();
while( next.length() != 1)
{
next = inputStream4.next();
}
employeeRole[r] = next;
System.out.println(employeeRole[r]);
}
I also tried
for (r=0; r<9; r++)
{
employeeRole[r] = wholeLine[r].substring(wholeLine[r].indexOf(1));
//inputStream.nextLine();
System.out.println(employeeRole[r]);
}
I'm just not sure if I'm going the right way about it? If I'm making it more difficult than it really is? Or if there's an easier way to do this. But after everything is done, the output should be able to basically say
Doctors: 2
Name: Michael Employee Number: 234 Specialty: Heart
Name: Nicos Employee Number: 891 Specialty: Bone
Any help would be greatly appreciated, thanks!
You don't have to open 4 streams in order to read the file (I guess you wanted to open "one per column" but you shouldn't do it).
Second, you can split the string on spaces (" ") which will provide you the columns (for every line separately) exactly like you want.
Code example:
BufferedReader br = null;
String[] characters = new String[1024];//just an example - you have to initialize it to be big enough to hold all the lines!
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("data.txt"));
int i=0;
while ((sCurrentLine = br.readLine()) != null) {
String[] arr = sCurrentLine.split(" ");
//for the first line it'll print
System.out.println("arr[0] = " + arr[0]); // h
System.out.println("arr[1] = " + arr[1]); // Vito
System.out.println("arr[2] = " + arr[2]); // 123
if(arr.length == 4){
System.out.println("arr[3] = " + arr[3]);
}
//Now if you want to enter them into separate arrays
characters[i] = arr[0];
// and you can do the same with
// names[1] = arr[1]
//etc
i++;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}

BufferedReader seems to only read last line of file

I'm trying to write a method to take a multiline tab-delimited file and return the contents of that file as an arraylist of String arrays (each line is a String[], and each such String[] is an element of an arraylist). My problem is, I can't tell if the output is correct or not. I've printed each arraylist element and String[] element as they are saved to the arraylist, and those printings look correct. But after the arraylist is returned and I print the String[] in it, they appear to only have the contents of the very last line of the file. I'm suspecting it might be something about FileReader or BufferedReader that I don't know. Anyhoo, here's the code:
public class DataParsingTest {
static File AAPLDailyFile = new File("./textFilesForMethodTests/dataParsingPractice2.tsv");
public static void main(String[] args) throws FileNotFoundException, IOException {
ArrayList<String[]> stringArrayList = fileToStringArray(AAPLDailyFile);
System.out.println("stringArray.size() = " + stringArrayList.size());
System.out.println(stringArrayList.get(0)[0]);
for (int i = 0; i < stringArrayList.size(); i++) {
for (int j = 0; j < stringArrayList.get(i).length; j++) {
System.out.println("index of arraylist is " + i + " and element at index " + j + " of that array is " + stringArrayList.get(i)[j]);
}
}
}
public static ArrayList<String[]> fileToStringArray(File file) throws FileNotFoundException, IOException {
ArrayList<String[]> arrayListOfStringArrays = new ArrayList<String[]>();
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
int nextChar = 0;
int noOfTokens = 1; // because the first token doesn't have a tab or newline before it
int startIndex = 0, endIndex = 0, tokenIndex = 0;
String toRead = "";
toRead = bufferedReader.readLine();
for (int i = 0; i < toRead.length(); i++) {
if (toRead.charAt(i) == '\t') {
noOfTokens++;
}
}
System.out.println("noOfTokens = " + noOfTokens);
bufferedReader.close();
fileReader.close();
String[] productString = new String[noOfTokens];
startIndex = 0;
endIndex = 0;
tokenIndex = 0;
FileReader fileReader2 = new FileReader(file);
BufferedReader bufferedReader2 = new BufferedReader(fileReader2);
tokenIndex = 0;
int count = 1;
while ((toRead = bufferedReader2.readLine()) != null) {
System.out.println("toRead = " + toRead);
startIndex = -1; // [L - so that the first time an array element is assigned, it's upped to 0]
endIndex = 0;
tokenIndex = 0;
while (true) {
endIndex = toRead.indexOf("\t", startIndex + 1);
if (endIndex == -1) {
productString[tokenIndex] = toRead.substring(startIndex + 1);
System.out.println("tokenIndex = " + tokenIndex);
System.out.println("productString[" + tokenIndex + "] = " + productString[tokenIndex]);
tokenIndex++;
count++;
arrayListOfStringArrays.add(productString);
System.out.println("just added an array to the list. the first element is " + productString[0]);
break;
}
productString[tokenIndex] = toRead.substring(startIndex + 1, endIndex);
System.out.println("tokenIndex = " + tokenIndex);
System.out.println("productString[" + tokenIndex + "] = " + productString[tokenIndex]);
startIndex = endIndex;
tokenIndex++;
count++;
}
}
fileReader2.close();
bufferedReader2.close();
return arrayListOfStringArrays;
}
}
The input file is:
1 2
3 4
5 6
The output is:
noOfTokens = 2
toRead = 1 2
tokenIndex = 0
productString[0] = 1
tokenIndex = 1
productString[1] = 2
just added an array to the list. the first element is 1
toRead = 3 4
tokenIndex = 0
productString[0] = 3
tokenIndex = 1
productString[1] = 4
just added an array to the list. the first element is 3
toRead = 5 6
tokenIndex = 0
productString[0] = 5
tokenIndex = 1
productString[1] = 6
just added an array to the list. the first element is 5
stringArray.size() = 3
5 // from here on up, it looks like the method works correctly
index of arraylist is 0 and element at index 0 of that array is 5
index of arraylist is 0 and element at index 1 of that array is 6
index of arraylist is 1 and element at index 0 of that array is 5
index of arraylist is 1 and element at index 1 of that array is 6
index of arraylist is 2 and element at index 0 of that array is 5
index of arraylist is 2 and element at index 1 of that array is 6 //these 6 lines only reflect the last line of the input file.
Thanks a mil!
You're only creating a single string array, and reusing that for all lines. So your ArrayList just contains multiple references to the same object. You need to understand that when you call arrayListOfStringArrays.add(productString); that's not adding a copy of the array to the ArrayList - it's just adding a reference. (The value of productString is just a reference, not the array itself.)
Just move this:
String[] productString = new String[noOfTokens];
into the while loop, and all should be well. (In this respect, anyway. You should also be closing your file handles in finally blocks.)
That looks like too much code for me to process. Try this altered fileToStringArray method.
public static ArrayList<String[]> fileToStringArray(File file) throws FileNotFoundException, IOException {
ArrayList<String[]> returnVal = new ArrayList<String[]>();
// Scanner is a nifty utility for reading Files
Scanner fIn = new Scanner(file);
// keep reading while the Scanner has lines to process
while (fIn.hasNextLine()) {
// take the next line of the file, and split it up by each tab
// and add that String[] to the list
returnVal.add(fIn.nextLine().split("\t", -1));
}
return returnVal;
}

Categories