File to 2D Array - java

I need to create a 2D array from a text file for later use in some operations.
This is my file separated by a space" ":
0 1 0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0 1 0
And this is the code that I have:
import java.io.*;
public class TxtToArray{
public static void main(String args[]){
double[][] array = new double[100][100];
int x=0, y=0;
try{
BufferedReader in = new BufferedReader(new FileReader("E:\\Documents\\JavaPrograms\\TxtToArray\\src\\Array.txt"));
String bar;
while ((bar = in.readLine()) != null){
String[] values = bar.split(" ");
for (String str : values){
double str_double = Double.parseDouble(str);
array[x][y]=str_double;
y++;
}
x++;
}
in.close();
}catch( IOException ioException ) {
System.out.println("Something happened...");
}
}
}
Thanks! for the help
EDIT:
I have corrected some errors in what came to be the explanation and code syntax. If there are more let me know.

You never told us what the problem is, but one issue I see is that you are splitting each line of input on comma alone. This won't work because your input data also uses space as a delimeter. One option is to remove this whitespace before splitting by comma:
while ((bar = in.readLine()) != null) {
String[] values = bar.replaceAll("\\s+", "")
.split(",");
for (int y=0; y < values.length; ++y) {
double str_double = Double.parseDouble(values[y]);
array[x][y] = str_double;
}
x++;
}
You will notice that I used a for loop to iterate over the strings in each input. This is a nice option because it eliminates the need for you to manage the second index of your array.

Your numers in the file are not only seperated by ,, but also by whitespaces. Double.parseDouble throws an exception, if this whitespace is included in the parameter. Therefore you need to use a regex that also matches these chars too, e.g. ,\s*. Also you need to set y back to 0 at the beginning of every iteration of the while loop:
while ((bar = in.readLine()) != null){
String[] values = bar.split(",\\s*");
y = 0;
for (String str : values){
double str_double = Double.parseDouble(str);
array[x][y] = str_double;
y++;
}
x++;
}

Related

How to solve java 2D array

i wrote the code correctly for 2D array hourglass problem.but it shows only one error.i did not know how to rectify it and also i dint know how it will work on negative numbers.how i can get 13 as output from my code.
Input (stdin)
1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 9 2 -4 -4 0
0 0 0 -2 0 0
0 0 -1 -2 -4 0
Your Output (stdout)
0
Expected Output
13
here is my code:
public class Solution {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int rows =sc.nextInt();
int column = sc.nextInt();
int[][] a = new int[rows][column];
for(int i=0;i<rows;i++){
for(int j=0;j<column;j++){
a[i][j]=sc.nextInt();
}
}
int sum=0,max=0;
for(int i=0;i<rows-2;i++){
for(int j=0;j<column-2;j++){
sum =(a[i][j]+a[i][j+1]+a[i][j+2]+a[i+1][j+1]+a[i+2][j]+a[i+2][j+1]+a[i+2][j+2]);
if(sum>max){
max = sum;
}
}
}
System.out.println(max);
}
}
In the stdin you haven't provided the rows and columns value as input. Your code works fine and gives the output 13.
For this particular problem, your stdin should be:
6 6
1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 9 2 -4 -4 0
0 0 0 -2 0 0
0 0 -1 -2 -4 0
Where the first line represents rows and columns. And will be assigned to:
int rows =sc.nextInt();
int column = sc.nextInt();
So what was the problem in your code?
Previously these were assigned 1 and 1 [the first two inputs] and took only 1 and 0 (the next two inputs) as the corresponding value. As a result, it couldn't satisfy the entry conditions in loop. hence the sum remained 0 and showed that as an output.

Java - Adjacency Matrix and DFS

I've been working on a program to implement a DFS in Java (by taking an adjacency matrix as input from a file). Basically, assuming vertices are traveled in numerical order, I would like to print the order that vertices become dead ends, the number of connected components in the graph, the tree edges and the back edges. But I'm not completely there yet. When I run my program, I get the number "1" as output, and nothing more. I've tried debugging certain parts of the DFS class, but I still can't quite figure out where I'm going wrong. Here is my code:
A basic "Driver" class:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Driver {
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("sample1.txt"));
scanner.useDelimiter("[\\s,]+");
int input = scanner.nextInt();
int[][] adjMatrix = new int[8][8];
for(int i=0; i < input; i++) {
for (int j=0; j < input; j++) {
adjMatrix[i][j] = scanner.nextInt();
}
}
scanner.close();
new DFS(adjMatrix);
}
}
DFS class:
import java.util.Stack;
public class DFS {
Stack<Integer> stack;
int first;
int[][] adjMatrix;
int[] visited = new int[7];
public DFS(int[][] Matrix) {
this.adjMatrix = Matrix;
stack = new Stack<Integer>();
int[] node = {0, 1, 2, 3, 4, 5, 6};
int firstNode = node[0];
depthFirstSearch(firstNode, 7);
}
public void depthFirstSearch(int first,int n){
int v,i;
stack.push(first);
while(!stack.isEmpty()){
v = stack.pop();
if(visited[v]==0) {
System.out.print("\n"+(v+1));
visited[v]=1;
}
for (i=0;i<n;i++){
if((adjMatrix[v][i] == 1) && (visited[i] == 0)){
stack.push(v);
visited[i]=1;
System.out.print(" " + (i+1));
v = i;
}
}
}
}
}
And the matrix from the input file looks like this:
0 1 0 0 1 1 0 0
1 0 0 0 0 1 1 0
0 0 0 1 0 0 1 0
0 0 1 0 0 0 0 1
1 0 0 0 0 1 0 0
1 1 0 0 1 0 0 0
0 1 1 0 0 0 0 1
0 0 0 1 0 0 1 0
Take a look at this part:
int input = scanner.nextInt();
int[][] adjMatrix = new int[8][8];
for(int i=0; i < input; i++) {
for (int j=0; j < input; j++) {
adjMatrix[i][j] = scanner.nextInt();
}
}
First you read a number, input.
Then you read input rows, in each row input columns.
This is your input data:
0 1 0 0 1 1 0 0
1 0 0 0 0 1 1 0
0 0 0 1 0 0 1 0
0 0 1 0 0 0 0 1
1 0 0 0 0 1 0 0
1 1 0 0 1 0 0 0
0 1 1 0 0 0 0 1
0 0 0 1 0 0 1 0
What is the first number, that will be read by scanner.nextInt().
It's 0. So the loop will do nothing.
Prepend the number 8 to your input, that is:
8
0 1 0 0 1 1 0 0
1 0 0 0 0 1 1 0
0 0 0 1 0 0 1 0
0 0 1 0 0 0 0 1
1 0 0 0 0 1 0 0
1 1 0 0 1 0 0 0
0 1 1 0 0 0 0 1
0 0 0 1 0 0 1 0
Btw, it's a good idea to verify that you have correctly read the matrix.
Here's an easy way to do that:
for (int[] row : adjMatrix) {
System.out.println(Arrays.toString(row));
}
There are several other issues in this implementation:
The number 7 appears in a couple of places. It's actually a crucial value in the depth-first-search algorithm, and it's actually incorrect. It should be 8. And it should not be hardcoded, it should be derived from the size of the matrix.
It's not a good practice to do computation in a constructor. The purpose of a constructor is to create an object. The depth-first-logic could be moved to a static utility method, there's nothing in the current code to warrant a dedicated class.
Fixing the above issues, and a few minor ones too, the implementation can be written a bit simpler and cleaner:
public static void dfs(int[][] matrix) {
boolean[] visited = new boolean[matrix.length];
Deque<Integer> stack = new ArrayDeque<>();
stack.push(0);
while (!stack.isEmpty()) {
int v = stack.pop();
if (!visited[v]) {
System.out.print("\n" + (v + 1));
visited[v] = true;
}
for (int i = 0; i < matrix.length; i++) {
if (matrix[v][i] == 1 && !visited[i]) {
visited[i] = true;
stack.push(v);
v = i;
System.out.print(" " + (i + 1));
}
}
}
}

Array out of Bounds Exception when populating 2D Array maze

I am currently prepping to head into a Data Structures Course and as a result have begun reading on certain topics before hand. I am currently studying up on Stacks but have come across a problem.
I am currently coding a Maze App that uses stacks to auto-solve a maze. However, I am experiencing a problem when it comes populating the maze itself.
Code below:
import java.io.*;
import java.util.*;
public class Maze {
private Square move;
private char[][] maze;
private SquareStack s;
private String path =
"C:\\Users\\Sigh\\workspace\\StegmannStackMaze\\maze.txt";
private File file = new File(path);
public Maze(){
s = new SquareStack();
maze = new char[12][12];
}
public void getMaze() throws IOException{
for (int row = 0; row < 12 ; ++row){ // Creates the left/right walls of the maze " | | "
maze[row][0] = '1';
maze[row][11] = '1';
}
for ( int col = 0; col < 12 ; ++col){ // Creates upper and lower walls of the maze
maze[0][col] = '1';
maze[11][col] = '1';
}
Scanner filescan = new Scanner(path);
for( int row = 1; row <= 10 ; ++row){
String line = filescan.nextLine();
String delim = "[ ]+";
String[] tokens = line.split(delim);
for(int col = 1; col <= 10; ++col)
maze[row][col] = tokens[col-1].charAt(0);
}
filescan.close();
}
}
Here is the .txt file
0 0 1 E 1 0 0 1 1 1
0 1 1 0 1 0 1 0 0 0
0 0 0 0 0 0 0 0 1 0
1 1 1 1 1 0 1 1 0 0
0 0 0 1 0 0 0 1 0 1
0 1 0 1 0 1 1 1 0 1
0 1 0 1 0 0 0 1 0 0
1 1 0 1 1 1 0 1 1 0
0 1 0 0 0 0 0 1 1 0
0 1 0 1 1 0 1 0 0 0
The Exception itself occurs at this particular line once col = 2.
for(int col = 1; col <= 10; ++col)
maze[row][col] = tokens[col-1].charAt(0);
}
From what I gather, this line takes each token that is created and populates the column. However, I am not sure why I get a exception.
Thanks for reading and hopefully I can get some insight from you guys.
Changes
Scanner filescan = new Scanner(path);
to
Scanner filescan = new Scanner(file);
The path is a String variable rather than File instance.

How do I generate a Matrix style output

I'm trying to get an output of a random string consisted of 1's and 0's in a Matrix style. I know how to display a string consisted of 1's and 0's, but I can't keep on looping through it for some reason. What I'm trying to do, is that whenever the StringBuilder reaches the length of 20, I want to start the loop on a new line again and repeat this 100 times.
import java.util.List;
import java.util.Random;
public class main {
static Random rand = new Random();
static StringBuilder x = new StringBuilder();
static int a = 0;
public static void main(String[] args) {
generatingnumber();
}
public static void generatingnumber() {
for (int bv = 0; bv <= 100; bv++) {
int random = rand.nextInt(50);
if (random % 2 == 0) {
x.append(" 0");
} else {
x.append(" 1");
}
if (x.length() == 20) {
System.out.println(x);
}
}
}
}
public class MatrixFilm {
public static void main(String[] args) {
int rows = 100;
int cols = 20;
for (int count1 = 0; count1 < (rows * cols); count1++) {
for (int count2 = 0; count2 < cols; count2++) {
int randomNum = 0 + (int) (Math.random() * 2);
System.out.print(" " + randomNum);
}
System.out.println();
}
}
}
Result:
0 0 1 0 0 0 0 1 0 0 1 1 0 0 1 0 1 1 1 1
1 1 0 1 1 1 0 1 0 1 0 1 1 0 1 1 0 0 1 0
0 1 0 0 1 0 1 1 0 0 1 1 1 0 1 1 1 1 1 0
0 1 0 1 1 1 1 1 0 0 1 1 0 0 0 1 1 0 1 0
0 0 0 1 0 1 0 0 1 0 0 0 1 0 1 0 0 1 0 0
....
Your string has length of 20 characters only once. You are not interested in whether x.length() == 20 but if x.length() % 20 == 0.
For a new line you can append "\n" (or "\r\n" for Windows machine) to the string, everytime just before printing it.
Change println to print (which doesn't add new line character at the end of printed string) in order to maintain continuity between prints.
Taking all into account:
if (x.length() % 20 == 0) {
x.append("\r\n");
System.out.print(x);
}
However it still wouldn't be enough, for "\r\n" itself adds to the length of the string. This should work:
if (x.length() % 20 == 0) {
x.replace(x.length() - 2, x.length(), "\r\n");
System.out.print(x);
}
You can also - and it would be better to... - reset the string, as #owlstead has mentioned.
if (x.length() == 20) {
System.out.println(x);
x.setLength(0);
}
Anyway; what I presented is not a solution for the problem. Only solution to - probably improper - approach you have currently taken on it.

NumberFormatException in my code

I was solving the Connected Sets problem on Amazon's Interview Street site https://amazon.interviewstreet.com/challenges and my code worked perfectly for the public sample test cases provided by the site, but I'm getting a NumberFormatException for the hidden test cases on line 25. Here is the part of my code that parses the input:
public class Solution
{
static int [][] arr;
static int num = 2;
static int N;
static String output = "";
public static void main(String[] args) throws IOException
{
int T;
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
T = Integer.parseInt(reader.readLine());
int i, j, k;
for(i=0;i<T;i++) //the loop for each of the 'T' test cases
{
N = Integer.parseInt(reader.readLine()); //line 25
arr = new int[N][N];
for(j=0;j<N;j++) //the loops for storing the input 2D array
{
for(k=0;k<N;k++)
{
arr[j][k] = Character.getNumericValue(reader.read());
reader.read();
}
}
I spent a lot of time trying to find what the problem is, but I've been unsuccessful at it. Thanks for your help in advance.
EDIT: The problem statement is given as follows on the site:
Given a 2–d matrix, which has only 1’s and 0’s in it. Find the total number of connected sets in that matrix.
Explanation:
Connected set can be defined as group of cell(s) which has 1 mentioned on it and have at least one other cell in that set with which they share the neighbor relationship. A cell with 1 in it and no surrounding neighbor having 1 in it can be considered as a set with one cell in it. Neighbors can be defined as all the cells adjacent to the given cell in 8 possible directions ( i.e N , W , E , S , NE , NW , SE , SW direction ). A cell is not a neighbor of itself.
Input format:
First line of the input contains T, number of test-cases.
Then follow T testcases. Each testcase has given format.
N [ representing the dimension of the matrix N X N ].
Followed by N lines , with N numbers on each line.
Output format:
For each test case print one line, number of connected component it has.
Sample Input:
4
4
0 0 1 0
1 0 1 0
0 1 0 0
1 1 1 1
4
1 0 0 1
0 0 0 0
0 1 1 0
1 0 0 1
5
1 0 0 1 1
0 0 1 0 0
0 0 0 0 0
1 1 1 1 1
0 0 0 0 0
8
0 0 1 0 0 1 0 0
1 0 0 0 0 0 0 1
0 0 1 0 0 1 0 1
0 1 0 0 0 1 0 0
1 0 0 0 0 0 0 0
0 0 1 1 0 1 1 0
1 0 1 1 0 1 1 0
0 0 0 0 0 0 0 0
Sample output:
1
3
3
9
Constraint:
0 < T < 6
0 < N < 1009
Note that the above sample test cases worked on my code. The hidden test cases gave the exception.
Okay, so I modified my program to incorporate LeosLiterak's suggestion to use trim() and the new code is as follows:
public class Solution
{
static int [][] arr;
static int num = 2;
static int N;
static String output = "";
public static void main(String[] args) throws IOException
{
int T;
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
T = Integer.parseInt(reader.readLine().trim());
int i, j, k;
for(i=0;i<T;i++)
{
N = Integer.parseInt(reader.readLine().trim());
arr = new int[N][N];
for(j=0;j<N;j++)
{
String [] temp = reader.readLine().trim().split(" ");
for(k=0;k<N;k++)
{
arr[j][k] = Integer.parseInt(temp[k]);
}
}
So instead of reading each character in the input matrix and converting it to an integer and storing, I now read the entire line and trim and split the string and convert each substring into an integer and store in my array.
Copied from comments: try to remove all white characters like spaces, tabulators etc. These characters are not prohibited by goal definition but they cannot be parsed to number. You must trim them first.
Check if its number before parse to int.
Character.isNumber()
T = Integer.parseInt(reader.readLine()); This where the problem. when user try to give string
and it convert into integer and run through loop? For eg : if user gives 'R' as char than how the integer conversion can happen and will the loop run further?? No right.

Categories

Resources