Place String into 2 dimensional array - java

To put a String into a single array is easy but I want to put a string into a 2d char[][];
I'm stuck here, can some one help me please ... Thank u, ans sorry for my bad English!
String woord = "GPDNATSFASELNIERTPOTSRARIRRCOOFPUAUOGONOTORENOTUAMRHRILGTPOFRSCENOIEKLMETANTRSRUNIAARSETEITNAKAVERNTEJLIBFTNVOTWEEDEKLASC";
char[][] bord = new char[11][11];
char[] letters = woord.toCharArray();
int teller = 0;
//Board into a single array
for (int i = 0; i < woord.length(); i++) {
letters[i] = woord.charAt(i);
teller++;
System.out.print(letters[i]);
if (teller % 11 == 0) {
System.out.println();
}
}
//Board into a 2d Array
for (int r = 0; r < bord.length; r++) {
bord[r][0]=letters[r]; //<=== first 11 letters, next?
System.out.print(bord[r][0]);
for (int c = 0; c < bord[0].length; c++) {
//??
}
}

You can use usual trick applied for multi-dimensional arrays while traversing it. r*11 + a value (according to loops) will give us the next character of string. Below code,
//Board into a 2d Array
for (int r = 0; r < bord.length; r++) {
for(int a = 0; a < 11; a++)
bord[r][a] = letters[r*11 + a];
System.out.println(bord[r]);
}
will give the output:
GPDNATSFASE
LNIERTPOTSR
ARIRRCOOFPU
AUOGONOTORE
NOTUAMRHRIL
GTPOFRSCENO
IEKLMETANTR
SRUNIAARSET
EITNAKAVERN
TEJLIBFTNVO
TWEEDEKLASC

Related

Appending a string into 2d Array Java

I have a string containing the following:
String text = "abcdefghijkl"
I want to put it in a 2d array so there will be 4 rows of 3
this is currently what I have, its not working correctly though:
char boxChar[][] = new char[4][3];
int j,i;
for (i = 0; i<4; i++)
{
for (j=0; j<3; j++)
{
boxChar[i][j] = text.charAt((i+1)*(j));
}
}
return boxChar[row][col];
It looks like you got the indexes mixed up. I added some print statements to your original code with a modification to get the right char in your charAt instruction.
String text = "abcdefghijkl";
char boxChar[][] = new char[4][3];
int j,i;
for (i = 0; i<4; i++)
{
for (j=0; j<3; j++)
{
boxChar[i][j] = text.charAt(i*3+j);
System.out.print(boxChar[i][j]);
}
System.out.println();
}
Sometimes it can be helpful to jot it down on a piece of paper if it's not lining up how you expected.
With your input string, the positions on a 1d array are
a b c d e f g h i j k l
0 1 2 3 4 5 6 7 8 9 10 11
As you loop through to get the box array (matrix), your outer loop indicates that you want four rows and three columns, in other words
a b c
d e f
g h i
j k l
so for the first element, a, its position is (0,0), b is at (0,1) and so on. Your charAt(position) has to map the 2d positions to their corresponding 1d positions.
Just the wrong indexing, otherwise you're good:
String text = "abcdefghijkl";
int rows = 4;
int cols = 3;
char boxChar[][] = new char[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
boxChar[i][j] = text.charAt((i * cols) + j);
}
}
//return boxChar[row][col];
System.out.println(boxChar[0]);
System.out.println(boxChar[1]);
System.out.println(boxChar[2]);
System.out.println(boxChar[3]);

I have a 2D MATRIX of chars, and having trouble searching the matrix Spirally

I start from the left-bottom and proceeding in clockwise direction till no chars are left. here is my code.
import java.io.*;
import java.util.*;
public class Solution {
static int count = 0;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
int n = sc.nextInt();
char[][] matrix = new char[n][m];
char[] temp = new char[n*m];
for(int r=0;r<n;r++){
for(int col=0;col<m;col++){
matrix[r][col] = sc.next().charAt(col);
}
}
int k=0, l = 0;
while(k < n && l < m){
if(l<m){
for(int i = n-1;i>=k;i--){
temp[count] = matrix[i][l];
count++;
}
l++;
}
for(int i = l;i<m;i++){
temp[count] = matrix[k][i];
count++;
}
k++;
for(int i = k;i<n;i++){
temp[count] = matrix[i][m-1];
count++;
}
m--;
if(k < n){
for(int i = m-1;i>=l;i--){
temp[count] = matrix[n-1][i];
}
n--;
}
}
String code = String.valueOf(temp);
String[] dec = code.split("#");
//System.out.println(dec);
int count2 = dec.length;
System.out.println(count2);
}
}
So can anyone point out where I am going wrong? I start at left bottom, climb up, go right , then go down, go left and continue till no elements left.
There are two issues: incorrect input and missing counter increment.
Incorrect input:
for(int r=0;r<n;r++){
for(int col=0;col<m;col++){
// The following reads a new line each time a new character is needed
matrix[r][col] = sc.next().charAt(col);
}
}
This could be fixed either by lifting sc.next() from the inner loop:
for (int r = 0; r < n; r++) {
String line = sc.next();
for (int col = 0; col < m; col++) {
matrix[r][col] = line.charAt(col);
}
}
Or (preferable) removing inner loop completely:
for (int r = 0; r < n; r++) {
matrix[r] = sc.next().toCharArray();
}
Missing increment (lower part of the spiral):
for(int i = m-1;i>=l;i--){
temp[count] = matrix[n-1][i];
// Counter increment is missing. Add
// counter++;
}
In general, is is better to use StringBuilder for gradual construction of the string. In you case it will look as following:
StringBuilder temp = new StringBuilder();
<...>
temp.append(matrix[n-1][i]);
<...>
String code = temp.toString();
In this code you don't have to estimate possible string size nor manually track current insert position.
starting left bottom in the matrix is
matrix[0][m];
going up the hill will be made by decreasing m to a point where you already had a char inserted.
i would use 4 for loops inside a while loop like is presented:
while (usedRow < (int)0.5*n && usedCol < (int)0.5*m)
{
//usedRow and usedCol start with the value of 0 and will be raised
// by the end of the loop
int i, j;
for (i = m - usedCol; i<=(m-usedCol); i++)
{
matrix[usedRow][m-i] = sc.next().charAt(0);
}
for (j = usedRow; j <= (n-usedRow); j++)
{
matrix[n + j][usedCol] = sc.next.charAt(0);
}
for (i = usedCol; i <= (m-usedCol); i++)
{
matrix [n - usedRow][m+i] = sc.next().chatAt(0);
}
for ( j = n - usedRow; j <= (n - usedRow); j++)
{
matrix[n - j][m - usedCol] = sc.next().charAt(0);
}
usedRow++;
usedCol++;
}
this way you go clockwise and keep the loop within the rows and cols that are not in use.
hope that it helped you in a way.

I need to convert an int[][] to a char[][] or create a char[][] of the same dimensions

I have an int[][] that will be initialized by a file so I don't know the size of it. how can I convert it to a 2D char array or create a char[][] of the same size?
Is this along the right lines? how would I do it?
int[][] shade = <a method returns an int[][]>
char[][] converted = new int[shade.length][];
for(int i = 0; i < shade.length; i++) {
converted[i] = new String[shade[i].length];
for(int j = 0; j < shade[i].length; j++){
converted[i][j] = Character.toInt(shade[i][j]);
}
}
you can do that :
String[][] converted = new String[a.length][];
for(int index = 0; index < a.length; index++) {
converted[index] = new String[a[index].length];
for(int subIndex = 0; subIndex < a[index].length; subIndex++){
converted[index][subIndex] = Integer.toString(a[index][subIndex]);
}
}
Firstly, you need to confirm what kind of char do you need .
I guess you need to convert the int into a char representing in ASCII, that means 65 will be cast to 'A' , you can just use typecast, like
int intvalue=65;
char c=(char)intvalue;//will be 'A'
If you want to convert 5 to '5'(But you need to guarantee that intvalue is within [0,9]) ,use
int intvalue=5;
char c= = (char) ('0' + intvalue); // c is now '5';
Here is the way of your case from int to char representing in ASCII:
public static void main(String agrs[]) {
int[][] shade = getIntArray();//here is how you
char[][] converted = new char[shade.length][shade[0].length];//use the shade's row and column length to declare an char[][] array
for (int i = 0; i < shade.length; i++) {
for (int j = 0; j < shade[i].length; j++) {
converted[i][j] = ((char) shade[i][j]);
System.out.println(converted[i][j]);//out put will be 'A'
}
}
}
//here you need to replace it into your own method, now I pretend that I returns a [2][2] array which holds value of 65 ('A')
private static int[][] getIntArray(){
int[][] array=new int[2][2];
for(int i=0;i<array.length;i++)
for(int j=0;j<array[i].length;j++){
array[i][j]=65;
}
return array;
}

String to int array [][] - JAVA

I have a board game define as
boardArray = new int[4][4];
and I have a string in this format:
String s = "[[0,0,2,0],[0,0,2,0],[0,0,0,0],[0,0,0,0]]"
Is there a way to put it in the int array? Consider that it should look like this
[0,0,2,0]
[0,0,2,0]
[0,0,0,0]
[0,0,0,0]
You could simply do the following:
String s = "[[0,0,2,0],[0,0,2,0],[0,0,0,0],[0,0,0,0]]";
String myNums[] = s.split("[^0-9]+");
//Split at every non-digit
int my_array[][] = new int[4][4];
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++) {
my_array[i][j] = Integer.parseInt(myNums[i*4 + j + 1]);
//The 1 accounts for the extra "" at the beginning.
}
}
//Prints the result
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++)
System.out.print(my_array[i][j]);
System.out.println();
}
If you want to to it dynamically, I've written a librray: https://github.com/timaschew/MDAAJ
The nice thing is, that it's really fast, because internally it's a one dimensional array, but provides you same access and much more nice features, checkout the wiki and and tests
MDDA<Integer> array = new MDDA<Integer>(4,4);
or initialize with an existing array, which is one dimensional "template", but will be converted into your dimensions:
Integer[] template = new Integer[] {0,0,2,0, 0,0,2,0, 0,0,0,0, 0,0,0,0};
MDDA<Integer> array = new MDDA<Integer>(template, false, 4,4);
//instead of array[1][2];
array.get(1,2); // 2

Java: Storing values in 2D Array

I have a problem with storing values in a multidimensional array. The main concept of the idea is that I have an arraylist which is called user_decide and I transform it in a array. So, the decide array looks like [1, 45, 656, 8, 97, 897], but all the rows don't have the same number of elements. Then, I split this replace [,] and spaces and I would like to store each value individually in a 2D array. So, I split it with the "," and try to store each value in a different position. Everything seems to be printed great, even the cut[j] is what I want to store, but I get a java.lang.NullPointerException, which I don't get. The count variable is actually the count = user_decide.size()
String [] decide = user_decide.toArray(new String[user_decide.size()]);
for (int i = 0; i < count; i ++){
decide[i] =
decide[i].replaceAll("\\s", "").replaceAll("\\[","").replaceAll("\\]", "");
}
String [][] data1 = new String[count][];
for (int i = 0; i < count; i++){
String [] cut = decide[i].split("\\,");
for (int j = 0; j < cut.length; j++){
System.out.println(cut[j]);
data1[i][j] = cut[j];
}
}
Another question is why I cannot store it in a Int [][] array? Is there a way to do that?
Thank you a lot.
** EDIT **
I just made an edit about my answer after I accepted the question. I am trying to store it in a 2D int array.
String [][] data1 = new String[user_decide.size()][];
int [][] data = new int [user_decide.size()][];
for (int i = 0; i < user_decide.size(); i++){
data1[i] = decide[i].split("\\,");
for (int j = 0; j < data1[i].length; j++) {
data[i] = new int [data1[i].length];
data[i][j] = Integer.parseInt(data1[i][j]);
System.out.println(data1[i][j]);
}
}
Ivaylo Strandjev's answer shows the reason for your problem. But there's a much simpler solution:
String [][] data1 = new String[count][];
for (int i = 0; i < count; i++){
data1[i] = decide[i].split("\\,");
System.out.println(Arrays.toString(data1[i]));
}
Also, you don't need to escape the comma.
EDIT
Saw your edit. There is a big mistake, see my comment in your code:
String [][] data1 = new String[user_decide.size()][];
int [][] data = new int [user_decide.size()][];
for (int i = 0; i < user_decide.size(); i++){
data1[i] = decide[i].split("\\,");
for (int j = 0; j < data1[i].length; j++) {
data[i] = new int [data1[i].length]; // This line has to be prior to the
// inner loop, or else you'll overwrite everything but the last number.
data[i][j] = Integer.parseInt(data1[i][j]);
System.out.println(data1[i][j]);
}
}
If all you want is the int[], this is what I would do:
int [][] data = new int [user_decide.size()][];
for (int i = 0; i < user_decide.size(); i++){
String[] temp = decide[i].split(",");
data[i] = new int [temp.length];
for (int j = 0; j < temp.length; j++){
data[i][j] = Integer.parseInt(temp[j]);
System.out.println(data1[i][j]);
}
}
There are probably nicer ways, but I don't know why you are using user_decide.size() ( a Collection) for the condition and decide[i] (an array) within the loop. There's no good reason I can think of mixing this, as it could lead to errors.
In java you will need to also allocate data[i], before copying contents:
for (int i = 0; i < count; i++){
data1[i] = new String[cut.length];
String [] cut = decide[i].split("\\,");
for (int j = 0; j < cut.length; j++){
System.out.println(cut[j]);
data1[i][j] = cut[j];
}
}
Before copying contents:

Categories

Resources