I need to write a recursive method that multiplies 2 square matrices (size n-by-n).
It needs to run in theta(N^3) time but it's not Strassen's algorithm.
I've written a method but I am getting a stack overflow.
Matrix A is Matrix B is
1 2 1 0 3 2 3 0
2 3 2 0 2 1 2 0
1 2 1 0 3 2 3 0
The two matrices are both int[][]. here is the code I have written:
public int[][] ncubed(int [][]A, int [][]B){
int w = A.length;
int [][] C = new int[w][w];
if (w==1){
C[0][0] = A[0][0] * B[0][0];
}
else{
int [][]A1 = partition(1,A);
int [][]A2 = partition(2,A);
int [][]A3 = partition(3,A);
int [][]A4 = partition(4,A);
int [][]B1 = partition(1,B);
int [][]B2 = partition(2,B);
int [][]B3 = partition(3,B);
int [][]B4 = partition(4,B);
int [][]C1 = partition(1,C);
int [][]C2 = partition(2,C);
int [][]C3 = partition(3,C);
int [][]C4 = partition(4,C);
C1 = add(ncubed(A1,B1),ncubed(A2,B3));
C2 = add(ncubed(A1,B2),ncubed(A2,B4));
C3 = add(ncubed(A3,B1),ncubed(A4,B3));
C4 = add(ncubed(A3,B2),ncubed(A4,B4));
join(C1, C, 0 , 0);
join(C2, C, w/2 , 0);
join(C3, C, 0, w/2);
join(C4, C, w/2, w/2);
}
return C;
}
public int [][] partition(int quadrant, int[][] array){
int n = array.length;
int[][] Q = new int[array.length][array.length];
if(quadrant>4 || quadrant<1) return null;
switch(quadrant){
case(1):
for(int i = 0; i<(n/2); i++){
for(int j = 0; j<(n/2); j++){
Q[i][j] = array[i][j];
}
}
break;
case(2):
for(int i = n/2; i<n; i++){
for(int j = 0; j<(n/2); j++){
Q[i][j] = array[i][j];
}
}
break;
case(3):
for(int i = 0; i<(n/2); i++){
for(int j = (n/2); j<n; j++){
Q[i][j] = array[i][j];
}
}
break;
case(4):
for(int i = (n/2); i<n; i++){
for(int j = (n/2); j<n; j++){
Q[i][j] = array[i][j];
}
}
break;
}
return Q;
}
The methods add and join work fine because I've tested them so it's not in that part.
I just can't figure out my problem in the actual ncubed method(the matrix multiply method).
If anyone is able to help me understand something I'm doing incorrectly or show me another way to do this with the specifications stated at the top, that would be awesome. Thanks for any help.
The naive method will give you theta(n^3) time -- have you checked out something simpler?
Failing that, have you looked at these similar questions?
Related
I was doing an assessment for job interview. One of the 3 problems that I had to solve in an hour was finding the maximal value in a grid where you traverse it and add 1 to the elements based on the coordinates given. I spent a little to much time on the second problem and only ended up with about 20 minutes for this one. I didn't finish it in time so it's bugging me.
I just want to make sure that the solution to the problem as I remember it is optimized.
The input is a String array of two int values and the dimension of the grid.
To illustrate, if the coordinates given are (3,2) (2,2) (1,3) then
[1][1][0]
[1][1][0]
[1][1][0]
[1][1][0]
[2][2][0]
[2][2][0]
[1][1][0]
[2][2][0]
[3][3][1]
and so on...
I believe the required result was the maximal value that is not in (1,1) and the number of times it exists in the grid.
This is the the solution I came up with. Is there any way to optimize it?
public static List<Integer> twoDimensions(String[] coordinates, int n) {
List<Integer> maxAndCount = new ArrayList<Integer>();
int[][] grid = new int[n][n];
int arrLength = coordinates.length;
int max = Integer.MIN_VALUE;
int count = 1;
for (int i = 0; i < arrLength; i++) {
String[] coors = coordinates[i].split(" ");
int row = Integer.parseInt(coors[0]);
int column = Integer.parseInt(coors[1]);
for (int j = 0; j < row; j++) {
for (int k = 0; k < column; k++) {
grid[j][k] += 1;
System.out.println("grid (" + j + "," + k + "): " + grid[j][k]);
if (!(j == 0 & k == 0) && grid[j][k] > max) {
max = grid[j][k];
count = 1;
} else if (grid[j][k] == max) {
count++;
}
}
}
}
maxAndCount.add(max);
maxAndCount.add(count);
return maxAndCount;
}
public static void main(String[] args) {
String[] coors = { "1 3", "2 4", "4 1", "3 2" };
System.out.println("The Max and count Are:" + twoDimensions(coors, 4).toString());
}
Other solution for exercise is. (erikdhv#gmail.com)
public static long countMax(List<String> upRight) {
// Write your code here
int xl = 1;
int yl = 1;
xl = Integer.parseInt(upRight.get(1).split(" ")[0]);
yl = Integer.parseInt(upRight.get(1).split(" ")[1]);
for (int i=0; i<upRight.size(); i++){
if (xl > Integer.parseInt(upRight.get((int) i).split(" ")[0]) ) xl = Integer.parseInt(upRight.get((int) i).split(" ")[0]);
if (yl > Integer.parseInt(upRight.get((int) i).split(" ")[1])) yl = Integer.parseInt(upRight.get((int) i).split(" ")[1]);
}
return (yl * xl);
}
This fails a few test cases I can think of, the value of XL should be on Index 0 not 1
Answer of erik fails for few test cases, just change int to long for xl and yl and boom... all test cases passed.
public static long twoDimensions(List<String> list, int n) {
long res = 0;
int rowCount =0,colCount=0;
for(int i=0;i<n;i++)
{
int row = list.get(i).charAt(0) - 48;
int col = list.get(i).charAt(2) - 48;
if(row > rowCount)
rowCount = row;
if(col >colCount)
colCount = col;
}
int tempArr[][] = new int[rowCount+1][colCount+1];
for(int i = 0;i<n;i++)
{
int row = list.get(i).charAt(0) - 48;
int col = list.get(i).charAt(2) - 48;
for(int j=row;j>=1;j--)
{
int m = j;
for(int k=1;k<=col;k++)
{
tempArr[m][k]= tempArr[m][k]+1;
if(tempArr[m][k]>res)
res = tempArr[m][k];
}
}
System.out.println("for row: "+row+" col: "+col);
for(int j = 0;j<=rowCount;j++)
{
for(int k=0;k<=colCount;k++)
{
System.out.print(""+tempArr[j][k]);
}
System.out.println("");
}
System.out.println("");
}
return res;
}
I have this line of code to create a zigzag array, its fairly simple and I already have the code for it. here's the summary of the question:
This method creates and returns a new two-dimensional integer array, which in Java is really just a one-dimensional array whose elements are one-dimensional arrays of type int[]. The returned array must have the correct number of rows that each have exactly cols columns. This array must contain the numbers start, start + 1, ..., start + (rows * cols - 1) in its rows in order, except that the elements in each odd-numbered row must be listed in descending order.
For example, when called with rows = 4, cols = 5 and start = 4, this method should create and return the two-dimensional array whose contents are
4 5 6 7 8
13 12 11 10 9
14 15 16 17 18
23 22 21 20 19
I've tried talking with my colleagues but they can't spot the problem too
public class P2J1
{
public static int[][] createZigZag(final int rows, final int cols, int start)
{
final int[][] array = new int[rows][cols];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
array[i][j] = start;
start++;
}
}
return array;
}
}
/// heres the tester program
#Test public void testCreateZigZag() {
Random rng = new Random(SEED);
CRC32 check = new CRC32();
for(int i = 0; i < TRIALS; i++) {
int rows = rng.nextInt(20) + 1;
int cols = rng.nextInt(20) + 1;
int start = rng.nextInt(100);
int[][] zig = P2J1.createZigZag(rows, cols, start);
assertEquals(rows, zig.length);
for(int j = 0; j < rows; j++) {
assertEquals(cols, zig[j].length);
for(int e: zig[j]) { check.update(e); }
}
}
assertEquals(3465650385L, check.getValue());
}
Your column index always goes from 0 to cols-1, in that order. You need to alternate the order every other row.
You can do this by using variables for the start, end, and increment of the inner loop and assign those variables based on the row index being odd or even.
Something like this (untested):
public static int[][] createZigZag(final int rows, final int cols, int start) {
final int[][] array = new int[rows][cols];
for (int i = 0; i < rows; i++) {
boolean backwards = ((i & 1) == 1);
final int jStart = backwards ? cols-1 : -1;
final int jEnd = backwards ? 0 : cols;
final int jStep = backwards ? -1 : 1;
for (int j = jStart; j != jEnd; j += jStep) {
array[i][j] = start;
start++;
}
}
return array;
}
You could also just write two different inner loops, selected on the same condition. One would fill starting from 0, the other would fill starting from cols-1 and going backwards.
public static int[][] createZigZag(final int rows, final int cols, int start) {
final int[][] array = new int[rows][cols];
for (int i = 0; i < rows; i++) {
if ((i & 1) == 1) {
for (int j = cols-1; j >= 0; j--) {
array[i][j] = start;
start++;
}
} else {
for (int j = 0; j < cols; j++) {
array[i][j] = start;
start++;
}
}
}
return array;
}
I'm trying to make an algorithm in java that makes an unsigned multiplication. This algorithm, then, make use of an unsigned sum. This is the code:
public int[] unsignedSum(int[] n1, int[] n2){
int[] result = new int[48];
int carry = 0;
for(int x = 47; x >= 0; x--){
if (n1[x]+n2[x]+carry == 1){
result[x] = 1;
carry = 0;
}
else if (n1[x]+n2[x]+carry == 2)
carry = 1;
else if (n1[x]+n2[x]+carry == 3)
result[x] = 1;
}
return result;
}
public int[] unsignedMult(int[] n1, int[] n2){
int[] result = new int[48];
int[] N1 = new int[48];
int[] N2 = new int[48];
//fix the size to 48
for (int x = 24; x < 48; x++){
N1[x] = n1[x-24];
N2[x] = n2[x-24];
}
for(int x = 47; x >= 0; x--){
if (N2[x] == 1){
int[] shiftedN1 = new int[48];
for (int y = 0; y < x; y++)
shiftedN1[y] = N1[y+48-x];
result = unsignedSum(result, shiftedN1);
}
}
return result;
}
Vectors n1 and n2 have size 24
any other vector have size 48
the problem is: it's eating the first number in some cases.
the multiplication should never overflow, but in this case, it does somehow.
1100000...(24bits) * 1100000(24bits).. should result in 10010000...(48 bits), but it's resulting in 00100000...(48 bits)
Look for 2 off-by-one errors in
for (int y = 0; y < x; y++)
shiftedN1[y] = N1[y+48-x];
What is exactly the off-by-one errors in the while loop?
You may want to run the above loop by hand with simple case of ....0001 * ....0001
I'm trying to write a method that calculates the exponential of a square matrix. In this instance, the matrix is a square array of value:
[1 0]
[0 10]
and the method should return a value of:
[e 0]
[0 e^10]
However, when I run my code, I get a range of values depending on what bits I've rearranged, non particularly close to the expected value.
The way the method works is to utilise the power series for the matrix, so basically for a matrix A, n steps and an identity matrix I:
exp(A) = I + A + 1/2!*AA + 1/3!*AAA + ... +1/n!*AAA..
The code follows here. The method where I'm having the issue is the method exponential(Matrix A, int nSteps). The methods involved are enclosed, and the Matrix objects take the arguments (int m, int n) to create an array of size double[m][n].
public static Matrix multiply(Matrix m1, Matrix m2){
if(m1.getN()!=m2.getM()) return null;
Matrix res = new Matrix(m1.getM(), m2.getN());
for(int i = 0; i < m1.getM(); i++){
for(int j = 0; j < m2.getN(); j++){
res.getArray()[i][j] = 0;
for(int k = 0; k < m1.getN(); k++){
res.getArray()[i][j] = res.getArray()[i][j] + m1.getArray()[i][k]*m2.getArray()[k][j];
}
}
}
return res;
}
public static Matrix identityMatrix(int M){
Matrix id = new Matrix(M, M);
for(int i = 0; i < id.getM(); i++){
for(int j = 0; j < id.getN(); j++){
if(i==j) id.getArray()[i][j] = 1;
else id.getArray()[i][j] = 0;
}
}
return id;
}
public static Matrix addMatrix(Matrix m1, Matrix m2){
Matrix m3 = new Matrix(m1.getM(), m2.getN());
for(int i = 0; i < m3.getM(); i++){
for(int j = 0; j < m3.getN(); j++){
m3.getArray()[i][j] = m1.getArray()[i][j] + m2.getArray()[i][j];
}
}
return m3;
}
public static Matrix scaleMatrix(Matrix m, double scale){
Matrix res = new Matrix(m.getM(), m.getN());
for(int i = 0; i < res.getM(); i++){
for(int j = 0; j < res.getN(); j++){
res.getArray()[i][j] = m.getArray()[i][j]*scale;
}
}
return res;
}
public static Matrix exponential(Matrix A, int nSteps){
Matrix runtot = identityMatrix(A.getM());
Matrix sum = identityMatrix(A.getM());
double factorial = 1.0;
for(int i = 1; i <= nSteps; i++){
sum = Matrix.multiply(Matrix.scaleMatrix(sum, factorial), A);
runtot = Matrix.addMatrix(runtot, sum);
factorial /= (double)i;
}
return runtot;
}
So my question is, how should I modify my code, so that I can input a matrix and a number of timesteps to calculate the exponential of said matrix after said timesteps?
My way to go would be to keep two accumulators :
the sum, which is your approximation of exp(A)
the nth term of the series M_n, that is A^n/n!
Note that there is a nice recursive relationship with M_n: M_{n+1} = M_n * A / (n+1)
Which yields :
public static Matrix exponential(Matrix A, int nSteps){
Matrix seriesTerm = identityMatrix(A.getM());
Matrix sum = identityMatrix(A.getM());
for(int i = 1; i <= nSteps; i++){
seriesTerm = Matrix.scaleMatrix(Matrix.multiply(seriesTerm,A),1.0/i);
sum = Matrix.addMatrix(seriesTerm, sum);
}
return sum;
}
I totally understand the sort of thrill that implementing such algorithms can give you. But if this is not a hobby project, I concur that you should that you should use a library for this kind of stuff. Making such computations precise and efficient is really not a trivial matter, and a huge wheel to reinvent.
Is there a way to parse 2 dimensional array like this into a rectangle object (x,y, width, height)?. I need the array of all possible rectangles...
{0,0,0,0,0}
{0,0,0,0,0}
{0,1,1,0,0}
{0,1,1,0,0}
{0,0,0,0,0}
This would give 4 rectangles (we are looking at 0):
0,0,5,2
0,0,1,5
3,0,2,5
0,5,5,1
I have tried something like this, but it only gives the area of the biggest rectangle...
public static int[] findMaxRectangleArea(int[][] A, int m, int n) {
// m=rows & n=cols according to question
int corX =0, corY = 0;
int[] single = new int[n];
int largeX = 0, largest = 0;
for (int i = 0; i < m; i++) {
single = new int[n]; // one d array used to check line by line &
// it's size will be n
for (int k = i; k < m; k++) { // this is used for to run until i
// contains element
int a = 0;
int y = k - i + 1; // is used for row and col of the comming
// array
int shrt = 0, ii = 0, small = 0;
int mix = 0;
int findX = 0;
for (int j = 0; j < n; j++) {
single[j] = single[j] + A[k][j]; // postions element are
// added
if (single[j] == y) { // element position equals
shrt = (a == 0) ? j : shrt; // shortcut
a = a + 1;
if (a > findX) {
findX = a;
mix = shrt;
}
} else {
a = 0;
}
}
a = findX;
a = (a == y) ? a - 1 : a;
if (a * y > largeX * largest) { // here i am checking the values
// with xy
largeX = a;
largest = y;
ii = i;
small = mix;
}
}
}// end of loop
return largeX * largest;
}
this code is working with 1s, but that is not the point right now