I have to sort elements in each row and then display the array.
For example, if the input array is:
5 1 3 1 3 5
INPUT: 7 6 4 OUTPUT: 4 6 7
9 8 2 2 8 9
My code for that was:
for (int i = 0; i < size; i++) { //"size" is the size of the square matrix
for (int j = 0; j < size; j++) {
for (int k = 0; k < size - 1; k++) {
for (int l = 0; l < size - k - 1; l++) {
if (arr[i][j] > arr[i][j+1]) { //arr[][] is of datatype int
int temp = arr[i][j];
arr[i][j] = arr[i][j+1];
arr[i][j+1] = temp;
}
}
}
}
}
Any suggestions?
for (int i = 0; i < size; i++){ //"size" is the size of the square matrix
for (int j = 0; j < size; j++){
for (int k = j+1; k < size; k++){
if (arr[i][j] > arr[i][k]){ //arr[][] is of datatype int
int temp = arr[i][j];
arr[i][j] = arr[i][k];
arr[i][k] = temp;
}
}
}
}
I don't think you need 4th loop
I would do it simpler
for(int[] r : arr){
Arrays.sort(r);
}
I would create a method to sort rows, and then just iterate through the rows in the matrix and sort them one at a time. For example:
public static int[] sortRow(int[] row) // selection sort
{
for (int i = 0; i < row.length - 1; i++) {
for (int j = i + 1; j < row.length; j++) {
if (row[i] > row[j]) {
int temp = row[i];
row[i] = row[j];
row[j] = temp;
}
}
}
return row;
}
public static void main(String args[])
{
int[][] arr = {{5, 1, 3}, {7,6,4}, {9,8,2}};
for (int r = 0; r < arr.length; r++) { // for every row in the matrix
arr[r] = sortRow(arr[r]); // set the row to be the sorted row
}
// print out the array to the console
for (int r[] : arr) {
for (int c : r)
System.out.print(c + " ");
System.out.println();
}
}
Output:
1 3 5
4 6 7
2 8 9
Related
So I'm currently playing around with multidimensional arrays (2D) and I'm trying to reverse the order of each array in a 2-d array.
So I have a 2D-array set as:
int firstArray[][] = {{5,6,7,8,9,10}, {11,12,13,14,15,16}}
I have manually looked through the issue to see where I may have went wrong, to see which part of my code would end up going out of bounds in regards to my for-loops. The -1 part also caught me off guard.
I have began doing reverses on a regular 1-d array, and tried to apply the same concept to multidimensional arrays.
class Test2 {
public static void main (String[] args) {
int firstArray[][] = {{5,6,7,8,9,10}, {10,11, 12, 13, 14, 15}};
System.out.println("FIRST ARRAY");
display(firstArray);
}
public void display(int [][]num) {
for (int i = 0; i < num.length; i++) {
for (int j = 0; j < num[i].length/2; j++) {
int temp = num[i][j];
num[i][j] = num[i][num.length-1-j];
num[i][num.length-1-j] = temp;
}
}
for (int a = 0; a < num.length; a++) {
for (int b = 0; b < num[a].length; b++) {
System.out.print(num[a][b] + "\t");
}
System.out.println();
}
}
}
I want the output using my display method to basically be a reverse of the arrays in my 2-d array:
10 9 8 7 6 5
15 14 13 12 11 10
The issue that I'm getting is an
Exception in thread "main"java.lang.ArrayIndexOutOfBoundsException: -1
ArrayIndexOutOfBoundsException: -1
at Test2.display(Test2.java:30)
at Test2.main(Test2.java:20)
You are using the length of the wrong dimension.
With num.length you are using the number of rows and not the number of columns of the current row.
You need to change that to num[i].length.
public static void display(int [][]num) {
for (int i = 0; i < num.length; i++) {
for (int j = 0; j < num[i].length/2; j++) {
int temp = num[i][j];
num[i][j] = num[i][num[i].length-1-j];
num[i][num[i].length-1-j] = temp;
}
}
for (int a = 0; a < num.length; a++) {
for (int b = 0; b < num[a].length; b++) {
System.out.print(num[a][b] + "\t");
}
System.out.println();
}
}
Notice you wrote num[i][num.length-1-j];
num.length-1-j is basically 2 - 1 -j.
public static void display(int [][]num) {
for (int i = 0; i < num.length; i++) {
for (int j = 0; j < num[i].length/2 ; j++) {
int temp = num[i][j];
num[i][j] = num[i][num[i].length-1-j];
num[i][num[i].length-1-j] = temp;
}
}
for (int a = 0; a < num.length; a++) {
for (int b = 0; b < num[a].length; b++) {
System.out.print(num[a][b] + "\t");
}
System.out.println();
}
}
This question already has answers here:
Syntax for creating a two-dimensional array in Java
(13 answers)
Closed 3 years ago.
I am working with 2-D arrays and I require help on this topic. My task is to create a 2-D array such that it is n by n (i.e. the number of rows and columns are equal). Fill the array with alternating 0's and 1's
void setup()
{
int n=3;
// code to populate the array
// code to display the output of array in a table format
/* output should be as follows:
The expected result when n=3 should be as the following:
1 0 1
0 1 0
1 0 1
*/
}
Solution:
class test{
public static void main(String[] args) {
int n = 3;
int[][] arr = setup(n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(arr[i][j]);
}
System.out.println();
}
}
static int[][] setup(int n){
int[][] arr = new int [n][n];
boolean even = false;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
arr[i][j] = even ? 1 : 0;
even = !even;
}
}
return arr;
}
}
Output:
0 1 0
1 0 1
0 1 0
This should work.
You can replace the 3 that is given to n with any number you want as the 2D-Array's length.
void setup(){
int n = 3;
int count = 0;
int[][] myArray = new int[n][n];
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(count % 2 == 0){
myArray[i][j] = 1;
}
else{
myArray[i][j] = 0;
}
System.out.print(myArray[i][j] + " ");
count++;
}
System.out.println();
}
}
Output:
0 1 0
1 0 1
0 1 0
It's not complex, you just have to iterate two loops, that's it. Although you can get the solution on different ways.
public static void main(String[] args) {
int n = 3;
int [][] arr = new int[n][n];
int val = 1;
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
arr[i][j] = val;
val = (val == 0) ? 1 : 0;
}
}
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
Output:
0 1 0
1 0 1
0 1 0
A simple implementation:
void setup()
{
int n=3;
final int[][] array = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if ((n * i + j) % 2 == 0) {
array[i][j] = 1;
}
}
}
}
Here is how you can approach your logic , create a counter and negate each time after it prints value.
public static void main(String[] args) {
int counter = 0;
int n = 3;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
System.out.print(counter==0?1:0);
counter = ~counter;
}
System.out.println();
}
}
Output
101
010
101
Here is Online source code.
Given a matrix with m-rows and n-columns, finding the maximum sum of
elements in the matrix by removing almost one row or one column
Example:
m=2, n=3
matrix :
**[[1,2,-3]
[4,5,-6 ]
]**
output: 12 , by removing the third column then sum of elements in
[[1,2][4,5]]
How to solve this problem in java8 using dynamic programming
Based on the kadane algorithm, below code works fine
public static void main(String[] args) {
int[][] m = {
{1, 2, -3},
{4, 5, -5},
};
int N = m.length;
for (int i = 0; i < N; ++i)
m[0][i] = m[0][i];
for (int j = 1; j < N; ++j)
for (int i = 0; i < N; ++i)
m[j][i] = m[j][i] + m[j - 1][i];
int totalMaxSum = 0, sum;
for (int i = 0; i < N; ++i) {
for (int k = i; k < N; ++k) {
sum = 0;
for (int j = 0; j < N; j++) {
sum += i == 0 ? m[k][j] : m[k][j] - m[i - 1][j];
totalMaxSum = Math.max(sum, totalMaxSum);
}
}
}
System.out.println(totalMaxSum);
}
I try to convert 1D to 2D array, but I keep getting java.lang.ArrayIndexOutOfBoundsException, and I have tried whatever I could find on the stackoverflow or internet, but I do not understand why I have this issue?
public class Arrayto2DArray {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int[] a = {0,1, 6, 83, 4, 5, 12, 7};
int[][] b = new int[4][4];
for (int i = 0; i < b.length; i++) {
for (int j = 0; j < b[i].length; j++) {
b[i][j]=0;
System.out.print(b[i][j]);
}
System.out.println();
}
System.out.println("--------------------------");
for (int i = 0; i < 4; i++) {
for (int j = 0; j < b[i].length; j++) {
try{
b[i][j] = a[i+j*4];
}catch(Exception e){
e.printStackTrace();
System.out.println(e);
}
}
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
System.out.print(b[i][j]);
}
System.out.println();
}
}
}
I kind of know why I get this error and it because of this line
b[i][j] = a[i+j*4];
but I cannot come up any formula better than this.
Consider the second for-loop
Lets say when i = 3 and j= 3
a[i+j*4] evaluates to a[15] which is out of the array
When you declare you 2-d array, you specified int[][] b = new int[4][];, meaning that the first inner for loop for (int j = 0; j < b[i].length; j++) should result in a NullPointerException since b[i].length has no predefined length. Before intering the inner for loop, you should define the size of each b[i] like b[i] = new int[somenumber]
In regards to convert the 1d loop to a 2d, you need to define the rule around spliting it into the 2-d array. Then accordingly the second for loop need modification
EDIT:You modified your code to have an int[4][4] array, which means you have 16 placeholders. Your 1-d array contain only 8 placeholders. It depends on how you want to sort the array, like it can be
b 0 1 2 3
0 0 1 6 83
1 4 5 12 7
2 0 0 0 0
3 0 0 0 0
or any other pattern
Assuming the length of 1-d array is 8 and the total index of 2-d array is 16, the following is more of a general solution:
public static void main(String[] args) {
// TODO code application logic here
int[] a = { 0, 1, 6, 83, 4, 5, 12, 7 };
int[][] b = new int[4][4];
for (int i = 0; i < b.length; i++) {
for (int j = 0; j < b[i].length; j++) {
b[i][j] = 0;
System.out.print(b[i][j] + "\t");
}
System.out.println();
}
System.out.println("--------------------------");
for (int i = 0; i < 4; i++) {
for (int j = 0; j < b[i].length; j++) {
try {
if ((j + i * 4) < a.length)
b[i][j] = a[j + i * 4];
} catch (Exception e) {
e.printStackTrace();
System.out.println(e);
}
}
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
System.out.print(b[i][j] + "\t");
}
System.out.println();
}
}
What is wrong is your 2D array is a 4*4, so that means for each index, there will be 4 elements i.e. say values. So there would be a total of 16 values, so you would need a 1D array with 16 elements for the above code to work. Right now you have only 8 values in your 1D array.
I think your code should change like this
public class Arrayto2DArray {
public static void main(String[] args) {
// TODO code application logic here
int[] a = {0,1, 6, 83, 4, 5, 12, 7};
int[][] b = new int[4][2];
for (int i = 0; i < b.length; i++) {
for (int j = 0; j < b[i].length; j++) {
b[i][j]=0;
System.out.print(b[i][j]);
}
System.out.println();
}
System.out.println("--------------------------");
for (int i = 0; i < 4; i++) {
for (int j = 0; j < b[i].length; j++) {
try{
b[i][j] = a[i+j*4];
}catch(Exception e){
e.printStackTrace();
System.out.println(e);
}
}
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 2; j++) {
System.out.print(b[i][j]+" ");
}
System.out.println();
}
}
}
Your correct formula should be like.
int[] a = {0,1, 6, 83, 4, 5, 12, 7};
int[][] b = new int[4][2];
int k=0;
for (int i = 0; i < b.length; i++) { // Column of 2D array
for (int j = 0; j < b[0].length; j++) { // Row of 2D array
b[i][j]= a[k++];
System.out.println(b[i][j]);
}
}
Edit:
For general case, If your row is fixed at 4 but column is not fixed than your 2D conversion formula should be like below.
int col = a.length / 4;
int remainder = a.length % 4;
if (remainder > 0) {
col = col + 1; // Get the correct column size.
}
int[][] b = new int[4][col];
int k = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < col; j++) {
if (k < a.length) {
b[i][j] = a[k];
System.out.println(b[i][j]);
}
k++;
}
}
So I am trying to figure out how to swap an ith row with the jth column. I have searched everywhere and still cant find a solution similar to what im looking for. (Pretty much switching the first row with the second column) I assume that i am going to have to create a temp to hold the value then swap it, but i can only do it for swapping out a row with another row or column with another column. At this point i am just completely lost. Any suggestions would be appreciated.
what it might look like for better clarification
Input:
2 3 4
1 2 3
4 5 6
Output:
3 2 5
1 3 3
4 4 6
Code :
private int n;
private int [][] Matrix = new int[n][n];
public void switchRowColumn(int i, int j)
{
for(int i=0; i< Matrix.length; i++)
{
I found this working, see if it works for you ...
public class Swap{
public static void main(String[]args){
int [][] array = {
{2,3,4},
{1,2,3},
{4,5,6}
};
swap(array, 0 , 1);
}
public static void swap ( int [][] array, int row, int col){
int [] temprow = new int [array[0].length];
int [] tempcol = new int [array.length];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[0].length; j++) {
if(i == row){
temprow = array[i]; // TEMP ROW
}
}
}
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[0].length; j++) {
if(j == col){
tempcol[i] = array[i][j];
}
}
}
for (int i = 0; i < tempcol.length; i++) {
System.out.print(tempcol[i]); /// COLS
}
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
if(i == row){
array[i] = tempcol;
}
}
}
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[0].length; j++) {
if(j == col){
array[i][j] = temprow[i];
}
}
}
System.out.println();
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[0].length; j++) {
System.out.print(array[i][j]+" ");
}
System.out.println();
}
}
}