Deleting elements from multi Dimensional Array - java

I have a 2-dimensional array in java.
For example,
double count=0;
double[][] arr1 =new double[3][3];
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
arr1[i][j]=count;
count++;
}
}
Now, I want to remove all elements where i or j value was 1.
arr1[1][0], arr1[1][1], arr1[1][2], arr[0][1], arr[2][1] ...
How can I achieve this?

Copies into arr2.
If you had
[1][2][3]
[4][5][6]
[7][8][9]
You'd get
[1][3]
[7][9]
If you wanted
[1][-][3]
[-][-][-]
[7][-][9]
See shijima's answer
double[][] arr2 = new double[arr1.length][arr1[0].length];
int ti = 0, tj = 0;
for(int i=0; i<arr1.length - 1; i++) {
if (i > 0)
ti = i+1;
else
ti = i;
for(int j=0; j<arr1[0].length - 1; j++) {
if (j > 0)
tj = j+1;
else
tj = j;
arr2[i][j] = arr1[ti][tj];
}
}

for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
if(i==1 || j==1){
arr1[i][j]=0;
}
}
}
or with much better efficiency :
for(int i=0;i<3;i++){
arr1[i][1]=0;
}
for(int i=0;i<3;i++){
arr1[1][i]=0;
}

ArrayList would make your life a lot easier since you could just call remove(int), but if you insist on arrays you could do this.
double[] tmp = arr1[0];
arr1 = Arrays.copyOfRange(arr1, 1, arr1.length);
arr1[0] = tmp;

You could just avoid adding anything if i = 1, that way you don't need to worry about removing anything, since it will be empty later anyway...
double count = 0;
double[][] arr1 = new double[3][3];
outerLoop: for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i == 1) {
continue outerLoop;
}
arr1[i][j] = count;
count++;
}
}
for (int x = 0; x < 3; x++) {
for (int y = 0; y < 3; y++) {
System.out.println("arr1[" + x + "][" + y + "]=" + arr1[x][y]);
}
}

Related

JAVA Inversion of multidimensional arrays [duplicate]

I'm trying to invert and flip a two-dimensional array, but something goes wrong! Flipping works ok, but inverting is not.
Can't find a mistake right here:
public int[][] flipAndInvert(int[][] A) {
int row = -1;
int col = -1;
int[][] arr = A;
for (int i = 0; i < arr.length; i++) {
row++;
col = -1;
for (int j = arr[i].length - 1; j >= 0; j--) {
col++;
arr[row][col] = A[i][j];
}
}
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] == 1) {
arr[i][j] = 0;
} else {
arr[i][j] = 1;
}
}
}
return arr;
}
int[][] A = { { 0, 1, 1 },{ 0, 0, 1 },{ 0, 0, 0 } };
After proceeding the output should be:
After inverting:
{1,1,0},{1,0,0},{0,0,0}
After flipping:
{0,0,1,},{0,1,1},{1,1,1}
Thanks to all a lot, the problem was here:
int[][] arr = A;
The reference of the array is being passed to arr.
What I think is that since you are using this line:
int[][] arr = A;
The reference of the array is being passed to arr, and hence the line:
arr[row][col] = A[i][j];
is equivalent to:
A[row][col] = A[i][j];
as arr has an reference to A and they both now refer to the same memory location (or they are both different names to a single variable)
You can fix this by either using the new keyword with arr and then initializing it:
int[][] arr = new int[someRows][someCols];
//use for loop to assign the value to each element of arr
Or you can run the for loop till arr[i].length/2 - 1:
for (int i = 0; i < arr.length; i++) {
row++;
col = -1;
for (int j = arr[i].length / 2 - 1; j >= 0; j--) { //here changed arr[i].length to arr[i].length / 2
col++;
arr[row][col] = A[i][j]; //for this you do not need arr and you can directly work on A and return it
}
}
The problem of your code should be this line:
int[][] arr = A;
You are assigning the reference of array A to arr and from then when you modify one you modify both of the arrays or better they are modified together because they refer to the same address.
Using apache commons lang:
int[][] matrix = new int[3][3];
for (int i = 0; i < matrix.length; i++) {
matrix[i][0] = 3 * i;
matrix[i][1] = 3 * i + 1;
matrix[i][2] = 3 * i + 2;
}
System.out.println(Arrays.toString(matrix[0]));
System.out.println(Arrays.toString(matrix[1]));
System.out.println(Arrays.toString(matrix[2]));
ArrayUtils.reverse(matrix);
System.out.println(Arrays.toString(matrix[0]));
System.out.println(Arrays.toString(matrix[1]));
System.out.println(Arrays.toString(matrix[2]));
Hope this helps.

How can I merge 2 arrays in 1 loop?

I was told to make
void mergeArrays(int[] ar1 , int[] ar2)
For an input like this:
int[] ar1 = {1,2,3,4}
int[] ar2 = {5,6,7,8}
This is my code :
public static void mergeArray(int[] ar1 , int[] ar2) {
int[] res = new int[ar1.length+ar2.length];
int counter = 0;
for(int a = 0; a<ar1.length; a++)
{
res[a] = ar1[a];
counter++;
}
for(int b = 0; b<ar2.length; b++)
{
res[counter++] = ar2[b];
}
for(int temp = 0; temp<res.length;temp++)
{
System.out.print(res[temp]+" ");
}
Output 12345678.
This is done using 2 loops. Now, how can I do it using a single loop?
Yes, you can do it in one loop,
int len = arr1.length + arr2.length;
int[] res = new int[len];
for(int i=0, j=0; i<len; i++) {
if(i<arr1.length){
res[i] = arr1[i];
}else{
res[i] = arr2[j];
j++;
}
}
This will work also, when both arrays are of different length.
Different length arrays
int[] result = new int[ar1.length + ar2.length];
for(int i = 0; i < result.length; i++) {
result[i] = i < ar1.length ? ar1[i] : ar2[i - ar1.length]; // comparison
}
Equal length arrays
int[] result = new int[ar1.length + ar2.length];
for(int i = 0; i < ar1.length; i++) {
result[i] = ar1[i]; // no
result[ar1.length + i] = ar2[i]; // comparison
}
See (and execute) the full implementation here.

Sum the elements of 2D array

I made 2D arrray which prints some random elements.
Now i need a method which calculates the sum of that elements but just elements below the main diagonal.
Here is my code...
class Init {
public static void main(String[] args) {
int n = 0;
int m = 0;
int aray[][];
Random random = new Random();
Scanner tastatura = new Scanner(System.in);
int[][] array = new int[n][m];
n = tastatura.nextInt();
m = tastatura.nextInt();
array = new int[n][m];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
array[i][j] = random.nextInt(20);
}
}
for (int[] a : array) {
System.out.println(Arrays.toString(a));
}
}
}
I did it like this... Now i can sum, but when i try to multyply same numbers i am geting 0 Why is that?
Scanner scanner = new Scanner(System.in);
System.out.print("Unesite duzinu kolona i redova : ");
int rows = scanner.nextInt();
int columns = rows;
int[][] matrix = new int[rows][rows];
Random random = new Random();
System.out.println("Nasumicni/random brojevi su :");
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = random.nextInt(20);
}
}
for (int[] a : matrix) {
System.out.println(Arrays.toString(a));
}
//here is the logic which sum those elements
int sum = 0;
for (int i = 1; i < rows; i++) {
for (int j = i - 1; j >= 0; j--) {
sum = sum + matrix[i][j];
}
}
System.out.println("\nMatrix is : ");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
System.out.println("Proizvod elemenata ispod glavne dijagonale je: " + sum);
What about this?
int s = 0;
for(int i = 1; i < m; ++i)
for(int j = 0; j < i; ++j)
s += a[i][j];
This selectively loops through the elements below the main diagonal and sums them up, without looping through the entire matrix and making it lengthier.
The main diagonal of a matrix consists of those elements that lie on the diagonal that runs from top left to bottom right. But since you want those elements "below" the main diagonal, here is an algorithm I came up with for that.
int sum = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (i == j && (i + 1 < n))
{
int temp = i + 1;
while (temp < n)
{
sum += arr[temp][j];
temp++;
}
}
Also, you declare int[][] array multiple times. You need to declare it only once, after you get the values for n and m.
for(i=0;i
        for(j=0;j
        {
                if(j>i)
                    d1+=a[i][j];. // Above the diagon
                else
                    if(i>j)
                        d2+=a[i][j];. // Below the diagonal
        }
    

Merging two arrays and short that merged array

I got homework "Take two given array(already sorted up, for example {1,2,3}) and create a new array contains both arrays and then sort him up", we have a function to sort up arrays so it's not the problem, however it gets a little bit complex to me, here is my code:
public static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
int[] a = new int[3];
int[] b = new int[5];
Help_arr.scan(a);
Help_arr.scan(b);
Help_arr.print(peula(a, b));
}
public static int[] peula(int[] a1, int[] b1) {
int[] c = new int[a1.length + b1.length];
for (int i = 0; i < a1.length; i++)
c[i] = a1[i];
for (int i = a1.length; i < c.length; i++){
c[i] = b1[i];
}
Help_arr.sortup(c);
return c;
}
Functions used from Help_arr class:
1) Scan an array:
public static void scan(int[] arr1) {
for (int i = 0; i < arr1.length; i++) {
System.out.println("Enter number" + (i + 1));
arr1[i] = in.nextInt();
}
}
2) Print an array:
public static void print(int[] arr1) {
for (int i = 0; i < arr1.length; i++) {
System.out.print(arr1[i] + " ");
}
}
3) Sort up an array:
public static void sortup(int[] arr1) {
int i, mini, temp, j;
for (j = 0; j < arr1.length; j++) {
mini = j;
for (i = j; i < arr1.length; i++) {
if (arr1[i] < arr1[mini])
mini = i;
}
temp = arr1[j];
arr1[j] = arr1[mini];
arr1[mini] = temp;
}
}
I get an error in the line c[i]=b1[i]; the array is going out of index bounds but I followed the code and this for will run until i=7 as the c.length is 8 and it is possible. But maybe I am missing something, here is the error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at arrays.PgRonTargilMivhan.peula(PgRonTargilMivhan.java:21)
at arrays.PgRonTargilMivhan.main(PgRonTargilMivhan.java:13)
The issue is with this code:
for (int i = a1.length; i < c.length; i++){
c[i] = b1[i];
here b1 index should start with 0 but you are starting with a1.length. You should have a separate index for b1 or use b1[i-a1.length].
Please find the logic ..
you were using 'i' index for array b is the problem.
Solution is below. Good luck
int[] c = new int[a.length + b.length];
int i = 0;
for (i = 0; i < a.length; i++)
c[i] = a[i];
for (int j = 0; j < b.length; j++)
c[i] = b[j];
}

How to print a two dimensional array?

I have a [20][20] two dimensional array that I've manipulated. In a few words I am doing a turtle project with user inputting instructions like pen up = 0 and pen down = 1. When the pen is down the individual array location, for instance [3][4] is marked with a "1".
The last step of my program is to print out the 20/20 array. I can't figure out how to print it and I need to replace the "1" with an "X". The print command is actually a method inside a class that a parent program will call. I know I have to use a loop.
public void printGrid() {
System.out.println...
}
you can use the Utility mettod. Arrays.deeptoString();
public static void main(String[] args) {
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
System.out.println(Arrays.deepToString(twoD));
}
public void printGrid()
{
for(int i = 0; i < 20; i++)
{
for(int j = 0; j < 20; j++)
{
System.out.printf("%5d ", a[i][j]);
}
System.out.println();
}
}
And to replace
public void replaceGrid()
{
for (int i = 0; i < 20; i++)
{
for (int j = 0; j < 20; j++)
{
if (a[i][j] == 1)
a[i][j] = x;
}
}
}
And you can do this all in one go:
public void printAndReplaceGrid()
{
for(int i = 0; i < 20; i++)
{
for(int j = 0; j < 20; j++)
{
if (a[i][j] == 1)
a[i][j] = x;
System.out.printf("%5d ", a[i][j]);
}
System.out.println();
}
}
Something like this that i answer in another question
public class Snippet {
public static void main(String[] args) {
int [][]lst = new int[10][10];
for (int[] arr : lst) {
System.out.println(Arrays.toString(arr));
}
}
}
public static void printTwoDimensionalArray(int[][] a) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.printf("%d ", a[i][j]);
}
System.out.println();
}
}
just for int array
Well, since 'X' is a char and not an int, you cannot actually replace it in the matrix itself, however, the following code should print an 'x' char whenever it comes across a 1.
public void printGrid(int[][] in){
for(int i = 0; i < 20; i++){
for(int j = 0; j < 20; j++){
if(in[i][j] == 1)
System.out.print('X' + "\t");
else
System.out.print(in[i][j] + "\t");
}
System.out.print("\n");
}
}
You should loop by rows and then columns with a structure like
for ...row index...
for ...column index...
print
but I guess this is homework so just try it out yourself.
Swap the row/column index in the for loops depending on if you need to go across first and then down, vs. down first and then across.
How about trying this?
public static void main (String [] args)
{
int [] [] listTwo = new int [5][5];
// 2 Dimensional array
int x = 0;
int y = 0;
while (x < 5) {
listTwo[x][y] = (int)(Math.random()*10);
while (y <5){
listTwo [x] [y] = (int)(Math.random()*10);
System.out.print(listTwo[x][y]+" | ");
y++;
}
System.out.println("");
y=0;
x++;
}
}
If you know the maxValue (can be easily done if another iteration of the elements is not an issue) of the matrix, I find the following code more effective and generic.
int numDigits = (int) Math.log10(maxValue) + 1;
if (numDigits <= 1) {
numDigits = 2;
}
StringBuffer buf = new StringBuffer();
for (int i = 0; i < matrix.length; i++) {
int[] row = matrix[i];
for (int j = 0; j < row.length; j++) {
int block = row[j];
buf.append(String.format("%" + numDigits + "d", block));
if (j >= row.length - 1) {
buf.append("\n");
}
}
}
return buf.toString();
I am also a beginner and I've just managed to crack this using two nested for loops.
I looked at the answers here and tbh they're a bit advanced for me so I thought I'd share mine to help all the other newbies out there.
P.S. It's for a Whack-A-Mole game hence why the array is called 'moleGrid'.
public static void printGrid() {
for (int i = 0; i < moleGrid.length; i++) {
for (int j = 0; j < moleGrid[0].length; j++) {
if (j == 0 || j % (moleGrid.length - 1) != 0) {
System.out.print(moleGrid[i][j]);
}
else {
System.out.println(moleGrid[i][j]);
}
}
}
}
Hope it helps!
more simpler approach , use java 5 style for loop
Integer[][] twoDimArray = {{8, 9},{8, 10}};
for (Integer[] array: twoDimArray){
System.out.print(array[0] + " ,");
System.out.println(array[1]);
}

Categories