Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Pathfinding error help
Index -> Programming, Java -> Java Help
Goto page Previous  1, 2, 3, 4  Next
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
Panphobia




PostPosted: Tue Nov 20, 2012 7:05 pm   Post subject: Re: Pathfinding error help

Ok I think I did everything to your specifications, here is ALL the code
code:
package bfs;

import java.util.*;
import java.io.*;

public class BFS {

    static int rows, col;

    public static void main(String[] args) throws FileNotFoundException {
        Scanner s = new Scanner(new File("C:\\Users\\DANIEL\\Desktop\\Java\\BFS\\src\\bfs\\DATA4.txt"));
        while (s.hasNext()) {
            String[] yx = s.nextLine().split(" ");
            rows = Integer.parseInt(yx[0]);
            col = Integer.parseInt(yx[1]);
            char[][] maze = new char[col][rows];
            for (int y = 0; y < rows; y++) {
                String text = s.nextLine();
                for (int x = 0; x < col; x++) {
                    maze[x][y] = text.charAt(x);
                }
            }


            int x[], y[];
            x = new int[3];
            y = new int[3];
            for (int z = 0; z < rows; z++) {
                for (int a = 0; a < col; a++) {
                    if (maze[a][z] == 'A') {

                        x[0] = z;
                        y[0] = a;

                    }
                    if (maze[a][z] == 'B') {
                        x[1] = z;
                        y[1] = a;
                    }
                    if (maze[a][z] == 'C') {
                        x[2] = z;
                        y[2] = a;
                    }
                }
            }

            System.out.println(bfs(maze, y[0], x[0], '#', 'B') + bfs(maze, y[1], x[1], '#', 'C')
                    + bfs(maze, y[2], x[2], '#', 'A'));

        }
    }

    public static int bfs(char[][] maze, int yStart, int xStart, char wall, char goal) {
        Queue<int[]> queue = new LinkedList<int[]>();
        int[] start = {yStart, xStart, 0};
        queue.add(start);
        while (queue.peek() != null) {
            int[] array = queue.remove();
            int x = array[0];
            int y = array[1];
            if (x < 0 || x >= col || y < 0 || y >= rows) {
                continue;
            }
            if (maze[x][y] == wall) {
                continue;
            }
            if (maze[x][y] == goal) {
                return array[2] + 1;
            }
            int[][] newPoints = {{0, -1}, {0, 1}, {1, 0}, {-1, 0}};
            for (int i = 0; i < 4; i++) {
                int[] temp = {x + newPoints[i][0], y + newPoints[i][1], array[2] + 1};
                queue.add(temp);
            }
        }
        return 0;

    }
}
and the contents of the data file are right here
code:
1 5
#ABC#
1 5
B.AC#
5 5
A....
.###.
.B...
.###.
.C...
5 5
.B...
.....
..A..
.....
...C.
10 10
##########
##..#..###
#.#...#.##
#..#.#..##
##..A..###
#..#C#..##
#.#...#.##
##..#..###
##B#######
##########
Sponsor
Sponsor
Sponsor
sponsor
Panphobia




PostPosted: Tue Nov 20, 2012 7:10 pm   Post subject: RE:Pathfinding error help

wait nvm i got it all i had to do to fix it is System.out.println((bfs(maze, y[0], x[0], '#', 'B')-1)+(bfs(maze, y[1], x[1], '#', 'C')-1)+(bfs(maze, y[2], x[2], '#', 'A')-1)); silly meeee, thank you so much maj, and demon
Panphobia




PostPosted: Wed Nov 21, 2012 12:32 am   Post subject: Re: Pathfinding error help

Ok so I think this is going to be my last question on BFS, and then I will know how to implement correctly, this question in dwite http://dwite.org/questions/train_ride.html , i finished, and it works as long as you do not bring in the xxxxxx into it, when i do, the arraylist causes a null pointer exception (the dreaded), here is my code
code:
package bfsv2;

import java.util.*;
import java.io.*;

public class BFSV2 {

    static int rows, col;

    public static void main(String[] args) throws FileNotFoundException {
        Scanner s = new Scanner(new File("C:\\Users\\DANIEL\\Desktop\\Java\\BFSV2\\src\\bfsv2\\DATA4.txt"));
        while (s.hasNext()) {
            ArrayList<String> text = new ArrayList<String>(5);
            char[][] maze;
            int c = 0;
            rows = 0;
            col = 10;
            text.add(null);
            while (text.get(c).charAt(0) != 'x'||text.get(c)==null) {
                text.add(c, s.nextLine());
                c += 1;
            }
            rows = c;
            maze = new char[col][rows];
            for (int y = 0; y < rows; y++) {
                for (int x = 0; x < col; x++) {
                    maze[x][y] = text.get(y).charAt(x);
                }
            }
            int x = 0;
            int y = 0;
            for (int z = 0; z < rows; z++) {
                for (int a = 0; a < col; a++) {
                    if (maze[a][z] == 'S') {
                        x = z;
                        y = a;
                    }
                }
            }
            System.out.println((bfs(maze, y, x, ' ', 'E') - 1));
        }
    }
    public static int bfs(char[][] maze, int yStart, int xStart, char wall, char goal) {
        Queue<int[]> queue = new LinkedList<int[]>();
        int[] start = {yStart, xStart, 0};
        queue.add(start);
        while (queue.peek() != null) {
            int[] array = queue.remove();
            int x = array[0];
            int y = array[1];
            if (x < 0 || x >= col || y < 0 || y >= rows) {
                continue;
            }
            if (maze[x][y] == wall) {
                continue;
            }
            if (maze[x][y] == goal) {
                return array[2] + 1;
            }
            //int[][] newPoints = {{0, -1}, {0, 1}, {1, 0}, {-1, 0}};
            int[][] newPoints = {{-1, -1}, {-1, 1}, {1, -1}, {1, 1}, {0, -1}, {0, 1}, {1, 0}, {-1, 0}};
            for (int i = 0; i < 8; i++) {
                int[] temp = {x + newPoints[i][0], y + newPoints[i][1], array[2] + 1};
                queue.add(temp);
            }
        }
        return 0;

    }
}
DemonWasp




PostPosted: Wed Nov 21, 2012 1:03 am   Post subject: RE:Pathfinding error help

code:
text.add(null);


Explain to me exactly what that line is doing.
Panphobia




PostPosted: Wed Nov 21, 2012 1:14 am   Post subject: RE:Pathfinding error help

Well basically I am trying to figure out the number of rows and am using a counter to figure out that, then I store the rows in an array list,when I try to run the while loop that says while the Next line isn't x it says nullpointerexcePtion, before that it was indexoutofbounds, so the. I just added null to position 0 and then I got this
Panphobia




PostPosted: Wed Nov 21, 2012 1:16 am   Post subject: RE:Pathfinding error help

I needed the test.add null to add something to the first position to compare it to x
DemonWasp




PostPosted: Wed Nov 21, 2012 3:16 am   Post subject: Re: Pathfinding error help

Stop doing things at random: that only works if you have evolutionary timescales and a massively parallel set of processors (you don't: you have limited time and only one "processor", you).

Here's how you write code to solve a problem:
1. State clearly how you want to solve the problem. Be precise: say exactly what you mean. You aren't allowed to use words or phrases like "kinda", "look at", "sorta", etc.
2. Break down the process from step #1 into the smallest steps possible.
3. Turn each step into a few lines of code (most of them should be one line).

For example, suppose you are trying to solve the following problem: "Read a single maze problem from an input file, stopping when you hit a line that contains an 'x'."

Step 1: Read lines from the file one at a time. If that line contains an 'x', discard it and stop reading; otherwise, add it to the list. Once we have the complete list, transfer the contents into a 2D array.

Step 2: Open the file for reading. Create a list to store results. Read lines one at a time; if the line contains 'x' then stop reading, otherwise, add the line to the list. After reading, convert every line in the list to a row of the 2D array.

Step 3:
code:

// Open the file for reading.
Scanner in = new Scanner(new File("DATA4.txt"));   // Note: you can use relative paths.

// Create a list to store results
List<String> lines = new ArrayList<String>();  // Note: don't use a custom default size until you know what you're doing

while ( in.hasNext() ) {
    // Read lines one at a time;
    String line = in.nextLine();

    // if the line contains 'x' then stop reading
    if ( line.contains ( 'x' ) ) {
        break;
    }

    // otherwise, add the line to the list
    lines.add ( line );
}

// Convert to 2D array
int rows = lines.size();    // Helpfully, List keeps track of how many entries it has.
// Your code actually does this correctly.


Eventually this process will become natural: you won't have to think about each step, you'll just understand how the code should look.
Panphobia




PostPosted: Wed Nov 21, 2012 8:46 am   Post subject: RE:Pathfinding error help

The way you implied is that it adds a line to the List until the end, not until the first set of xx's, what I was getting at was, to add the lines to the arraylist until you get to a line containing x, and THEN making the 2D array and solve the answer, the way you did it was, while there is a nextline in the file you will keep adding a line to the list, see what i am trying to get at is I cannot then differentiate between which maze is which if they are all in the same boat, that is why i tried to put the line.contains('x') in a while loop, so it will add to the list while the nextline is not x, and then i convert it to array etc
Sponsor
Sponsor
Sponsor
sponsor
Panphobia




PostPosted: Wed Nov 21, 2012 8:55 am   Post subject: Re: Pathfinding error help

I am sorry I might be stupid as shit, but it still gives me an IndexOutOfBound exception, here is the code that is responsible
code:
while (!line.contains("x")) {
                line = s.nextLine();
                // if the line contains 'x' then stop reading
                // otherwise, add the line to the list
               
                if(line.contains("x")){
                    break;
                }else{
                    text.add(line);
                }

            }
            System.out.println(text.get(1));
DemonWasp




PostPosted: Wed Nov 21, 2012 12:37 pm   Post subject: RE:Pathfinding error help

You're not stupid. You are moving too fast. Slow down: programming is best done as slowly and methodically as you need to.

If something doesn't go exactly like you want, take a deep breath, close your eyes and count to 10, then look at it again, methodically. Go through it line-by-line. Explain what each line does to yourself (talk to yourself!). Don't take anything for granted: make sure each line does what you think it does as you go.

As a corollary, if you think something is working just the way you want, test it to make sure!

Look at this line:
code:
System.out.println(text.get(1));


You're getting an IndexOutOfBounds exception. What is the index there? Well, it has to be the 1.

How can a 1 be out of bounds? Well, consider the equivalent with arrays:
code:

int[] myArray = new int[1];
myArray[1] = 3;  // ArrayIndexOutOfBoundsException


This happens because arrays start at 0 (called "0-indexed"). So if you have an array of length 1, then the only in-bounds index is 0.

The same is true for arrays. If the while loop only ran once, there may be 1 element in the list, which means the only valid index is 0, so text.get(1) will be out of bounds.

It's even possible that you have two lines containing 'x' in a row. In that case, you may have an empty list: text.size() will return 0, and there is no valid index (any number you pass to text.get(number) will throw an IndexOutOfBoundsException). You can probably ignore that case here, but you should remember it for later.
Panphobia




PostPosted: Wed Nov 21, 2012 1:35 pm   Post subject: RE:Pathfinding error help

Ok i fixed that, now only one problem, when i have the array of chars, and try to output them, there is nothing in it, even when i give it values from the list
Panphobia




PostPosted: Wed Nov 21, 2012 8:45 pm   Post subject: Re: Pathfinding error help

When I try to output the array, it only outputs the lines printed with system.out.println and nothing in the actual array is outputted, so I do not know why the array is not getting the values from the arraylist, because the arraylist actually has the values
code:
   Scanner s = new Scanner(new File("C:\\Users\\DANIEL\\Desktop\\Java\\BFSV2\\src\\bfsv2\\DATA4.txt"));

        while (s.hasNext()) {
            List<String> text = new ArrayList<String>();
            char[][] maze;
            String line = "";
            while (!line.contains("x")) {
                line = s.nextLine();
                // if the line contains 'x' then stop reading
                // otherwise, add the line to the list

                if (line.contains("x")) {
                    break;
                } else {
                    text.add(line);
                }

            }
// Convert to 2D array
            int rows = text.size();
            maze = new char[col][rows];
            String texts;
            for (int y = 0; y < rows; y++) {
                texts = text.get(y);
                for (int x = 0; x < col; x++) {
                    maze[x][y] = texts.charAt(x);
                }
            }
            int x = 0;
            int y = 0;

            for (int z = 0; z < rows; z++) {
                for (int a = 0; a < col; a++) {
                    if (maze[a][z] == 'S') {
                        x = z;
                        y = a;
                    }
                }
            }
            // System.out.println(maze[0][0]);
            // System.out.println((bfs(maze, y, x, ' ', 'E') - 1));
        }
    }
DemonWasp




PostPosted: Wed Nov 21, 2012 11:56 pm   Post subject: RE:Pathfinding error help

It's pretty clear you didn't even try debugging that. Look at your code and try to figure out why your code doesn't print anything.

I'm pretty sure that the array does contain the correct values, you just aren't printing them correctly.
Panphobia




PostPosted: Thu Nov 22, 2012 12:04 am   Post subject: Re: Pathfinding error help

I know that I wasn't outputting, but even when I do, it doesnt work, here is the code that I use to output,
code:
for(int q = 0;q<rows;q++){
                for(int w=0;w<col;w++){
                    System.out.print(maze[w][q]);
                }
                System.out.println();
            }
Panphobia




PostPosted: Thu Nov 22, 2012 12:12 am   Post subject: RE:Pathfinding error help

yep you were right, it was right in front of my face (facepalm) I did not initialize col Smile
Display posts from previous:   
   Index -> Programming, Java -> Java Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 2 of 4  [ 58 Posts ]
Goto page Previous  1, 2, 3, 4  Next
Jump to:   


Style:  
Search: