public static int[][] shift(final int[][] original, final int amount) {
int[][] shifted = new int[original.length][original[0].length];
for (int col = 0; col < original.length; col++) {
for (int row = 0; row < original[col].length; row++) {
shifted[col][row] = FILL_VALUE;
}
for (int cols = 0; cols < original.length + amount; cols++) {
for (int rows = 0; rows < original[cols].length; rows++) {
if (cols - amount < original.length) {
shifted[cols][rows] = original[cols - amount][rows];
}
}
}
}
return shifted;
}
Hi,
I am trying to write a method that will shift the elements in my 2-D array to the left by some arbitrary amount. I don't want to loop the values back around, but instead fill the empty arrays with some fill_value which is already predefined. And if the shift amount is more than the orignial length, I would just return an image with only fill_value. However, this function is throwing an arrayindexoutofbound Error. But I can't think of how I should change my for loop to fix the error. Any help is appreciated! Thank you!
I believe it's because in your second outer for loop, the condition is cols < length + amount, so it will continue past the edge of the array if amount > 0. You could step through your code with a debugger and see exactly where it's going out of bounds.
The error is occurring because of following line:
shifted[cols][rows] = original[cols - amount][rows];
When cols=0, rows=0, amount=2 (say), it is trying to access original[-2][0] which does not exist.
Instead you may use following:
public class overflow1 {
static int a[][] = {{1,2,3,4,5,6},{2,3,4,5,6,7},{3,4,5,6,7,8}, {4,5,6,7,8,9}, {5,6,7,8,9,10}, {6,7,8,9,10,11}};
static int b[][] ;
static int FILL_VALUE =0;
public static int[][] shift(final int[][] original, final int amount) {
int[][] shifted = new int[original.length][original[0].length];
for (int col = 0; col < original.length; col++) {
for (int row = 0; row < original[col].length; row++) {
shifted[col][row] = FILL_VALUE;
}
for (int cols = 0; cols < original.length ; cols++) {
for (int rows = 0; rows < original[cols].length; rows++) {
if (cols - amount >=0) {
shifted[cols][rows] = original[cols - amount][rows];
}
}
}
}
return shifted;
}
public static void main(String[] arggs) {
b=shift(a,2);
System.out.println("Original array:");
for(int i=0; i<a.length; i++){
for (int j=0; j<a[i].length; j++){
System.out.print(a[i][j]+ ":");
}
System.out.println();
}
System.out.println("After shift by 2 array:");
for(int i=0; i<b.length; i++){
for (int j=0; j<b[i].length; j++){
System.out.print(b[i][j]+ ":");
}
System.out.println();
}
}
}
Here is the output for the sample:
Original array:
1:2:3:4:5:6:
2:3:4:5:6:7:
3:4:5:6:7:8:
4:5:6:7:8:9:
5:6:7:8:9:10:
6:7:8:9:10:11:
After shift by 2, array:
0:0:0:0:0:0:
0:0:0:0:0:0:
1:2:3:4:5:6:
2:3:4:5:6:7:
3:4:5:6:7:8:
4:5:6:7:8:9:
Related
I need help to complete the removal of the row with max element. I managed to read the user's input to set up the matrix dimension, filled the matrix with random numbers and search for the maximum element. However, I can't delete the row with the max element.
public class Main {
static int MAX = 0;
public static void main(String[] args) {
System.out.println("My name");
System.out.print("Enter N: ");
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
Integer matrix[][] = new Integer[N][N];
Initialization(matrix);
Search(matrix);
}
static void Initialization(Integer[][] matrix) {
Random r = new Random();
System.out.println("Matrix before processing");
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
matrix[i][j] = r.nextInt(100);
System.out.print(matrix[i][j] + "\t");
}
System.out.print("\n");
}
}
static void Search(Integer matrix[][]) {
int max = 0;
for(int i = 0; i < matrix.length; i++) {
for(int j = 0; j < matrix.length; j++) {
if (matrix[i][j] > max) {
max = matrix[i][j];
}
}
}
MAX = max;
System.out.println("Max element in matrix: " + max);
}
}
As #idanz has pointed out in the comments, you cannot redefine an array size, or a matrix since it's simply an array of arrays.
What you can do though is to instantiate a new array (or in this case a new matrix) with one less row than the original matrix. In your search method you could return the index of the row to "delete", then use this index to copy every element from the original matrix into the new one except for the elements within the row to "delete", i.e. not to copy.
On a side note, I've also noticed you've improperly iterated the elements of your matrix. Your innermost loop should check the length of matrix[i].length, not matrix.length. besides, I've also tweaked some variable and method names since they didn't respect the naming conventions. Your variables and methods should start in lower case and be written in camel-case notation.
public class Main {
public static void main(String[] args) {
System.out.print("Enter N: ");
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
//Initializing and printing the matrix
Integer matrix[][] = new Integer[n][n];
initialization(matrix);
print(matrix);
//Retrieving the index row with the maximum element
int rowWithMax = search(matrix);
//Retrieving a new a matrix without the row to delete and assigning it to the old matrix
matrix = deleteRow(matrix, rowWithMax);
System.out.println("\nNew matrix without the deleted row");
print(matrix);
}
static void print(Integer[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + "\t");
}
System.out.println();
}
}
static void initialization(Integer[][] matrix) {
Random r = new Random();
System.out.println("Matrix before processing");
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = r.nextInt(100);
}
}
}
static int search(Integer matrix[][]) {
int max = 0, rowWithMax = -1;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] > max) {
max = matrix[i][j];
rowWithMax = i;
}
}
}
System.out.println("\nMax element in matrix: " + max);
return rowWithMax;
}
static Integer[][] deleteRow(Integer matrix[][], int rowToDelete) {
//Since in Java you cannot redefine the size of an array (in this case an array of array of int)
//you need to instantiate a new matrix filled with the elements of the original matrix except
//for the row with the highest element.
//If no row must be deleted (i.e. no proper index has been passed) then the original matrix is simply returned
if (rowToDelete < 0) {
return matrix;
}
Integer[][] matrix2 = new Integer[matrix.length - 1][matrix.length];
int displacedIndex;
for (int i = 0; i < matrix.length; i++) {
//Skipping the row to delete (i.e. the row which must not be copied within the new matrix)
if (i != rowToDelete) {
//Since i is the row index of the original matrix, this can't be the same index for the new matrix after skipping the row to delete,
//so, we need to create a displaced index for the new matrix which corresponds to i before meeting the deleted row while to i-1 after
//meeting the deleted row
displacedIndex = i < rowToDelete ? i : i - 1;
for (int j = 0; j < matrix[i].length; j++) {
matrix2[displacedIndex][j] = matrix[i][j];
}
}
}
return matrix2;
}
}
I have a question. Can anyone help me with finding duplicates in submatrices?
I have a code which finds submatrices in 2d matrix, but I can't find duplicates. I thought to push the values onto the Stack (because in assignment I should use Stack), find all duplicates in each submatrix, and then compare them, but I don't really know how to do it. I'll be very gratefull, if anyone help me to finish this program.
My code:
public static void main(String[] args) throws Exception {
int[][] data = new int[3][3];
Random random = new Random();
for(int i=0; i<data.length;i++)
{
for(int j=0; j<data.length; j++)
{
data[i][j] = random.nextInt(10);
}
}
printSubMatrix(data);
}
private static void printSubMatrix(int[][] mat) {
int rows=mat.length;
int cols=mat[0].length;
Stack _stack = new Stack();
//prints all submatrix greater than or equal to 2x2
for (int subRow = rows; subRow >= 2; subRow--) {
int rowLimit = rows - subRow + 1;
for (int subCol = cols; subCol >= 2; subCol--) {
int colLimit = cols - subCol + 1;
for (int startRow = 0; startRow < rowLimit; startRow++) {
for (int startCol = 0; startCol < colLimit; startCol++) {
for (int i = 0; i < subRow; i++) {
for (int j = 0; j < subCol; j++) {
System.out.print(mat[i + startRow][j + startCol] + " ");
_stack.push(mat[i+startRow][j+startCol]);
}
System.out.print("\n");
}
System.out.print("\n");
}
}
}
}
System.out.printf(_stack.toString().replaceAll("\\[", "").replaceAll("]", ""));
}
I'm stuck on an assignment where I'm supposed to use helper methods to sort rows and columns in a 2D int array in Java. It's explicitly required to use two different methods to sort an array. Anyways so here is my code for sorting a row
public static void sortOneRow(int[] arr1) {
int temp;
for (int i = 0; i < arr1.length; i++) {
for (int j = i + 1; j < arr1.length; j++) {
if (arr1[i] > arr1[j]) {
temp = arr1[i];
arr1[i] = arr1[j];
arr1[j] = temp;
}
}
}
And here's to sort a column if given an input parameter representing the 2D array and the column index:
public static void sortOneColumn(int[][] x, int colNo) {
// Sorting one column
int[] thisCol = new int[x.length];
for (int i = 0; i < x.length; i++) {
thisCol[i] = x[i][colNo];
}
// Sort
sortOneRow(thisCol);
for (int i = 0; i < x.length; i++) {
x[i][colNo] = thisCol[i];
}
Now, how do I call these two methods in another method that only takes in the 2D Array and I have to first sort rows then sort columns?
If i understand correctly, you want to reuse your own methods to sort an 2D array. Hope this can help:
public static void sort(int[][] a){
if(a == null || a.length == 0) return;
for(int row = 0; row < a.length; row++) {
sortOneRow(a[row]);
}
for(int col = 0; col < a[0].length; col++) {
sortOneColumneRow(a, col);
}
}
I'm looking for a way to add up the elements of the rows of an array and get that sum. I have to get the column's sum as well.
The array looks something like this:
{{45.24, 54.67, 32.55, 25.61},
{65.29, 49.75, 32.08, 26.11},
{25.24, 54.33, 34.55, 28.16}};
For example, I would add 45.24, 65.29, and 25.24 to get the sum of that part of the columns. I would then have to add the other 3 columns up as well.
Same goes for the rows.
I keep getting errors concerning the variable types. Is there a way to do this? Thanks.
The logic Would be --->
for(i = 0; i < columns; i++)
{
for(j=0; j<rows; j++)
{
sum+=arr[j][i];
}
}
Opposite for Columns
I think you should define the type of numbers your array will handle, if I use float numbers I can have some code like the class bellow to do the type of operations you are asked for. You can also add some decimal formatting.
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
float myarray[][]= {
{45.24f, 54.67f, 32.55f, 25.61f},
{65.29f, 49.75f, 32.08f, 26.11f},
{25.24f, 54.33f, 34.55f, 28.16f}
};
float row[] = new float[3];
float column[] = new float[4];
for (int i=0; i < 3; i++) {
float rowvalue = 0f;
for (int j=0; j < 4; j++) {
System.out.print(myarray[i][j]+" ");
rowvalue+=myarray[i][j];
}
row[i]=rowvalue;
System.out.println("");
}
System.out.println("");
for (int i=0; i < 4; i++) {
float colvalue = 0f;
for (int j=0; j < 3; j++) {
System.out.print(myarray[j][i]+" ");
colvalue+=myarray[j][i];
}
column[i]=colvalue;
System.out.println("");
}
System.out.println("Rows answer:");
for (int i=0; i < 3; i++) {
System.out.println(row[i]);
}
System.out.println("Columns answer:");
for (int i=0; i < 4; i++) {
System.out.println(column[i]);
}
}
}
Suppose you have nxn matrix. The idea is to identify the pattern.
Row values
i j
0 0
0 1
0 2
Column values
i j
0 0
1 0
2 0
The position of i and j values is reversed.
Let's assume we have an array a[][]. The logic would be:
for (int i=0; i<n; i++) {
int row = 0, col = 0;
for (int j=0; j<n; j++) {
row += a[i][j];
col += a[j][i];
}
System.out.println("row" + i + " = " + row);
System.out.println("col" + i + " = " + col);
}
I assumed you wanted the sum of each row and column separately. You can modify it accordingly.
So here's my problem. I have to write a program that will fill array with random numbers(and it's ok), then it's necessary to print only even index numbers or only odd value numbers(j). Tried like this but when i put if statement and it shows every even number (index and value-the second in array) so it wrong. What should i do so?
import java.util.Random;
public class Array {
public static void main(String[] args)
{
int rows = 5;
int colu = 2;
Random r = new Random();
int [][] array = new int [rows][colu];
for(int row = 0; row < array.length; row++)
{
for(int col = 0; col < array[row].length; col++)
{
array[row][col] = r.nextInt(10);
}
}
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array[i].length; j++)
{
if(array[i][j]%2 == 0){
System.out.print(array[i][j] + " ");
}
}
}
System.out.println();
}
}
Thanks
I'm going to take a stab at this but I'm not sure if I quite understand yet.
int array[][] = new int[row][col];
// ... populate the array with random numbers, works fine...
// Let's traverse the first column.
for (int i = 0; i < row; i++) {
int value = array[i][0]; // col 0 means first column
if (value % 2 == 0) {
// ...
}
}
// Let's traverse the second column.
for (int i = 0; i < row; i++) {
int value = array[i][1]; // col 1 means second column
// ...
}
Is this what you mean? If it is, do you see the pattern and how you could generalize this and make the code a bit smaller?
Just implement this formula in your "if" statement :
(Number × 2 )/4 ==0. You will always get even numbers. You can handle the rest :D