how to get specific column in 2D array using java - 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

Related

Copy coordinates of one 2D array to another array

I have a 2D array freeSpace[][] that represents x, y coordinates. If the space is "not free" then I have it marked as 77, other 1.
I want to put all the elements marked as 77 into it's own array, with those particular array coordinates. I think it should be simple, but I just can't get the syntax correct.
Here is my code:
for (int v = 0; v < info.getScene().getHeight(); v++) {
for (int h = 0; h < info.getScene().getWidth(); h++) {
//System.out.print(freeSpace[h][v] != 77 ? "." : "#");
if (freeSpace[h][v] == 77) {
blockedCoordinates = new int[][]{{h, v}};
}
}
System.out.println();
}
I have already declared the blockedCoordinates[][] array.
Most of my attempts have lead to an empty array.
You are doing some error while copying your data, here is why:
// assuming following definition
int[][] blockedCoordinate = new int[][]{};
for (int v = 0; v < info.getScene().getHeight(); v++) {
for (int h = 0; h < info.getScene().getWidth(); h++) {
//System.out.print(freeSpace[h][v] != 77 ? "." : "#");
if (freeSpace[h][v] == 77) {
// Make a copy
int[][] copyBlockedCoordinate = blockedCoordinates;
// extend the array length by 1
blockedCoordinates = new int[copyBlockedCoordinate.length + 1][2];
for (int i = 0; i < copyBlockedCoordinate.length; i++) {
for (int j = 0; j < copyBlockedCoordinate[i].length; j++) {
blockedCoordiante[i][j] = copyBlockedCoordinate[i][j];
}
}
// add new array at new or last index position in blockedCoordinate array
blockedCoordinate[copyBlockedCoordinate.length] = {h, v};
}
}
// Make sure you write what you want to the console here to debug :)
System.out.println();
}

Adding 2 differently sized 2d arrays together

I am trying to add two differently sized matrices together. For example, the resultant matrix should be matOne[0][0]+matTwo[0][0]; however, I am having trouble taking into account their different sizes (if there's a missing value, it should be assumed it's a 0).
Here's my code:
int[][] go(int[][] matOne, int[][] matTwo)
{
int size= Math.max(matOne.length, matTwo.length);
int[][] matThree= new int [size][];
int c;
for (int i=0; i<size; i++) {
c= Math.max(matOne[i].length, matTwo[i].length);
for (int j = 0; j < c; j++) {
if (matOne[j].length > i) {
matThree[i][j] += matOne[i][j];
}
if (matTwo[j].length > i) {
matThree[i][j] += matTwo[i][j];
}
}
}
return matOne;
}
I see the following bugs in the code:
You never allocate the inner arrays. After you get size, you correctly create the outer array. After you get c, you forget to create the inner array for that row.
Right inside the i loop, one of matOne[i] and matTwo[i] is likely to fail eventually, whichever one is shorter.
Variable i iterates over rows, and variable j iterates over columns in a row, which means that the [i][j] in the += statements are correct, but that the matOne[j].length > i should have been matOne[i].length > j. Same for matTwo.
You return the wrong array.
Here is the fixed code, using better variable names:
static int[][] go(int[][] matOne, int[][] matTwo) {
int rows = Math.max(matOne.length, matTwo.length);
int[][] matThree = new int [rows][];
for (int r = 0; r < rows; r++) {
int cells = Math.max((matOne.length > r ? matOne[r].length : 0),
(matTwo.length > r ? matTwo[r].length : 0));
matThree[r] = new int[cells];
for (int c = 0; c < cells; c++) {
if (matOne.length > r && matOne[r].length > c) {
matThree[r][c] += matOne[r][c];
}
if (matTwo.length > r && matTwo[r].length > c) {
matThree[r][c] += matTwo[r][c];
}
}
}
return matThree;
}
Test
public static void main(String[] args) {
int[][] matOne = { { 1, 2, 3 }, { 4, 5, 6 } };
int[][] matTwo = { { 7, 8 }, { 9, 10 }, { 11, 12 } };
int[][] matThree = go(matOne, matTwo);
print(matOne);
System.out.println("+");
print(matTwo);
System.out.println("=");
print(matThree);
}
static void print(int[][] mat) {
for (int[] row : mat) {
for (int cell : row)
System.out.printf(" %2d", cell);
System.out.println();
}
}
Output
1 2 3
4 5 6
+
7 8
9 10
11 12
=
8 10 3
13 15 6
11 12
If you don't want the result to be a jagged array, i.e. you want the result to be a 2D rectangular matrix, change the code as follows:
static int[][] go(int[][] matOne, int[][] matTwo) {
int rows = Math.max(matOne.length, matTwo.length);
int cols = 0;
for (int[] row : matOne)
cols = Math.max(cols, row.length);
for (int[] row : matTwo)
cols = Math.max(cols, row.length);
int[][] matThree = new int [rows][cols];
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (matOne.length > r && matOne[r].length > c) {
matThree[r][c] += matOne[r][c];
}
if (matTwo.length > r && matTwo[r].length > c) {
matThree[r][c] += matTwo[r][c];
}
}
}
return matThree;
}
Output
1 2 3
4 5 6
+
7 8
9 10
11 12
=
8 10 3
13 15 6
11 12 0
Just before the inner loop; replace current calculation of 'c' and allocate a row for matThree.
c = 0;
if (i < matOne.length)
c = matOne[i].length;
if (i < matTwo.length && matTwo[i].length > c)
c = matTwo[i].length;
matThree[i] = new int[c];
The code inside the inner loop should be:
int elem1 = 0, elem2 = 0;
if (i < matOne.length && j < matOne[i].length)
elem1 = matOne[i][j];
if (i < matTwo.length && j < matTwo[i].length)
elem2 = matTwo[i][j];
matThree[i][j] = elem1 + elem2;
Firstly, it's necessary to allocate storage for the current row of matThree.
Secondly, you need to check that both row and column are within bounds for each matrix. For my taste it's clearest to explicitly extract the values, defaulting to zero, thus the variables elem1 and elem2.

How to print every third element of Array?

I need to take 2 inputs from user size of array and then elements of that same array.
I need to print every third element of array.
Example Array: 1,2,3,4,5,6,7,8,9
Desired output: 3,6,9
Getting: 9,6,3
class Demo {
public static void main(String[] args) {
int x;
int[] y;
Scanner tastatura = new Scanner(System.in);
System.out.println("Enter size of array:");
x = tastatura.nextInt();
y = new int[x];
System.out.println("Enter the elements of array:");
for (int i = 0; i < x; i++) {
y[i] = tastatura.nextInt();
}
System.out.println("\n Every third element of array is : ");
for (int i = y.length - 1; i >= 0; i = i - 3) {
System.out.println(y[i]);
}
tastatura.close();
}
You were close! You just have the iteration order reversed!
for (int i = y.length - 1; i >= 0; i = i - 3) {
System.out.println(y[i]);
}
Should be:
for (int i = 2; i < y.length; i += 3) {
System.out.println(y[i]);
}
Take note that this can throw an ArrayIndexOutOfBoundsException if your array does not contain at least 3 elements, so you should handle that somewhere.
use the modulus operator to find each 3rd item.
example
0 % 3 = 0
1 % 3 = 1
2 % 3 = 2
3 % 3 = 0
for (int i =0 ; i < y.length - 1; i = i + 3) {
System.out.println(y[i]);
}
The way you are printing is in reverse order .. Correct that
You are on the right track I would strongly recommend using a modulus:
for (int i = 0; i < y.length; i++) {
if(i%3==0){
System.out.println(y[i]);
}//if statement
}//for loop

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]);

Retrieving second and third column from a 2d array to an array

I have a Java code that will output 3 column of double integer just like this (1 column, 2 column, 3 column):
( 0.09, 0.27, 0.01)
( 0.00, -0.00, 0.26)
( 0.02, -0.02, 0.24)
( 0.22, -0.11, -0.03)
Now, I wish to store all the values from the second column into an array and the values from the third column into another array. Is there a way I could modify it so that it will achieve that?
This is my partial code:
for (int i = 0; i < termVectors.length; ++i) {
System.out.print("(");
for (int k = 0; k < 3; ++k) {
if (k > 0) System.out.print(", ");
System.out.printf("% 5.2f",termVectors[i][k]);
}
System.out.print(") ");
}
Thanks!
Please try the following code.
int[] secondColVal = new int[termVectors.length];
int[] thirdColVal = new int[termVectors.length];
for (int i = 0; i < termVectors.length; ++i) {
System.out.print("(");
for (int k = 0; k < 3; ++k) {
if (k > 0) System.out.print(", ");
System.out.printf("% 5.2f",termVectors[i][k]);
if(k==1)
secondColVal[i] = termVectors[i][k];
if(k==2)
thirdColVal[i] = termVectors[i][k];
}
System.out.print(") ");
}
This should give you what you need :)
// since you're using the length multiple times, store it in a variable!
int len = termVectors.length;
// declare two arrays to represent your second and third columns
int[] secondColumn = new int[len];
int[] thirdColumn = new int[len];
for (int i=0;i<len;i++)
{
// populate your arrays
secondColumn[i] = termVectors[i][1];
thirdColumn[i] = termVectors[i][2];
}

Categories

Resources