reading the maze file and print it - java

This program is about maze recursion and I'm struggling finding out how to read the maze file and print the solved maze since I'm new in Java. Could anyone explain it to me how to call the print method from main method? Thank you in advance!
public class Maze {
private static char[][] maze;
private static int rows = 0;
private static int columns = 0;
public Maze(char[][] mazeIn) {
maze = mazeIn;
}
private static boolean valid (int r, int c) {
boolean result = false;
// check if cell is in the bounds of the matrix
if (r >= 0 && r < maze.length &&
c >= 0 && c < maze[0].length)
// check if cell is not blocked and not previously tried
if (maze[r][c] == '1')
result = true;
return result;
} // method valid
public static boolean solve (int r, int c) {
boolean done = false;
if (valid (r, c)) {
maze[r][c] = '7'; // cell has been tried
if (r == maze.length-1 && c == maze[0].length-1)
done = true; // maze is solved
else {
done = solve (r+1, c); // down
if (!done)
done = solve (r, c+1); // right
if (!done)
done = solve (r-1, c); // up
if (!done)
done = solve (r, c-1); // left
}
if (done) // part of the final path
maze[r][c] = '8';
}
return done;
} // method solve
public static void print () {
System.out.println();
for (int r=0; r < maze.length; r++) {
for (int c=0; c < maze[r].length; c++)
System.out.print (maze[r][c]);
System.out.println();
}
System.out.println();
} // method print_maze
public static void main(String[] args) throws IOException {
String fileName = "Maze.txt";
try {
String readline;
FileReader fileReader =
new FileReader(fileName);
BufferedReader br =
new BufferedReader(fileReader);
int line = 0;
while((readline = br.readLine()) != null) {
System.out.println(readline); //loads the maze
char[] charArr = readline.toCharArray();
maze[line] = charArr; // error here
line++;
}
br.close();
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
}
}
}
the maze.txt file looks like this
000100000000000
000100001000010
000111111111000
000100000001000
000111110001000
000000010001000
000011110001000
000010010001010
000010010000000
000010000000000
000011111110000
000000000010000
000000000010000
000001000011110
000000000010000

There are a few things I would do differently, but the important part is that you're not populating the char array with any data. While you're reading in the data, you need to populate it into the char array. Something like this would work:
int line = 0;
while((readline = br.readLine()) != null) {
System.out.println(readline); //loads the maze
char[] charArr = readline.toCharArray();
maze[line] = charArr;
line++;
}
Additionally, the maze array is never actually instantiated, and the main method is never calling "solve()" or "print()". These are things you can handle in your main method.
Finally, if you're going to call "solve()," you have to decide whether you want to instantiate an instance of the Maze class and call solve on that (which would involve quite a bit of code changes, but is the right approach), or else "solve()" should be a static method as well, which means "valid()" also has to be static.
P.S.: you have an error in your for-loop
for (int c=0; columns < maze[r].length; c++)
You should just change "columns" to "c".
P.P.S., in your solve method you're assigning ints to a char array. Put 7 and 8 in single-quotes to indicate that they're chars, not ints.
maze[r][c] = '7'; // cell has been tried
This is especially important in your valid() method, because you're testing if the maze[r][c]==1, but you should be testing if maze[r][c]=='1'.
I made all these changes myself and got this as output
000700000000000
000700007000010
000777777777000
000700000007000
000777770007000
000000070007000
000077770007000
000070070007010
000070070000000
000070000000000
000077777770000
000000000070000
000000000070000
000001000077770
000000000070000

Related

comparing two files and giving an output which ever file has the highest count

The problem with my code is, sometimes it reads and compares the string without any issue but again it also throws errors when comparing other strings. I think my comparing function isn't performing enough to the mark, where do I need to set the code efficiently so that my comparison function works efficiently?
can someone please suggest to me something? so far I have tried comparing two files using bufferedreader. my code works to some extent but at the same time encounters an error
"Exception in thread "main"
java.lang.StringIndexOutOfBoundsException:"
I have a few pictures which describe my problem intuitively. I think my findtarget function isn't accurate enough which is why it keeps throwing these exceptions
ERROR : click here to view the image.
NO-ERROR : click here to view the image.
and here is my two files which contains positive and negative keywords.
NEGITIVE : file extention is negi.txt
POSITIVE : file extention is posi.txt
here is the findtarget function which is used to compare the strings.
public static int findTarget(String target, String source)
{
int target_len = target.length();
int source_len = source.length();
int add = 0;
// this function check the character whether it is present.
for (int i = 0; i < source_len; ++i) // i is a varialbe used to count upto source_len.
{
int j = 0; // take another variable to count loops
//int[] k = new int[100];
while (add == 0)
{
if (j >= target_len) // count upto target length
{
break;
}
else if (target.charAt(j) != source.charAt(i + j))
{
break;
}
else
{
++j;
if (j == target_len)
{
add++; // this will return 1: true
}
}
}
}
return add;
//System.out.println(""+add);
}
here is my entire code just incase if you wanna run them.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
import java.io.FileWriter;
public class test {
public static int findTarget(String target, String source)
{
int target_len = target.length();
int source_len = source.length();
int add = 0;
// this function check the character whether it is present.
for (int i = 0; i < source_len; ++i) // i is a varialbe used to count upto source_len.
{
int j = 0; // take another variable to count loops
//int[] k = new int[100];
while (add == 0)
{
if (j >= target_len) // count upto target length
{
break;
}
else if (target.charAt(j) != source.charAt(i + j))
{
break;
}
else
{
++j;
if (j == target_len)
{
add++; // this will return 1: true
}
}
}
}
return add;
//System.out.println(""+add);
}
public static void main(String... args)
{
// function 1
//this variable can be called from any place inside this main function.
int testing1 = 0;
int testing2 = 0;
try {
//reads user review and store them inside source1
Scanner sc = new Scanner(System.in);
System.out.println("Enter your review: ");
String source1 = sc.nextLine();
//establising a file object
File file = new File("posi.txt");
BufferedReader br1 = new BufferedReader(new FileReader(file));
//establising a file object
File file2 = new File("negi.txt");
BufferedReader br2 = new BufferedReader(new FileReader(file2));
String target1; // using a string variable to read the content of the file posi.txt
while ((target1 = br1.readLine()) != null) //as long the condition is not null it will keep printing.
{
testing1 += test.findTarget(target1, source1); // supplying two arguments to findtarget function.
}
String target2; // using a string variable to read the content of the file negi.txt
while ((target2 = br2.readLine()) != null) //as long the condition is not null it will keep printing.
{
testing2 += test.findTarget(target2, source1); // supplying two arguments to findtarget function.
}
br1.close(); br2.close();
System.out.println("positive is:"+testing1 +"\nnegative is :"+testing2); //-not going to print now! :D-
System.out.println("\nthank you for your feedback! :)");
}
catch (IOException e)
{
System.out.println("file error!");
}
// this function is an area where it stores the return value inside a file called pos.txt
try
{
FileWriter myWriter = new FileWriter("pos.txt",true);
// using the true condition makes the line move to the next line.
myWriter.write(" "+testing1);
myWriter.close();
}
catch (IOException e)
{
System.out.println("An error occurred.");
}
// writing neg inside a file called neg.txt
try
{
FileWriter myWriter = new FileWriter("neg.txt",true);
// using the true condition makes the line move to the next line.
myWriter.write(" "+testing2);
myWriter.close();
}
catch (IOException e)
{
System.out.println("An error occurred.");
}
// to evaluate an output based on highest count.
if(testing1 > testing2)
System.out.println("it is positive");
else if (testing1 == testing2)
System.out.println("it is neutral");
else
System.out.println("it is negative");
}
}
finally, I was able to solve the problem by using one of string method known as "regionmatches". Note: make sure your positive and negative files are arranged in an alphabetical sequence. This will give you an accurate increment.
Github : use my link to download the positive and negative keywords.
public static int findTarget(String target, String source) //method/function
{
String sourcee = source;
String targett = target;
int source_len = sourcee.length();
int target_len = targett.length();
/*
**this function check the character whether it is present using one of string methond called "regionmatch"
**regionMatches(int toffset, String other, int ooffset,int len)
*/
int add = 0;
boolean foundIt = false;
for (int i = 0;i <= source_len - 1;i++)
{
if (sourcee.regionMatches(i, targett, 0, target_len))
{
foundIt = true;
break;
}
}
//checking
if(!foundIt)
{
// do nothing.
}
else
{
add++;
}
return add; //returns incrementation
}
You increment i to the lenght of source but you call
.
.
.
else if (target.charAt(j) != source.charAt(i + j))
.
.
.
which exceeds the lenght of source at some point.
Lets say i == source.length, then source.charAt(i + j) throws an exception as soon as j > 0.

Throw Exception when the String shape is illegal

Im doing something wrong with the Excetpion in my code because when a String layout such as:
..b.
bbb. //<---Illegal
...
.x.
... //<---Illegal
..r
.rr //<---Illegal
.....
.y...
..y..
...y. //<---Illegal
is passed into the method (only one layout can be passed at one time), the method should throw an exception because String layouts for shapes must have at least one filled block in each of 0th row, 0th column, last row, and last column. The following String layouts are legal:
...e
..e.
e...
a...a
.....
.....
a....
My code only handles Exception when it sees the first and last charcters of the first line. Can smb please help me out with this method regarding throwing Exception? Thanks in advance!
public static Shape makeShape(String layout,char displayChar)
{
Shape result;
int height = 0;
int width = 0;
Scanner data = new Scanner(layout);
char[][] temp;
while(data.hasNextLine())
{
String line = data.nextLine();
height = line.length();
width++;
}
temp = new char[height][width];
Scanner data2 = new Scanner(layout);
while(data2.hasNextLine())
{
String line2 = data2.nextLine();
if(line2.charAt(0) == '.' && line2.charAt(width) == '.')
throw new FitItException("Empty borders!");
else {
for (int r = 0; r < height; r++)
for (int c = 0; c < width; c++) {
// System.out.println(line2.charAt(c));
if (temp[r][c] == '.') {
temp[r][c] = displayChar;
}
System.out.println(line2.charAt(temp[r][c]));
}
}
}
result = new CreateShape(height, width, displayChar, layout);
return result;
}
There are a couple of things not clear to me still, so I concentrated on parsing the layout into a two dimensional char array and checking for the constraints you specified. Hopefully that will let you adapt it to your exact needs:
public static char[][] parseShape(String layout, char displayChar) throws Exception {
int height = 0;
Scanner data = new Scanner(layout);
ArrayList<String> lines = new ArrayList<String>();
// parse layout into an array of lines to determine dimensions
while (data.hasNextLine()) {
String line = data.nextLine();
lines.add(line);
height = line.length();
}
int width = lines.size();
char[][] temp = new char[height][width];
Boolean row0 = false;
Boolean col0 = false;
Boolean rowLast = false;
Boolean colLast = false;
// parse array of lines in char array and check for constraints
for (int w = 0; w < width; w++) {
String line = lines.get(w);
for (int h = 0; h < height; h++) {
char c = line.charAt(h);
if (c == displayChar) {
// we are looking at the display characters,
// check if we're in any of rows of columns that matter
if (h == 0)
row0 = true;
if (w == 0)
col0 = true;
if (h == height - 1)
rowLast = true;
if (w == width - 1)
colLast = true;
}
temp[h][w] = c;
}
}
// if any of the constraints are not true, the layout is invalid
if(!row0) {
throw new Exception("no block in Oth row");
}
if(!col0) {
throw new Exception("no block in Oth column");
}
if(!rowLast) {
throw new Exception("no block in last row");
}
if(!colLast) {
throw new Exception("no block in last column");
}
return temp;
}
Basically we have to parse the entire layout and accumulate the constraints that are satisfied rather than checking for non-satisfaction. Only at the end will we know if they are not all satisfied.
A simpler approach might be to use regular expressions.
Your requirements can be expressed as:
at least one line must start with a non-.
at least one line must end with a non-.
the first line must contain at least one non-.
the last line must contain at least one non-.
The patterns for these can be written as:
private static final LINE_STARTS_WITH_NON_DOT =
Pattern.compile("^[^.]", Pattern.MULTILINE);
private static final LINE_ENDS_WITH_NON_DOT =
Pattern.compile("[^.]$", Pattern.MULTILINE);
private static final FIRST_LINE_CONTAINS_NON_DOT =
Pattern.compile("^\\.*[^.]");
private static final LAST_LINE_CONTAINS_NON_DOT =
Pattern.compile("[^.]\\.*$");
To ensure that each pattern matches layout, you can write:
if (!LINE_STARTS_WITH_NON_DOT.matcher(layout).find()
|| !LINE_ENDS_WITH_NON_DOT.matcher(layout).find()
|| !FIRST_LINE_CONTAINS_NON_DOT.matcher(layout).find()
|| !LAST_LINE_CONTAINS_NON_DOT.matcher(layout).find()) {
throw new FitItException("Empty borders!");
}
(Note: the above assumes that layout does not end with a newline. If it does end with a newline, then you'll need to change LINE_ENDS_WITH_NON_DOT to Pattern.compile("[^.]\n") and LAST_LINE_CONTAINS_NON_DOT to Pattern.compile("[^.]\\.*\n$").)

Array Out of Bounds Exception in 2D array - how can I avoid this?

I'm a begginer in Java and I am writing a program to solve mazes, as an assignment. Right now, I'm having a hard time with something that may be pretty stupid on the part that reads the maze from a cvs file, but I just can't fix it.
I get ArrayOutOfBounds exception for the line that says "while (info[x] != null) {", for some reason. I need to check if the array element is empty or not for my program to run, but it's not working. Any ideas?
public class Project5v2
{
static String mazecsv = "/Users/amorimph/Documents/COMP 182/Project 5/mazeinput.csv";
static File solvedMaze = new File("/Users/amorimph/Documents/COMP 182/Project 5/solvedMaze.txt");
static int[][] maze = new int[50][50];
static int trigger = 0;
static int mazeWidth;
static int mazeHeight;
public static void main(String[] args) {
readCSV(mazecsv);
start(maze);
mazeToString(maze);
}
public static void readCSV(String csvfile) {
BufferedReader br = null;
String line = "";
String csvSplitBy = ",";
int x = 1;
int y = 0;
try {
br = new BufferedReader(new FileReader(csvfile));
br.readLine();
while ((line = br.readLine()) != null) {
String[] info = line.split(csvSplitBy);
while (info[x] != null) {
maze[x][y] = Integer.parseInt(info[x]);
x++;
mazeWidth = x;
}
y++;
x = 1;
mazeHeight = y;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
change this to a for loop
while (info[x] != null) {
maze[x][y] = Integer.parseInt(info[x]);
x++;
mazeWidth = x;
}
to:
for (int x = 0; x < info.length; x++) {
maze[x][y] = Integer.parseInt(info[x]);
}
mazeWidth = info.length;
This is assuming that info will not be greater than 50, which is the size that you have defined for maze. If this is not guaranteed then
for (int x = 0; x < info.length && x < maze.length; x++) {
You are getting the error on that line because there is nothing to stop x from incrementing to a number BEYOND the greatest row value in maze. So one thing that you could do if you wanted to keep the while loop is add another condition.
Just add this to your while loop, IFF you need or want to keep the while around.
while(info[x] != null && x < maze.length)
{
//magicalness
}
The additional boolean statement prevents the OutOfBounds error by making sure x is not greater than the number of rows in the 2D array or the length of the array called info.

Java program freaks out when user inputs parenthesis

I am making a simple calculator, however before I can do that, I need to make an algorithm to convert a user input into a consistent format. The user can input numbers and operators as well as parenthesis. The program has no problem dealing with numbers and operators, but for some unknown reason it throws an error whenever the loop encounters a parenthesis.
I have been attempting to debug the code for the past few hours, but I can't seem to figure out why this is happening?
/** These are the possible operators */
private static final String OPERATORS = "+-/*%^()[]{}";
/** This is an ArrayList of all the discrete
things (operators/operands) making up an input.
This is really just getting rid of the spaces,
and dividing up the "stuff" into manageable pieces.
*/
static ArrayList<String> input = new ArrayList<String>();
public static ArrayList inputCleaner(String postfix) {
StringBuilder poop = new StringBuilder();
String doody = postfix.replace(" ", "");
try {
for (int i = 0; i < doody.length(); i++) {
char c = doody.charAt(i);
boolean isNum = (c >= '0' && c <= '9');
if (isNum) {
poop.append(c);
if (i == doody.length() - 1) {
input.add(poop.toString());
poop.delete(0, poop.length());
}
}
else if (c == '.') {
for (int j = 0; j < poop.length(); j++) {
if (poop.charAt(j) == '.') {
throw new SyntaxErrorException("You can't have two decimals in a number.");
}
else if (j == poop.length() - 1) {
poop.append(c);
}
}
if (i == doody.length() - 1) {
throw new SyntaxErrorException("You can't end your equation with a decimal!");
}
}
else if (OPERATORS.indexOf(c) != -1 && poop.length() != 0) {
input.add(poop.toString());
poop.delete(0, poop.length());
poop.append(c);
input.add(poop.toString());
poop.delete(0, poop.length());
}
else {
throw new SyntaxErrorException("Make sure your input only contains numbers, operators, or parantheses/brackets/braces.");
}
}
return input;
}
catch (SyntaxErrorException exc) {
System.out.println("That didn't work, something was wrong with the syntax.");
return input;
}
}
public static void main(String[] args) {
ArrayList test = new ArrayList();
Scanner f = new Scanner(System.in);
System.out.println("Please insert an argument: \n");
String g = f.nextLine();
test = inputCleaner(g);
for (int z = 0; z < test.size(); z++) {
System.out.println(test.get(z));
}
}
I know my answer is not very good coz I have no good explanation for it(due to brain overheat at work) but this change doesn't throw exception as in your case(might be an answer for you ;) )
Instead of using poop.length() != 0 in the condition I have simply changed it to poop != null and voila... there are no Exceptions now. Comment if you can explain me this.

Java Horner's polynomial accumulation method

So far, I have this code, which, in summary, takes two text files and a specified block size in cmd and standardises the txt files, and then puts them into blocks based on the specified block size.
import java.io.*;
import java.util.*;
public class Plagiarism {
public static void main(String[] args) throws Exception {
//you are not using 'myPlag' anywhere, you can safely remove it
// Plagiarism myPlag = new Plagiarism();
if (args.length == 0) {
System.out.println("Error: No files input");
System.exit(0);
}
String foo = null;
for (int i = 0; i < 2; i++) {
BufferedReader reader = new BufferedReader(new FileReader(args[i]));
foo = simplify(reader);
// System.out.print(foo);
int blockSize = Integer.valueOf(args[2]);
List<String> list = new ArrayList<String>();
for (int k = 0; k < foo.length() - blockSize + 1; k++) {
list.add(foo.substring(k, k + blockSize));
}
// System.out.print(list);
}
}
public static String simplify(BufferedReader input)
throws IOException {
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = input.readLine()) != null) {
sb.append(line.replaceAll("[^a-zA-Z]", "").toLowerCase());
}
return sb.toString();
}
}
The next thing I would like to do is use Horner's polynomial accumulation method (with set value x = 33) to convert each of these blocks into a hash code. I am completely stumped on this and would appreciate some help from you guys!
Thanks for reading, and thanks in advance for any advice given!
Horner's method for hash generation is as simple as
int hash=0;
for(int i=0;i<str.length();i++)
hash = x*hash + str.charAt(i);

Categories

Resources