I am trying to convert a string to a matrix of 4x4 size. The matrix should contain the elements same as that of the string.
For eg.
String="1234567890111213141516";
I need to convert this to a 4x4 matrix in java.
a[0][0]=1;
a[0][1]=2;
and so on.
Can anyone suggest me the code for the same?
For reading a String s = "1234567890abcdefghij", you can add below code snippet :
char[][] a = new char[4][4];
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
a[i][j] = s.charAt(4 * i + j);
}
}
this will help you. This will work for only one digit character only.
Here is a hint:
a[i][j] = Integer.valueOf(str.charAt(4 * i + j));
Figuring out how to use this to populate the entire matrix is left as an exercise for the reader.
P.S. This will work for a 16-character abcdefghijklmnop string as in your title; if the string is longer, as in the question, there is no unambiguous way to parse it into a 4x4 matrix.
P.P.S. If all you need to do is set the elements to the consecutive numbers from 1 to 16, you don't need the string at all.
Indeed your question is an easy one, so I answer your question with some additional points that I think help you more than the answer itself:
First, this is the code:
int N = 4;
String delim = ",";
String s = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16";
String[] c = s.split(delim);
int[][] mat = new int[4][4];
int l = 0;
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++,l++)
mat[i][j] = Integer.valueOf(c[l]);
Notes:
Please
1 - don't a simple problem a real hard one!
if it's a hw you can convince the tutor about defining the string delimited with something like "," (if he/she insists) or whatever, and if this is a real project convince the customer, you don't want to torture yourself!
String s = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16";
2 - you said you want to split the string into a 4 x 4 matrix, what if you want a 5x5 matrix? So take advantage of constants, and the same for the delimiter
int N = 4;
String delim = ",";
Hope these help.
You should run two for loops through your string and fill up the matrix.
(This can be done with one array too, but let's keep it simple.)
String str ="1234567890111213141516";
final int rowSize = 4;
final int columnSize = 4;
String[][] a = new String[rowSize][columnSize];
// iterate
for (int row = 0; row < rowSize; row++) {
for (int column = 0; column < columnSize; column++) {
a[row][column] = String.valueOf(str.charAt(rowSize * row + column));
}
}
// test
for (int row = 0; row < rowSize; row++) {
for (int column = 0; column < columnSize; column++) {
System.out.print(a[row][column] + " ");
}
System.out.println();
}
Related
I am having trouble creating multiple arrays with a loop in Java. What I am trying to do is create a set of arrays, so that each following array has 3 more numbers in it, and all numbers are consecutive. Just to clarify, what I need to get is a set of, let's say 30 arrays, so that it looks like this:
[1,2,3]
[4,5,6,7,8,9]
[10,11,12,13,14,15,16,17,18]
[19,20,21,22,23,24,25,26,27,28,29,30]
....
And so on. Any help much appreciated!
Do you need something like this?
int size = 3;
int values = 1;
for (int i = 0; i < size; i = i + 3) {
int[] arr = new int[size];
for (int j = 0; j < size; j++) {
arr[j] = values;
values++;
}
size += 3;
int count = 0;
for (int j : arr) { // for display
++count;
System.out.print(j);
if (count != arr.length) {
System.out.print(" , ");
}
}
System.out.println();
if (i > 6) { // to put an end to endless creation of arrays
break;
}
}
To do this, you need to keep track of three things: (1) how many arrays you've already created (so you can stop at 30); (2) what length of array you're on (so you can create the next array with the right length); and (3) what integer-value you're up to (so you can populate the next array with the right values).
Here's one way:
private Set<int[]> createArrays() {
final Set<int[]> arrays = new HashSet<int[]>();
int arrayLength = 3;
int value = 1;
for (int arrayNum = 0; arrayNum < 30; ++arrayNum) {
final int[] array = new int[arrayLength];
for (int j = 0; j < array.length; ++j) {
array[j] = value;
++value;
}
arrays.add(array);
arrayLength += 3;
}
return arrays;
}
I don't think that you can "create" arrays in java, but you can create an array of arrays, so the output will look something like this:
[[1,2,3],[4,5,6,7,8,9],[10,11,12,13...]...]
you can do this very succinctly by using two for-loops
Quick Answer
==================
int arrays[][] = new int[30][];
for (int j = 0; j < 30; j++){
for (int i = 0; i < (j++)*3; i++){
arrays[j][i] = (i++)+j*3;
}
}
the first for-loop tells us, via the variable j, which array we are currently adding items to. The second for-loop tells us which item we are adding, and adds the correct item to that position.
All you have to remember is that j++ means j + 1.
Now, the super long-winded explanation:
I've used some simple (well, I say simple, but...) maths to generate the correct item each time:
[1,2,3]
here, j is 0, and we see that the first item is one. At the first item, i is also equal to 0, so we can say that, here, each item is equal to i + 1, or i++.
However, in the next array,
[4,5,6,7,8,9]
each item is not equal to i++, because i has been reset to 0. However, j=1, so we can use this to our advantage to generate the correct elements this time: each item is equal to (i++)+j*3.
Does this rule hold up?
Well, we can look at the next one, where j is 2:
[10,11,12,13,14...]
i = 0, j = 2 and 10 = (0+1)+2*3, so it still follows our rule.
That's how I was able to generate each element correctly.
tl;dr
int arrays[][] = new int[30][];
for (int j = 0; j < 30; j++){
for (int i = 0; i < (j++)*3; i++){
arrays[j][i] = (i++)+j*3;
}
}
It works.
You have to use a double for loop. First loop will iterate for your arrays, second for their contents.
Sor the first for has to iterate from 0 to 30. The second one is a little less easy to write. You have to remember where you last stop and how many items you had in the last one. At the end, it will look like that:
int base = 1;
int size = 3;
int arrays[][] = new int[30][];
for(int i = 0; i < 30; i++) {
arrays[i] = new int[size];
for(int j = 0; j < size; j++) {
arrays[i][j] = base;
base++;
}
size += 3;
}
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
Here is my string
100000000000000000000000000000000000000000000000000000000000
a string combined with 60 1/0.
I want to put it into a int Array[6][10].
I tried to add "," between each row, but it failed
String data = "1000000000,0000000000,0000000000,0000000000,0000000000,0000000000";
String[] rows = data.split(",");
String[][] matrix = new String[rows.length][];
int r = 0;
for (String row : rows) {
matrix[r++] = row.split("\\|");
}
System.out.print(matrix);
Please help and solve this problem, thank you!
Here's a very straightforward solution that does not require splitting on regex or inserting commas:
String input = "100000000000000000000000000000000000000000000000000000000000";
int[][] matrix = new int[6][10];
for (int i = 0; i < 6; i++)
for (int j = 0; j < 10; j++)
matrix[i][j] = Integer.parseInt(input.charAt(i * 10 + j) + "");
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:
I have problem with conversion from String into two dimension int array.
Let's say I have:
String x = "1,2,3;4,5,6;7,8,9"
(In my program it will be String from text area.) and I want to create array n x n
int[3][3] y = {{1,2,3},{4,5,6},{7,8,9}}
(Necessary for next stages.) I try to split the string and create 1 dimensional array, but I don't have any good idea what to do next.
As you suggest I try split at first using ; then , but my solution isn’t great. It works only when there will be 3 x 3 table. How to create a loop making String arrays?
public int[][] RunMSTFromTextFile(JTextArea ta)
{
String p = ta.getText();
String[] tp = p.split(";");
String tpA[] = tp[0].split(",");
String tpB[] = tp[1].split(",");
String tpC[] = tp[2].split(",");
String tpD[][] = {tpA, tpB, tpC};
int matrix[][] = new int[tpD.length][tpD.length];
for(int i=0;i<tpD.length;i++)
{
for(int j=0;j<tpD.length;j++)
{
matrix[i][j] = Integer.parseInt(tpD[i][j]);
}
}
return matrix;
}
After using split, take a look at Integer.parseInt() to get the numbers out.
String lines[] = input.split(";");
int width = lines.length;
String cells[] = lines[0].split(",");
int height = cells.length;
int output[][] = new int[width][height];
for (int i=0; i<width; i++) {
String cells[] = lines[i].split(",");
for(int j=0; j<height; j++) {
output[i][j] = Integer.parseInt(cells[j]);
}
}
Then you need to decide what to do with NumberFormatExceptions
Split by ; to get rows.
Loop them, incrementing a counter (e.g. x)
Split by , to get values of each row.
Loop those values, incrementing a counter (e.g. y)
Parse each value (e.g. using one of the parseInt methods of Integer) and add it to the x,y of the array.
If you have already created an int[9] and want to split it into int[3][3]:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
toArray[i][j] = fromArray[(3*i) + j);
}
}
Now, if the 2-dimensional array is not rectangular, i.e. the size of inner array is not same for all outer arrays, then you need more work. You would do best to use a Scanner and switch between nextString and next. The biggest challenge will be that you will not know the number of elements (columns) in each row until you reach the row-terminating semi-colon
A solution using 2 splits:
String input = "1,2,3;4,5,6;7,8,9";
String[] x = input.split(";");
String[][] result = new String[x.length][];
for (int i = 0; i<x.length; i++) {
result[i] = x[i].split(",");
}
This give a 2 dimension array of strings you will need to parse those ints afterwards, it depends on the use you want for those numbers. The following solution shows how to parse them as you build the result:
String input = "1,2,3;4,5,6;7,8,9";
String[] x = input.split(";");
int[][] result = new int[x.length][];
for (int i = 0; i < x.length; i++) {
String[] row = x[i].split(",");
result[i] = new int[row.length];
for(int j=0; j < row.length; j++) {
result[i][j] = Integer.parseInt(row[j]);
}
}
Super simple method!!!
package ADVANCED;
import java.util.Arrays;
import java.util.Scanner;
public class p9 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
String x=sc.nextLine();
String[] array = x.split(",");
int length_x=array.length;
int[][] two=new int[length_x/2][2];
for (int i = 0; i <= length_x-1; i=i+2) {
two[i/2][0] = Integer.parseInt(array[i]);
}
for (int i = 1; i <= length_x-1; i=i+2) {
two[i/2][1] = Integer.parseInt(array[i]);
}
}
}