how to get int[][] dimensionArray? - java

I want to get matrix[i][j] to my int[][] gettwodimensionalArray, I try so many way, but when I do the test, my gettwodimensionaArray still not store from matrix[i][j]. Please help me out, thank you.
Here is my code look like.
public int[][] gettwodimensionalArray(String file_name) {
File file = new File(file_name);
ArrayList<int[]> rows = new ArrayList<int[]>();
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] s = line.split("\\s+");
int[] row = new int[s.length];
for (int i = 0; i < s.length; i++) {
row[i] = Integer.parseInt(s[i]);
}
rows.add(row);
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int numbOfRow = rows.size();
// find number of columns by gettting the lenght of one of the rows row
int keepTrackSizeFirstRow;
for (int i = 0; i < numbOfRow; i++) {
if (i == 0) {
keepTrackSizeFirstRow = rows.get(0).length;
}
// compare current row i's array length, to keetracksizefirstrow
}
int[][] matrix = new int[numbOfRow][rows.get(0).length];
// System.out.println(matrix);
for (int i = 0; i < numbOfRow; i++) {
// i = row
for (int j = 0; j < rows.get(i).length; j++) {
// j = col
matrix[i][j] = rows.get(i)[j];
System.out.print(matrix[i][j]);
}
}
return matrix;
}

Not sure what you are trying to do. If you want each row of the input to fit in the array, you can declare the array with variable sizes, like this:
int[][] matrix = new int[numbOfRow][];
for (int i = 0; i < matrix.length; i++) {
matrix[i] = new int[rows.get(i).length];
}
If instead you want all rows to have the same length, you should find the maximum length of the input like this:
int maxlength = 0;
for (int i = 0; i < rows.size(); i++) {
maxlength = (rows.get(i).length > maxlength) ? rows.get(i).length : maxlength;
}
int[][] matrix = new int[numbOfRow][maxlength];

Related

how to get String array containing distinct characters?

i have a String "iye" and i want make it distinct and also i have a array ["hi", "bye", "bebe"] and i want to make each element of the array and get the distinct characters only so my array would be like this ["hi", "bye", "be"] an then at last i want to take each element from that distinct array and count how many characters of distinctArray[i] are present in the distinct String "iye" and i will store that count for each element of distinct array in same order respectively to the elements of distinct array for e.g
sample input = "iyee" and ["hi", "bye", "bebe"]
sample ouput = [1, 2, 1]
below is my solution not working for larger inputs
static int[] mathProfessor(String B,String[] a){
List<String> distinct = new ArrayList<String>();
int[] arr = new int[a.length];
// store each value of names array as distinct value
for (int i = 0; i < a.length; i++) {
StringBuilder str = new StringBuilder();
a[i].chars().distinct().forEach(c -> str.append((char) c));
distinct.add(str.toString());
}
// System.out.println("distinct list: " + distinct.toString());
// store the count
int count = 0;
for (int i = 0; i < distinct.size(); i++) {
String s = distinct.get(i);
for (int j = 0; j < B.length(); j++) {
if (s.contains(Character.toString(B.charAt(j))))
count++;
}
arr[i] = count;
count = 0;
}
return arr;
}
static int[] mathProfessor(String b, String[] a) {
b = dist(b);
int count = 0;
String[] arr = new String[a.length];
int[] countArr = new int[a.length];
for (int i = 0; i < a.length; i++) {
arr[i] = dist(a[i]);
}
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < b.length(); j++) {
if (arr[i].contains(Character.toString(b.charAt(j))))
count++;
}
countArr[i] = count;
count = 0;
}
//System.out.println(Arrays.toString(countArr));
return countArr;
}
public static String dist(String s) {
StringBuilder sb = new StringBuilder();
Set<Character> set = new HashSet<Character>();
for (int i = 0; i < s.length(); i++) {
if (set.add(s.charAt(i)) == true)
sb.append(s.charAt(i));
}
return sb.toString();
}
Using Java 8+ Streams:
static int[] mathProfessor(String b, String[] a) {
var distinctB = dist(b);
System.out.println(distinctB);
var result = new int[a.length];
for(int i=0, j=a.length; i < j; i++) {
result[i] = (int) Arrays.stream(dist(a[i]).split("")).filter(distinctB::contains).count();
}
return result;
}
public static String dist(String s) {
Set<String> set = new HashSet<>();
set.addAll(Arrays.asList(s.split("")));
return String.join("", set);
}

How do I convert a String into a 2D array

I have to define a method called getDistance. That takes the following string:
0,900,1500<>900,0,1250<>1500,1250,0 and returns a 2d array with the all the distances. The distances are separated by "<>" symbol and they are separated into each column by ",".
I know I need to use String.split method. I know splitting by the commmas will give me the columns and splitting it by the "<>" will give me the rows.
public static int[][] getDistance(String array) {
String[]row= array.split(",");
String[][] distance;
int[][] ctyCoord = new int[3][3];
for (int k = 0; k < row.length; k++) {
distance[k][]=row[k].split("<>");
ctyCoord[k][j] = Integer.parseInt(str[j]);
}
return ctyCoord;
This is a working dynamic solution:
public static int[][] getDistance(String array) {
String[] rows = array.split("<>");
int[][] _2d = null;
// let us take the column size now, because we already got the row size
if (rows.length > 0) {
String[] cols = rows[0].split(",");
_2d = new int[rows.length][cols.length];
}
for (int i = 0; i < rows.length; i++) {
String[] cols = rows[i].split(",");
for (int j = 0; j < cols.length; j++) {
_2d[i][j] = Integer.parseInt(cols[j]);
}
}
return _2d;
}
Let's test it:
public static void main(String[] args) {
String given = "0,900,1500<>900,0,1250<>1500,1250,0";
int[][] ok = getDistance(given);
for (int i = 0; i < ok.length; i++) {
for (int j = 0; j < ok[0].length; j++) {
int k = ok[i][j];
System.out.print(k + " ");
}
System.out.println();
}
}
I think you should first split along the rows and then the colums. I would also scale the outer array with the number of distances.
public static int[][] getDistance(String array) {
String[] rows = array.split("<>");
int[][] out = new int[rows.length][3];
for (int i = 0; i < rows.length, i++) {
String values = rows[i].split(",");
for (int j = 0; j < 3, j++) {
out[i][j] = Integer.valueOf(values[j]);
}
}
return out;

Reading data from file into 2d array

I need to read a file with a magic square in the format of:
#
# # #
# # #
# # #
where the first line represents the square size and create a 2d array with the file values.
I set up my readMatrix method to read through the lines, created a 2d array of the correct size and input each value to its correct position.
private int[][] readMatrix(String fileName) throws
FileNotFoundException {
int n;
File file = new File(fileName);
Scanner fileScan = new Scanner(file);
String line = fileScan.nextLine();
Scanner lineScan = new Scanner(line);
n = lineScan.nextInt();
square = new int[n][n];
while (fileScan.hasNextLine()) {
line = fileScan.nextLine();
while (lineScan.hasNext()) {
for (int i = 0; i < n; i++) {
lineScan = new Scanner(line);
for (int j = 0; j < n; j++) {
square[i][j] = lineScan.nextInt();
}
}
}
}
fileScan.close();
lineScan.close();
return square;
public int[][] getMatrix() {
int[][] copy;
int n = square.length;
copy = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
copy[i][j] = square[i][j];
}
}
return copy;
However the tester for this program displays a magic square of the correct dimensions but with all the values being 0 and fails the getMatrix method(I'm assuming because the returned square doesn't match the file square). I tried moving the scanner objects around(inside/outside) the for/while loops in the readMatrix and tried using parseInt/scan next instead of nextInt with no success. I am stumped.
Try this code is able to display 1 - 9 from the 3 x 3 matrix. The variable type can be changed to your need. I used 'char' for ease.
private static char[][] finalmatrix;
public static void main(String[] args) throws Exception {
finalmatrix = readMatrix("File.txt");
// Output matrix.
for (int i = 0; i < finalmatrix.length ;i++) {
for (int j = 0; j < finalmatrix[i].length ;j++) {
System.out.print(finalmatrix[i][j] + " ");
}
System.out.println("");
}
}
private static char[][] readMatrix(String fileName) throws IOException {
File file = new File(fileName);
Scanner scan = new Scanner(file);
int countRow = 0;
int countColumn = 0;
List temp = new ArrayList();
while (scan.hasNextLine()) {
String line = scan.nextLine();
for (int i = 0; i < line.length(); i++) {
// Count the number of columns for the first line ONLY.
if (countRow < 1 && line.charAt(i) != ' ') {
countColumn++;
}
// Add to temporary list.
if (line.charAt(i) != ' ') {
temp.add(line.charAt(i));
}
}
// Count rows.
countRow++;
}
char[][] matrix = new char[countRow][countColumn];
// Add the items in temporary list to matrix.
int count = 0;
for (int i = 0; i < matrix.length ;i++) {
for (int j = 0; j < matrix[i].length ;j++) {
matrix[i][j] = (char) temp.get(count);
count++;
}
}
scan.close();
return matrix;
}

How to randomly insert String numbers into an array-Java

I have this array here that takes strings values this is my Puzzle Board View,
Right now everything works but the array is hard coded and i need the strings to be generated randomly from 0-4.
I have tried to get a random char and put it is as a string but this didn't work. Any tips would be nice.
Random rand = new Random();
char c = (char)(rand.nextInt(5) + '0');
StringBuilder sb = new StringBuilder();
sb.append(c);
String[] debug_board_state = new String[7];
debug_board_state[0] = "0,3,0,0,3,0,2";
debug_board_state[1] = "1,0,2,0,0,1,2";
debug_board_state[2] = "0,2,0,0,0,0,0";
debug_board_state[3] = "0,0,3,0,3,0,4";
debug_board_state[4] = "2,0,0,0,0,1,0";
debug_board_state[5] = "0,1,0,0,1,0,2";
debug_board_state[6] = "2,0,3,0,0,2,0";
UPDATE.
Thanks to user Answer i was able to get the random matrix, although i ran into another problem, I need do more stuff to the matrix so i don't want to print it out. here is the code
static private final int WIDTH_EASY = 7;
protected void InitializeEasy() {
Random rand = new Random();
String[][] debug_board_state = new String[7][7];
for (int row = 0; row < debug_board_state.length; row++) {
for (int column = 0; column < debug_board_state[row].length; column++) {
debug_board_state[row][column] = String.valueOf(rand.nextInt(5));
}
}
for (int row = 0; row < debug_board_state.length; row++) {
for (int column = 0; column < debug_board_state[row].length; column++) {
System.out.print(debug_board_state[row][column] + " ");
}
};
for (int i = 0; i < WIDTH_EASY; ++i) {
StringTokenizer tokenizer = new StringTokenizer (debug_board_state[i][i], ",");
int column = 0;
while(tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
getCurrentState().board_elements[i][column] = new BoardElement();
getCurrentState().board_elements[i][column].max_connecting_bridges = Integer.parseInt(token);
getCurrentState().board_elements[i][column].row = i;
getCurrentState().board_elements[i][column].col = column;
if (getCurrentState().board_elements[i][column].max_connecting_bridges > 0) {
getCurrentState().board_elements[i][column].is_island = true;
}
++column;
}
}
}
The string Tokenizer works with 1d array but not with 2d, i need something that will do the same thing as StringTokenizer and apply it to the matrix. I am getting the following error
java.lang.NullPointerException: Attempt to read from field Island_and_Bridges.Hashi.BoardElement[][] Island_and_Bridges.Hashi.BoardState$State.board_elements on a null object reference
Although I think int[][] is a better idea, here is the String[][] solution. You can use String.valueOf(rand.nextInt(5)) to generate element in the matrix:
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random rand = new Random();
String[][] matrix = new String[7][7];
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
matrix[row][column] = String.valueOf(rand.nextInt(5));
}
}
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
System.out.print(matrix[row][column] + " ");
}
System.out.println();
}
}
}
Update:
for (int row = 0; row < WIDTH_EASY; ++row) {
for (int column = 0; column < WIDTH_EASY; ++column) {
getCurrentState().board_elements[row][column] = new BoardElement();
getCurrentState().board_elements[row][column].max_connecting_bridges = Integer.parseInt(debug_board_state[row][column]);
getCurrentState().board_elements[row][column].row = row;
getCurrentState().board_elements[row][column].col = column;
if (getCurrentState().board_elements[row][column].max_connecting_bridges > 0) {
getCurrentState().board_elements[row][column].is_island = true;
}
}
}
Something like this?
Pseudo-code:
String[][] debug_board_state = new String[7][7];
for (int x = 0; x < debug_board_state.size(); x++) {
for (int y = 0; y < debug_board_state[x].size(); y++) {
debug_board_state[x][y] = new_random_character();
}
}
0-4 lies from 49 to 52 on the ASCII scale:
Random rand = new Random();
char c = (char)(rand.nextInt(4)+49);
StringBuilder sb = new StringBuilder();
sb.append(c+'0');
Maybe, you want something like this:
public void initBoard() {
Random random = new Random();
String[][] board = new String[7][7];
for (int i=0; i < board.size(); i++) {
for (int j=0; j < board[].size(); j++) {
board[i][j] = String.valueOf(random.nextInt() % 5);
}
}
}
It will initialize your board with random number of String.

Fill a 2d array with text file, comma separated values

Hi i want to fill a 2d array with comma separated values like this
3
1,2,3
4,5,6
7,8,0
first number the size of the array, the next values are the values of the array this is my code at the moment
//readfile
public static void leeArchivo()
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try
{
//read first value which is teh size of the array
size = Integer.parseInt(br.readLine());
System.out.println("size grid" + size);
int[][] tablero = new int[size][size];
//fill the array with the values
for (int i = 0; i < tablero.length; i++)
{
for (int j = 0; j < tablero[i].length; j++ )
{
tablero[i][j] = Integer.parseInt(br.readLine());
}
}
br.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
This method is working fine for me, just another question, this will work if I want to insert another 2d array of the same size next to the other?
public static void leeArchivo()
{
Scanner s = new Scanner(System.in);
size = Integer.parseInt(s.nextLine());
tablero = new int[size][size];
boolean exit = false;
while (!exit) {
for (int i = 0; i < size; i++) {
//quit commas to fill array
String valuesStrArr[] = s.nextLine().split(",");
for (int j = 0; j < size; j++) {
tablero[i][j] = Integer.parseInt(valuesStrArr[j]);
}
if (i == size - 1)
exit = true;
}
}
}
Example:
3
1,2,3
4,5,6
7,8,0
1,2,3
8,0,4
7,6,5
Solution using Scanner
Scanner s = new Scanner(System.in);
int size = Integer.parseInt(s.nextLine());
int[][] tablero = new int[size][size];
boolean exit = false;
while (!exit) {
for (int i = 0; i < size; i++) {
String valuesStrArr[] = s.nextLine().split(",");
for (int j = 0; j < size; j++) {
tablero[i][j] = Integer.parseInt(valuesStrArr[j]);
}
if (i == size - 1)
exit = true;
}
}
Scanner in = new Scanner(System.in);
int num = in.nextInt();
Use Scanner. Replace System.in with File.
First, you have to separate the elements.
You can do this using the String method split (https://www.javatpoint.com/java-string-split)
//fill the array with the values
for (int i = 0; i < tablero.length; i++)
{
String[] elements = br.readLine().split(",");
for (int j = 0; j < tablero[i].length; j++ )
{
tablero[i][j] = Integer.parseInt(elements[j]);
}
}
br.close();
Or you can use Scanner method, nextInt.
Regarding perfomance, the first option is better.

Categories

Resources