Bubble-Sort 2D array - java

I need to build a code that bubble sort 2D array. The trick here is that I cannot use an one dimensional array helper, or move the items to another array.
The sorting need to be on the 2D array.
Now I built my function. But something is going wrong. This is my output
1 1 2 6 12 32
49 44 54 55 100 344
is to close to be done, and I cant think how to do it.
public static int [] [] sortMatrix(int[][]matrix){
for(int x = matrix.length ; x >0 ; x-- ){
for(int i = matrix[0].length ; i > 0 ; i-- ){
for(int j = 0 ; j < x ; j++){
for(int t = 0 ;t < i ; t++){
if(t < matrix[0].length - 1 && matrix[j][t] > matrix[j][t+1] ){
swap(matrix , j , t, t+1);
}
else if(t == matrix[0].length - 1 && j != matrix.length -1&& matrix[j][t] > matrix[j+1][0] ){
swap1(matrix ,j , t , j + 1);
}
}
}
}
}

Try
public static int [] [] sortMatrix(int[][]matrix){
// for loop of matrix rows: -
for(int x = 0 ; x < matrix.length; x++){
// for loop of matrix columens: -
for(int i =0; i < matrix[x].length; i++){
// for loop of comparison and swapping
for(int t = 0; t < matrix[x].length - i - 1; t++){
if(matrix[x][t] > matrix[x][t+1]){
// Swapping operation: -
int temp = matrix[x][t];
matrix[x][t] = matrix[x][t+1];
matrix[x][t+1] = temp;
}
}
}
}
return matrix;
}
instead of
public static int [] [] sortMatrix(int[][]matrix){
for(int x = matrix.length ; x >0 ; x-- ){
for(int i = matrix[0].length ; i > 0 ; i-- ){
for(int j = 0 ; j < x ; j++){
for(int t = 0 ;t < i ; t++){
if(t < matrix[0].length - 1 && matrix[j][t] > matrix[j][t+1] ){
swap(matrix , j , t, t+1);
}
else if(t == matrix[0].length - 1 && j != matrix.length -1&& matrix[j][t] > matrix[j+1][0] ){
swap1(matrix ,j , t , j + 1);
}
}
}
}
}

Below is the code for sorting 2D array, trick is that you have to think of the 2D array as one dimensional array and then derive the appropriate row, offset pairs for indices.
import java.util.Arrays;
public class Bubble2DSort {
public static void main(String[] args) {
System.out.println("Started");
int[][] matrix = {{49,44,54,55,100,344}, {1,1,2,6,12,32}};
sortMatrix(matrix);
System.out.println("Printing output ");
for(int[] rowArr : matrix) {
System.out.println(Arrays.toString(rowArr));
}
}
private static void sortMatrix(int[][] matrix) {
int row = matrix.length;
int col = matrix[0].length;
int totalCount = row * col;
System.out.println("totalCount : " +totalCount);
boolean noSwaps = false;
for(int i = 0; !noSwaps; i++) {
noSwaps = true;
for(int j = 1; j < totalCount - i; j++) {
int currentRow = (j-1) / col;
int currentOffset = (j-1) % col;
int nextRow = j / col;
int nextOffset = j % col;
if( matrix[currentRow][currentOffset] > matrix[nextRow][nextOffset]) {
//swapping
int temp = matrix[nextRow][nextOffset];
matrix[nextRow][nextOffset] = matrix[currentRow][currentOffset];
matrix[currentRow][currentOffset] = temp;
noSwaps = false;
}
}
}
}
}
Output:
Started
totalCount : 12
Printing output
[1, 1, 2, 6, 12, 32]
[44, 49, 54, 55, 100, 344]

Related

Program counting adjacent elements in a 2D array gives inconsistent results

I have a piece of program that i have to fill. It is supposed to count adjacent numbers in a 5 by 5 binary matrix. For example a matrix like this:
0 1 1 1 0
1 0 0 0 1
1 0 0 0 0
1 0 0 1 0
0 1 0 1 0
Should return 8, you can only move horizontally or vertically.
Here is the code that generates these said matrices and it can't have any modifications after i'm done.
import java.util.Random;
public class Test {
public static void main(String[] args) {
final Random r = new Random();
for (int kerrat = 0; kerrat < 10; kerrat++) {
int[][] alkioTaulukko = new int[5][5];
System.out.println("Matriisin");
for (int i = 0; i < alkioTaulukko.length; i++) {
System.out.print("");
for (int j = 0; j < alkioTaulukko[i].length; j++) {
alkioTaulukko[i][j] = r.nextInt(2);
System.out.print("" + alkioTaulukko[i][j] + " ");
}
System.out.println("");
}
System.out.print("suurimman yhtenäisen alueen koko on ");
System.out.println(laskeSuurinAlue(alkioTaulukko));
System.out.println("");
}
}
}
And finally here is my solution to the problem.
static int laskeSuurinAlue(int[][] matriisi) {
int vierekkaiset = 0;
int rivi = matriisi.length;
int palkki = matriisi[0].length;
for (int r = 0; r < rivi; r++)
{
for (int p = 0; p < palkki; p++)
{
if ((p+1 < palkki) && (matriisi[r][p] == matriisi[r][p+1]))//loops through the rows
vierekkaiset++;
if ((r+1 < rivi) && (matriisi[r][p] == matriisi[r+1][p]))//loops through the columns
vierekkaiset++;
}
}
return vierekkaiset;
}
What happens is that my solution always brings up too big results and i'm failing to see any pattern between each run. However if i use a smaller matrix like this:
int[][] array = {{1, 0, 1}, {0, 1, 1}, {0, 1, 0}};
The result is correctly 4.
And if i use a bigger one like this:
int[][] arr = {{1,0,1,1,0},
{0,0,1,0,0},
{0,0,1,0,1},
{1,1,1,0,1},
{0,0,1,0,0}
};
The result is always 20.
Finally here is my code at its current state:
import java.util.Random;
import static java.util.Arrays.deepToString;
public class Test {
public static void main(String[] args) {
final Random r = new Random();
int[][] array = {{1, 0, 1}, {0, 1, 1}, {0, 1, 0}};
int[][] arr = {{1,0,1,1,0},
{0,0,1,0,0},
{0,0,1,0,1},
{1,1,1,0,1},
{0,0,1,0,0}
};
for (int kerrat = 0; kerrat < 10; kerrat++) {
int[][] alkioTaulukko = new int[5][5];
System.out.println("Matriisin");
for (int i = 0; i < alkioTaulukko.length; i++) {
System.out.print("");
for (int j = 0; j < alkioTaulukko[i].length; j++) {
alkioTaulukko[i][j] = r.nextInt(2);
System.out.print("" + alkioTaulukko[i][j] + " ");
}
System.out.println("");
}
System.out.print("suurimman yhtenäisen alueen koko on ");
System.out.println(laskeSuurinAlue(arr));//Change to arr,array or alkioTaulukko to run the code with different matrices
System.out.println(deepToString(arr));
System.out.println("");
}
}
static int laskeSuurinAlue(int[][] array) {
int counter = 0;
int rowLimit = array.length;
int colLimit = array[0].length;
for (int r = 0; r < rowLimit; r++)
{
for (int c = 0; c < colLimit; c++)
{
if ((c+1 < colLimit) && (array[r][c] == array[r][c+1]))
counter++;
if ((r+1 < rowLimit) && (array[r][c] == array[r+1][c]))
counter++;
}
}
return counter;
}
}
You're couting the same entry more than once.
Use this code
static int laskeSuurinAlue(int[][] array) {
int counter = 0;
int rowLimit = array.length;
int colLimit = array[0].length;
for (int r = 0; r < rowLimit; r++)
{
for (int c = 0; c < colLimit; c++)
{
if (array[r][c] == 0) {
continue;
}
int sum = array[r][c];
sum += (r + 1 < rowLimit) ? array[r+1][c] : 0;
sum += (c + 1 < colLimit) ? array[r][c+1] : 0;
sum += (r - 1 >= 0 ) ? array[r-1][c] : 0;
sum += (c - 1 >= 0) ? array[r][c-1] : 0;
if (sum > 1) {
counter++;
}
}
}
return counter;
}

How can I find a local minimum in a 2D array?

public static void main(String[] args) {
// TODO code application logic here
int numRows = 5;
int numCols = numRows;
int[][] twoDimArray = new int[numRows][numCols];
Random randGen = new Random();
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
int randIndex = randGen.nextInt(4);
int value = randGen.nextInt(100);
twoDimArray[i][j] = value;
}
}
System.out.println("\nThe two-dimensional array: ");
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
System.out.print(twoDimArray[i][j] + " ");
}
System.out.println();
}
}
}
I want to find a local minimum using a "brute force" approach. I know with a one dimensional array I would use a for-loop to compare all the elements in the array until I found a local minimum, but I don't know how to do that here.
Edit: Could I use binary search instead? Find the middle row and search there and if one isn't found, I search one of the halves.
The brute force method would be very similar to that of a 1D array, just with an extra loop, and a few more checks:
public int[] findLocalMinimum(int[][] arr) {
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
int current = arr[i][j];
if (i + 1 < arr.length && current >= arr[i + 1][j] ||
i - 1 >= 0 && current >= arr[i - 1][j] ||
j + 1 < arr[i].length && current >= arr[i][j + 1] ||
j - 1 >= 0 && current >= arr[i][j - 1]) {
continue;
} else {
return new int[] { i, j };
}
}
}
return new int[] { -1, -1 };
}

How can I sum the product of two two-dimensional arrays?

So I got a code with two arrays: one array contains tickets sold for three cinemas and the other one contains the adult and kid prices. My code outputs the total for every cinema separately (3 lines of output) but I need the total number of those 3. So instead of printing 828 for cinema1, 644 for cinema2, 1220 for cinema3 and I need it to print 2692 (total of 3 cinemas). How can I sum the 3 products with a for loop? Here's the code:
public class Arrays {
public Arrays() {}
public static void main(String[] args) {
float[][] a = new float[][] {{29, 149}, {59, 43}, {147, 11}};
float[] b = new float[] {8, 4};
String[] s = new String[] {"cinema 1", "cinema 2", "cinema 3"};
String[] t = new String[] {"Adults", "Children"};
int i,j;
System.out.println("Cinema Complex Revenue\n\n");
for ( i = 0 ; i <= 2 ; i++ )
{
for ( j = 0 ; j < 1 ; j++ )
{
System.out.println(s[i] + "\t$" +
(a[i][j] * b[j] + a[i][j + 1] * b[j + 1]));
}
}
}
}
And the output: 1
Just code what you want.
int i, j;
float sum = 0;
for (i = 0; i < a.length; i++) {
for (j = 0; j < a[i].length && j < b.length; j++) {
sum += a[i][j] * b[j];
}
}
System.out.println(sum);
Or if you want to use only one for loop, it may be
int i;
float sum = 0;
for (i = 0; i < a.length * b.length; i++) {
sum += a[i / b.length][i % b.length] * b[i % b.length];
}
System.out.println(sum);
All you need is 1 nested for-loop:
Integer totalCost = 0;
for( i = 0 ; i<b.length; i++ ) {
//you should check if the a[i].length == b.length, and throw an exception if not!
for( j = 0 ; j<a.length; j++) {
totalCost += b[i]*a[j][i];
}
}
System.out.println("Total cost: "+totalCost.toString());

Insert a String of numbers into a matrix

I'm kind of stuck in this algorithm. I have this function below that gets a String and a matrix[n][m].
The String has up to n*m digits, and I need to insert them by reverse from the last digit to the last cell of the matrix, respectively, until I reach the first cell;
For example: the String='3' will be like that {[0][0],[0][3]}; the String='123' will be like that {[0][1],[2][3]}; and the String='2222' will be like that {[2][2],[2][2]};
The issue is: For the String '123' I get a matrix {[1][1],[1][1]}. It seems like only the first digit insert into the matrix.
stringToInteger(String correctBase, int [][] board)
{
int integerNum;
for(int i=correctBase.length()-1; i>=0; i--)
{
integerNum=correctBase.charAt(i)-'0';
for(int row=board.length-1; row>=0; row--)
for(int col=board[row].length-1; col>=0; col--)
board[row][col]=integerNum;
}
Try this:
stringToInteger(String correctBase, int [][] board)
{
int integerNum;
int row = board.length - 1;
int col = board[0].length - 1;
for(int i=correctBase.length()-1; i>=0; i--)
{
integerNum=correctBase.charAt(i)-'0';
board[row][col]=integerNum;
col--;
if(col < 0) {
col = board[0].length - 1;
row--;
}
}
...
}
Yes, or:
int i = correctBase.length();
for(int row=board.length-1; row>=0; row--)
for(int col=board[row].length-1; col>=0; col--)
board[row][col] = i > 0 ? correctBase.get(--i)-'0' : 0;
I would first check if the size of the string matches the size of the matrix. If it does not, then pad said string with zeroes. Then just parse the positions of the string and insert them into the matrix.
Try it like this.
public static void main(String[] args) {
//define size of matrix
int n = 2;
int m = 2;
String input = "3";
//if size of string is less than matrix size we append 0 to it
if (input.length() < n * m) {
int diff = n * m - input.length();
for (int i = 0; i < diff; i++)
input = "0" + input; //pad zeroes to the string
}
int board[][] = new int[n][m]; //declare matrix
//populate matrix
int stringPosition = 0; //position in the string starting from the left
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
board[i][j] =
Character.getNumericValue(input.charAt(stringPosition)); //transfrom char to int, then assign it to matrix
stringPosition++; //increment position
}
}
//display matrix
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
System.out.println("board[" + i + "][" + j + "] = " + board[i][j]);
}
}
}
It produces the desired results
input="3"
board[0][0] = 0
board[0][1] = 0
board[1][0] = 0
board[1][1] = 3
input="123"
board[0][0] = 0
board[0][1] = 1
board[1][0] = 2
board[1][1] = 3
input="2222"
board[0][0] = 2
board[0][1] = 2
board[1][0] = 2
board[1][1] = 2

Traversing a 2D array matrix diagonally from bottom left to upper right

I have a 3x4 matrix represented by a 2D array:
. 0 1 2 3
0 a c f i
1 b e h k
2 d g j l
and my approach to traverse the diagonal slice was to treat each slice as a sum, like this:
a = (0+0) = 0
b,c = (0+1),(1+0) = 1
d,e,f = (0+2),(1+1),(2+0) = 2
g,h,i = (1+2),(2+1),(3+0) = 3
j, k = (2+2),(3+1) = 4
l = (3+2) = 5
However, my code right now prints it in the opposite way that I want it to, which is from upper right to bottom left.
Current Output is:
acbfedihgkjl
Desired Output is:
abcdefghijkl
for (int sum = 0; sum <= numRows + numColumns - 2; sum++) {
for (int i = 0; i < numRows; i++) {
int j = sum - i;
if ((i >= 0 && i < numRows) && (j >= 0 && j < numColumns)) {
System.out.print(array[i][j]);
}
}
}
Can somebody point me in the right direction on how to fix my code to get the output that I want?
While it isn't very pretty, I think this will do it:
int i = 0;
int j = 0;
while (true) {
System.out.println("" + array[i][j]);
--i;
++j;
if (i < 0) {
if (j == numCols)
break;
i = Math.min(j, numRows - 1);
j = Math.max(j - numCols + 2, 0);
} else if (j >= numCols) {
if (i == numRows - 2)
break;
i = numRows - 1;
j = Math.max(j + 2 - numCols + i, 0);
}
}
int i = 0;
int j = 0;
int n = 0;
int x = 3;
int y = 4;
int newSize = Math.max(x,y) * Math.max(x,y);
while(n < newSize){
if(i <= x && j <= y)
System.out.println(array[i][j]);
n++;
if(i == 0) {
i = n:
j = 0;
} else {
--i;
++j;
}
}

Categories

Resources