Appending a string into 2d Array Java - 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]);

Related

How to declare and fullfill three-dimentional array of arrays?

I need help completing one task from Java book that I read. I need to create a 3-dimentional array of int that will be able to store 30 values.
It's described as cuboid containing cubes. Each cube is supposed to be a cell and they should store ints from 30 to 59. How should it look like? I try to draw it but it's pretty hard for me. Here is what I've tried.
public class cw124{
public static void main (String[]args){
int tab[][][]=new int[31][30][30];
int wypelniacz=30;
for (int i=0; i<tab.length; i++){
for (int j=0; j<tab[j].length; j++){
wypelniacz=30;
for (int k=0; k<tab[k].length; k++){
tab[i][j][k]=wypelniacz++;
}
}
}
for (int i=0; i<tab.length; i++) {
for (int j=0; j<tab[j].length; j++){
for (int k=0; k<tab[k].length; k++){
wypelniacz=30;
tab[i][j][k]=wypelniacz++;
System.out.println("Row "+i+" Cell 1 "+j+" Cell 2 "+k+" "+tab[i][j][k]);
}
}
}
}
}
Your 3D array currently has 31*30*30 = 27,900 cells. If you need a 3D array with 30 cells, you can do this:
int tab[][][]=new int[5][3][2];
This will give you a 3D array with 5*3*2 = 30 cells.
You can imagine each value in square brackets to be the length of one side of the cuboid.
The next step would be:
int counter = 30;
for(int i = 0; i < tab.length; i++)
{
for(int j = 0; j < tab[0].length; j++)
{
for(int k = 0; k < tab[0][0].length; k++)
{
tab[i][j][k] = counter;
counter++;
}
}
}
This will populate all the cells with numbers from 30 to 59.
I think the following code may help you understand the task.
You have to think of the 3 dimensions as a cube, the cube contains grids, each grid has rows which then have multiple columns)
(imagine a Rubik's cube, which has 3 layers=grids, each grid then has 3 rows and each of those rows again has 3 columns)
final int gridCount = 5;
final int rowCount = 5;
final int colsPerRow = 15;
final int[][][] cube = new int[gridCount][rowCount][colsPerRow];
for (final int[][] grid : cube) {
for (int col = 0; col < grid.length; col++) { //just to show the two different versions of 'for'
final int[] row = grid[col];
row[col] = 42+ col; //set it to whatever number
}
}

Ignore index of a letter if I use it

I'm working on key columnar transposition cipher,
for(int i = 0; i < column; i++){
position = keyWord.indexOf(sorted_key[i]); // Here's the problem
for(int j = 0; j < row; j++){
matrix[j][position] = cipher_array[count];
count++; }}
Keyword is:
analyst
sorted_key is:
{a, a, l, n, s, t, y}
When I tried to print the variable position:
0 0 3 1 5 6 4
But I'm supposed to get this:
0 2 3 1 5 6 4
The problem occurs when I have a duplicated letter in the key. 'a' in this example, it always sees the first index of it's occurrence even if there's a second or third occurrence of it. How could this be fixed?
You can maintain a Map that holds the last index for each character:
Map<Character,Integer> indices = new HashMap<>();
for(int i = 0; i < column; i++) {
// get the previous position of sorted_key[i] (or -1 is there is no previous position)
int last = indices.computeIfAbsent(sorted_key[i],c->-1);
// search for the next position of sorted_key[i]
position = keyWord.indexOf(sorted_key[i],last+1);
// store the next position in the map
indices.put(sorted_key[i],position);
for(int j = 0; j < row; j++) {
matrix[j][position] = cipher_array[count];
count++;
}
}

how to get specific column in 2D array using java

when searched value exist in array, I choose the column and save them.
for example
1 2 3 4 5 6
A B C D E F
G H I J K L
I want to make a column including x==1||x==4
below column will be result of what i want
1 4
A D
G J
below code is my 2D array code. I make 1D array from csv file and 2D array. when searched value exist, I choose the column and save them.
String str = readCSV(new File("D:/sample_folder/sample1.csv"));
String[] strArr = parse(str); // It comes out in a row in an String array.
int varNumber = 45;
int rowNumber = strArr.length/varNumber;
String[][] Array2D = new String[varNumber][rowNumber];
for(int j=0;j<varNumber;j++)
{
for(int i=0; i<rowNumber;i++)
{
String k = strArr[i*varNumber+j];
Array2D[j][i]= k;
}
} //make 2D array
You can through rows of 2D array and pick the column you want.
for(int j=0;j<rowNumber;j++)
{
// index starts from 0
yourArray[j][0] = array2D[j][0];
yourArray[j][1] = array2D[j][3];
}
Or more dynamically you could write:
int[] columnsYouWant = {0, 3};
for(int j=0;j<rowNumber;j++)
{
for(int c=0;c<columnsYouWant.length;c++)
{
yourArray[j][c] = array2D[j][columnsYouWant[c]];
}
}
If you want to use if (x == 1 || x == 4) :
for(int j=0;j<rowNumber;j++)
{
column = 0;
for(int c=0;c<columnNumber;c++)
{
x = c + 1;
if (x == 1 || x == 4)
yourArray[j][column++] = array2D[j][c];
}
}
I might get it wrong. It also seems you may want to have columns starting with 1 or 4. In that case, if your first row has numbers and rest are alphabetical. You should find the column starting with either 1 or 4.
for(int j=0;j<colNumber;j++)
{
x = array2d[0][j];
if ( x == 1 || x == 4 ) {
// add you j to an array
}
}
In the case you will know which columns you want, and you can use the second piece of code in my answer to create 2D array with columns you want.
Try this simulation, I populate this in your 2DArray:
1 2 3 4 5 6
A B C D E F
G H I J K L
after that, I made a code to print only the columns 1 and 4.
public static void main(String[] args) {
String[][] twoDArray = populateArray();
int x = 0;
for (int i = 0; i < twoDArray.length; i++) {
for (int j = 0; j < twoDArray[0].length; j++) {
x = j + 1;
if(x == 1 || x == 4) {
System.out.print(twoDArray[i][j]);
}
}
System.out.println();
}
}
public static String[][] populateArray() {
String[][] twoDArray = new String[3][6];
for (int i = 0; i < twoDArray[0].length; i++) {
twoDArray[0][i] = (i + 1) + "";
}
char alphaChar = 'A';
for (int i = 1; i < twoDArray.length; i++) {
for (int j = 0; j < twoDArray[0].length; j++) {
twoDArray[i][j] = String.valueOf(alphaChar);
alphaChar++;
}
}
return twoDArray;
}
the output of the code is:
14
AD
GJ
if you comment the if(x == 1 || x == 4) { that I used, it will print like this:
123456
ABCDEF
GHIJKL

Parsing large numbers into binary

I am trying to make a program that finds the maximum possible determinant of an n*n binary [0,1] matrix. The problem with my current code is that after 4x4, the numbers are too long for a 'long' to hold. The code below is what I use to generate the matrices.
for (int j = 0; j < Math.pow(2, Math.pow(dim, 2)); j++) { //for each possible matrix
int[][] matrix = new int[dim][dim];//make a 2d i*i matrix
long t = Long.valueOf(Long.toBinaryString(j)); //line 58
//format the string so its length = # of elements in the matrix
String format = "%0" + (dim * dim) + "d";
String s = String.format(format, t);
//fill matrix
int counter = 0;
for (int k = 0; k < dim; k++) {//for each row
for (int l = 0; l < dim; l++) {//for each column
matrix[k][l] = s.charAt(counter) - 48; //the -48 is for ascii conversions
counter++;
}// end l
}// end k -- matrix is filled
The error I get when I go over a 4*4:
Exception in thread "main" java.lang.NumberFormatException: For input string: "10000000000000000000"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Long.parseLong(Long.java:444)
at java.lang.Long.valueOf(Long.java:540)
at determinants.Determinants.findMaxBinDet(Determinants.java:58)
at determinants.Determinants.main(Determinants.java:38)
What else can I do to parse the number into binary?
It appears you want to create with all the combinations of 0 and 1 in the cells. A much simpler approach is
for (long j = 0, limit = 1<<(dim*dim); j < limit; j++) { //for each possible matrix
int[][] matrix = new int[dim][dim];//make a 2d i*i matrix
//fill matrix
for (int k = 0, counter = 0; k < dim; k++) {//for each row
for (int l = 0; l < dim; l++, counter++) {//for each column
matrix[k][l] = (j >>> counter) & 1;
}
}
This will only work up to 7x7 matrixes but since generating all 8x8 combination is like to take more than a lifetime, you need another approach for that.

Place String into 2 dimensional array

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

Categories

Resources