Extract an String Array and turn into int matrix - java

I have an array of String like this, {"1","0","1","<>","0","1","0","<>","1","0","1"} and I need to extract the numbers and populate an int matrix. The "<>" is a breakline, so in this caseI will have in the end, this matrix: int matrix[][] = new int[3][3]. But I want to develop an genereic function to extract n numbers of rows and columns.
List<String> oM = Arrays.asList(strArr);
int iterator = 0;
int numberOfColumns = (int) oM.stream().takeWhile(s -> !s.equalsIgnoreCase("<>")).count();
int numberOfRows = (int) oM.stream().filter(s -> s.equalsIgnoreCase("<>")).count() + 1;
int originalMatrix[][] = new int[numberOfRows + 1][numberOfColumns];
for (int i = 0; i < numberOfRows; i++) {
for (int j = 0; j <= numberOfColumns - 1; j++) {
if (!strArr[iterator].equalsIgnoreCase("<>")) {
originalMatrix[i][j] = Integer.parseInt(strArr[iterator]);
iterator++;
continue;
}
iterator++;
}
}
But the order It's not right, can anybody please show my fault ?

Related

Java implement cross correlation 2d image

enter image description here
Can i implement the cross-correlation in the same way as the convolution?
I want to implement the formula in as in the picture, where Li the kernel in 4 different direction filters; Ci is the magnitude map for direction i. So what I did is to find the cross-correlation in the four directions separately and add them up. I learned that the cross correlation can be the same as convolution in image line sharping; s as the result should be stroke line of an image but what I actually get are discrete points. I am not sure if I implemented the formula correctly. Please help
private static void sharpTheLine(){
int[][] cC_0= crossCorrelation(KERNEL_0,CMap_0);
int[][] cC_45=crossCorrelation(KERNEL_45,CMap_45);
int[][] cC_90=crossCorrelation(KERNEL_90,CMap_90);
int[][] cC_135=crossCorrelation(KERNEL_135,CMap_135);
//generate S
for(int i=0; i<imageWidth; i++){
for(int j =0; j<imageHight; j++) {
SMap[i][j] = cC_0[i][j]+cC_45[i][j]+cC_90[i][j]+cC_135[i][j];
}
}
}
private static int[][] crossCorrelation(int [][] kernel,int[][] CMapVal){
int horizontalWalk = imageWidth - K_R;
int verticalWalk = imageHight - K_C;
int res[][]=new int[imageWidth][imageHight];
for (int i = 0; i < horizontalWalk; i++) {
for (int j = 0; j < verticalWalk; j++) {
int sample[][] = new int[K_R][K_C];
for (int k = i; k < K_R + i; k++) {
for (int m = j; m < K_C + j; m++) {
sample[k - i][m - j] = CMapVal[k][m];
OnePixelConvolution(sample, i, j, kernel, res);
}
}
}
}
return res;
}
private static void OnePixelConvolution(int[][] sample, int x, int y, int [][]kernel, int [][] res) {
int resrgb = 0;
for (int i = 0; i < K_R; i++) {
for (int j = 0; j < K_C; j++) {
resrgb = resrgb + sample[i][j] * kernel[i][j];
}
}
res[x][y] = resrgb;
}

Find the biggest gap after removing a list of rows and columns in an array

I have an array of size m rows n columns with each cell size is considered as 1x1.
Now I am removing a list of rows and columns from this array, next I want to know the biggest gap that can be formed after removing them.
Example:
Array of size 4 rows and 3 columns, now I am removing rows {1,2,3} and columns {1,2}
This results is an array having biggest gap of 12 cells.
Another Example:
Array of size 4 rows and 4 columns, now I am removing rows {2} and columns {2}
This results is an array having biggest gap of 4 cells.
I have come up with below code that works for this example:
static long process(int n, int m, int[] h, int[] v) {
ArrayList<ArrayList<Long>> array = new ArrayList<ArrayList<Long>>();
for (int r = 0; r <= n; r++) {
ArrayList<Long> temp = new ArrayList<Long>();
for (int c = 0; c <= m; c++) {
temp.add((long) 1);
}
array.add(temp);
}
int[] x = h;
int xnum = x.length;
Arrays.sort(x);
int[] y = v;
int ynum = y.length;
Arrays.sort(y);
// removing bar i means that list at i-1 and at i
for (int a = xnum - 1; a >= 0; a--) {
int i = x[a];
for (int cell = 0; cell < array.get(i).size(); cell++) {
array.get(i).set(cell, array.get(i).get(cell) + array.get(i - 1).get(cell));
}
array.remove(i - 1);
}
ArrayList<ArrayList<Long>> newarray = new ArrayList<ArrayList<Long>>();
for (int col = 0; col < array.get(0).size(); col++) {
ArrayList<Long> temp = new ArrayList<Long>();
for (int row = 0; row < array.size(); row++) {
temp.add(array.get(row).get(col));
}
newarray.add(temp);
}
for (int b = ynum - 1; b >= 0; b--) {
int i = y[b];
for (int cell = 0; cell < newarray.get(i).size(); cell++) {
newarray.get(i).set(cell, newarray.get(i).get(cell) + newarray.get(i - 1).get(cell));
}
newarray.remove(i - 1);
}
long max = 1;
for (ArrayList<Long> arr : newarray) {
for (long num : arr) {
if (num > max)
max = num;
}
}
return max;
}
How can we reduce the time complexity of this code, because the size of rows and columns is:
1 <= rows, columns <= 100000
Let's start by looking at your current solution, by using simple array instead of ArrayList we can reduce this code to:
static long process(int rows, int cols, int[] hor, int[] ver) {
final long[][] a = new long[rows][cols];
for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) a[i][j] = 1;
for (int h : hor) for (int j = 0; j < cols; j++) a[h - 1][j] = a[h][j] = a[h - 1][j] + a[h][j];
for (int v : ver) for (int i = 0; i < rows; i++) a[i][v - 1] = a[i][v] = a[i][v - 1] + a[i][v];
long max = 0;
for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) max = Math.max(max, a[i][j]);
return max;
}
this code has complexity O(N^2)
but, we should understand that biggest gap will be in place where biggest count of consecutive rows and columns are removed, thus we can simplify algorithm to:
static int maxConsecutive(int[] a) {
Arrays.sort(a);
int max = 0;
int start = 0;
for (int i = 0; i < a.length; i++)
if (a[i] - a[start] == i - start) max = Math.max(max, i - start + 1);
else start = i;
return max;
}
static long process(int rows, int cols, int[] hor, int[] ver) {
long maxH = maxConsecutive(hor);
long maxV = maxConsecutive(ver);
return (maxH + 1) * (maxV + 1);
}
which has complexity O(logN)

How to find duplicates in a submatrices of 2d matrix and compare them

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("]", ""));
}

java - slow calculation processing

I try to run this, but it is very slow. Takes ages till it processes and finishes the calculating. Is there anyways I could improve it or make it work faster and more efficiently?
int n = 25;
int len = (int) Math.pow(2, n);
String[][] BinaryNumbers = new String[len][];
int[] DummyArray = new int[n];
int[][] BinaryNumbersInt = new int[len][];
for (int count = 0; count < len; count++) {
BinaryNumbers[count] = String.format("%" + n + "s",
Integer.toBinaryString(count)).replace((" "), ("0"))
.split("");
for (int i = 0; i < n; i++) {
DummyArray[i] = Integer.parseInt(BinaryNumbers[count][i]);
}
BinaryNumbersInt[count] = Arrays.copyOf(DummyArray, DummyArray.length);
}
thanks!
You're doing a lot of useless string manipulation. Try something like this:
for (int count = 0; count < len; count++) {
int[] DummyArray = new int[n];
int x = count;
for (int i = 0; i < n; i++) {
DummyArray[n-i-1] = x & 1;
x >>= 1;
}
BinaryNumbersInt[count] = DummyArray;
}

Sorting with 2D Arrays

I need help with sorting Random numbers into a 2D array. I have to generate 50 random numbers into a column of the array, then sort the numbers in order (ascending or descending). This is what I have so far and am so lost. Please Help.
UPDATED VERSION
public static void main(String[] args)
{
int rows = 2;
int columns = 50;
int[][] anArray = new int[rows][columns];
Random rand = new Random();
for (int i = 0; i < anArray.length; i++)
{
for (int j = 0; j < anArray[0].length; j++)
{
int n = rand.nextInt(100);
anArray[i][j] = n;
}
}
int []temp;
for (int i=0;i<anArray.length;i++)
{
for (int j=0;j<anArray.length-i;j++ )
{
if (anArray[i][j]>anArray[i][j+1])
{
temp =anArray[j];
anArray[j+1]=anArray[j];
anArray[j+1]=temp;
}
}
}
for (int i = 0; i < anArray.length; i++)
{
for (int j=0;j<anArray.length-i;j++ )
{
System.out.println(anArray[i][j]);
}
}
}
}
You can sort 2D arrays on their initial element using a custom Comparator:
Arrays.sort(anArray, new Comparator<int[]>() {
public int compare(int[] lhs, int[] rhs) {
return lhs[0]-rhs[0];
}
});
First of all, you need nested for loops in order to properly insert the random numbers into the two dimensional array. I have also updated my response to show how the sorting should be done. Hope this helps!
EDITED TO SATISFY REQUIREMENTS MENTIONED IN COMMENT BELOW.
import java.util.Arrays;
import java.util.Random;
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
int rows = 2;
int columns = 50;
int[][] anArray = new int[rows][columns];
Random rand = new Random();
//initialize the first row only
for (int j = 0; j < anArray[0].length; j++)
{
int n = rand.nextInt(100);
anArray[0][j] = n;
}
System.out.println("-----------Before the Sort----------------");
for (int i = 0; i < anArray.length; i++)
{
for (int j = 0; j < anArray[0].length; j++)
{
System.out.print(anArray[i][j] + ", "); //format any way you want
}
System.out.println(); //to make each row print on a new line.
}
anArray = mySort(anArray);
System.out.println("-----------After the Sort----------------");
for (int i = 0; i < anArray.length; i++)
{
for (int j = 0; j < anArray[0].length; j++)
{
System.out.print(anArray[i][j] + ", "); //format any way you want
}
System.out.println(); //to make each row print on a new line.
}
}
private static int[][] mySort(int[][] anArray) {
int [][] result = new int[anArray.length][anArray[0].length];
int thisRow[] = getRow(anArray, 0);
Arrays.sort(thisRow);
for(int j = 0; j < thisRow.length; j++){
result[0][j] = anArray[0][j];
result[1][j] = thisRow[j];
}
return result;
}
private static int[] getRow(int[][] anArray, int row) {
int thisRow[] = new int[anArray[row].length];
for(int j = 0; j < anArray[row].length; j++){
thisRow[j] = anArray[row][j];
}
return thisRow;
}
}
You can sort by considering the 2D array 1D. Let's consider a 3x4 array.
1st element's index is 0, 2nd is 1, 3rd is 2, 4th is 3, 5th is 4, etc.
General formula to convert from a 1D index to a 2D:
row_index = _1D_index % nRows;
col_index = _1D_index % nCols;
For example the 5th element has the 1D index of 4, to get the row: 4 % 3 = 1, to get the col, 4 % 4 = 0, so your element is at 1,0. What's the point of all this? Now you can just make a function
int GetAt(int index)
{
return array[index % nRows][index % nCols];
}
and something along the lines of:
void Swap(int index1, int index2)
{
int r1 = index1 % nRows;
int c1 = index1 % nCols;
int r2 = index2 % nRows;
int c2 = index2 % nCols;
int temp = array[r1][c1];
array[r1][c1] = array[r2][c2];
array[r2][c2] = temp;
}
And sort the array as if it was one dimensional :)

Categories