Matrix in diagonal order using array list only - list

Encountered this problem on hackerrank ,
Please guide on how to print a matrix diagonally in 2D array using ArrayList only.
Here is my code below:
public static List<Integer> downwardDigonal(List<List<Integer>> matrix, int n) {
for (int slice = 0; slice < 2 * n - 1; ++slice) {
int z = (slice < n) ? 0 : slice - n + 1;
for (int j = z; j <= slice - z; ++j) {
matrix.get(j).get(slice-j) ;
}
}
return matrix;
}

Related

Magical Subarrays in an Array

Can someone explain how to solve the question below, Much appreciated!
Given an integer array[] of size n, your task is to count the number of magical subarrays in the arr.
Here any subarray array[l…r] is considered to be magical if it satisfies the magical condition.
it should contain an even number(non zero) of odd numbers
More Formally the count of odd numbers in the subarray should be even and should be greater than 0
Constraints
1<=n<=10^5
1<=array[i]<=2*(10)^5
#TestCase 1;
Input:
n=4
array[]={2,1,2,3}
output:2
the magical subarrays are: {2,1,2,3} , {1,2,3}
#Testcase 2
n=6
array[]={1,2,5,2,3,7}
output:7
the magical subarrays are:{1,2,5}, {1,2,5,2}, {2,5,2,3}, {5,2,3}, {2,3,7}, {3,7}, {1,2,5,2,3,7}
The code below gives TLE for the above constraints
long long magicalSubarrays(int n,vector<int> arr)
{
vector<int> O;
for (int i = 0; i < arr.size(); i++) {
if (arr[i] % 2 == 1) {
O.push_back(i);
}
}
int k=O.size();
long long sum = 0;
for (int i = 0; i < O.size(); i++) {
for (int j = i + 1; j < O.size(); j += 2) {
int left = (i-1<0)? O[i]: O[i]-1-O[i-1];
int right= (j+1>=k)? n-1-O[j]: O[j+1]-1-O[j];
sum += (1 + left) * (1 + right);
}
}
return sum;
}
Let O be the array that contains all indices of odd elements.
Every magical subarray must then consist of:
every number from O[i] to O[j] inclusive (where j = i+1+2*k for some k)
an arbitrary number of even items left of i
an arbitrary number of even items right of j
Or, in C++-flavored pseudocode:
int magical_subarrays(const std::vector<int>& arr) {
std::vector<size_t> O;
for (int i = 0; i < arr.length(); i++) {
if (arr[i] % 2 == 1) {
O.push_back(i);
}
}
int sum = 0;
for (int i = 0; i < O.length(); i++) {
for (int j = i + 1; j < O.length(); j += 2) {
int left = /* exercise for the reader. It involves O[i] and O[i-1]. */
int right = /* exercise for the reader. It involves O[j] and O[j+1]. */
sum += (1 + left) * (1 + right);
}
}
return sum;
}

Define matrices in an array element C++

I have written some c++ code that receives a Matrix as input and now I want to create a 2D array with matrices in each element so that I can send the individual matrices to the function.
typedef vector< vector > Matrix;
double a[2][2] = Matrix(2, vector(2));
so that each element of a is a 2x2 Matrix.
The reason I don't want to just create a 4D array with vectors is that I want to keep all of the original functions that I have already created with matrices as input.
Any way this is possible?
Here is a simple example code...
#include <stdio.h>
#include <iostream>
#include <time.h>
#include <vector>
typedef vector< vector > Matrix;
void test2D_array(int l, int m, Matrix &a, Matrix &b) {
int R = l - 1;
for (int i = 0; i < m+1; i++) {
b[l - 1][i] = a[l][i];
b[l - 2][i] = (l - 1) * a[l - 1][i];
for (int k = R-1; k > 0; k--) {
b[k - 1][i] = b[k + 1][i] + a[k][i];
}
}
}
int main(void) {
Matrix a(2, vector<double>(2));
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
a[i][j] = 1;
}
}
Matrix b(2, vector<double>(2));
test2D_array(2, 2, a, b);
// What I want to accomplish...
// Matrix a[2][2] = Matrix((2, vector<double>(2)); i.e. 4D array with each element a 2x2 matrix
// for (int i = 0; i < 2; i++) {
// for (int j = 0; j < 2; j++) {
// test2D_array(2, 2, a[i][j], b);
// }
//}
//
return 0;
}

Why reserving space with std::vector runs slower?

I created the following function: given a m * n matrix of ones and zeros, it return how many square submatrices have all ones
For example
Input: matrix =
[
[0,1,1,1],
[1,1,1,1],
[0,1,1,1]
]
Output: 15
Explanation:
There are 10 squares of side 1.
There are 4 squares of side 2.
There is 1 square of side 3.
There is the program without reserving space.
int countSquares(vector<vector<int>>& matrix)
{
const size_t rows{ matrix.size() }, cols{ matrix[0].size() }; //Get the number of rows and colums
//Creating a dynamic programing matrix
vector<vector<int>> dp(rows, vector<int>(cols)); //Initializing m * n elements (this should be slower than reserving without initializing)
dp[0][0] = matrix[0][0];
size_t count = dp[0][0]; //counter of the squares
for (size_t i{ 1 }; i < rows; ++i)
count += dp[i][0] = matrix[i][0]; //Count squares in the first row and update the dynamic programming first row
for (size_t i{ 1 }; i < cols; ++i)
count += dp[0][i] = matrix[0][i]; //Count squares in the first colums and update the dynamic programming first column
//Count the rest of squares and update the dynamic programming matrix
for (size_t i{ 1 }; i < rows; ++i)
for (size_t j{ 1 }; j < cols; ++j)
count += dp[i][j] = matrix[i][j] ? min({ dp[i - 1][j], dp[i - 1][j - 1], dp[i][j - 1] }) + 1 : 0;
return count;
}
This is exactly the same program but without initialization the dynamic programming matrix at construction and reserving all space before use
int countSquares(vector<vector<int>>& matrix)
{
const size_t rows{ matrix.size() }, cols{ matrix[0].size() }; //Get the number of rows and colums
//Creating a dynamic programing matrix
vector<vector<int>> dp; //This time without default initialization
dp.reserve(rows);
dp.push_back(vector<int>());
dp.back().reserve(cols);
dp.back().push_back(matrix[0][0]);
size_t count = dp[0][0];
//Count squares in the first row and update the dynamic programming first row
for (size_t i{ 1 }; i < rows; ++i)
{
dp.push_back(vector<int>());
dp.back().reserve(cols);
dp.back().push_back(matrix[i][0]);
count += dp.back().back();
}
//Count squares in the first colums and update the dynamic programming first column
for (size_t i{ 1 }; i < cols; ++i)
{
dp[0].push_back(matrix[0][i]);
count += dp[0].back();
}
//Count the rest of squares and update the dynamic programming matrix
for (size_t i{ 1 }; i < rows; ++i)
for (size_t j{ 1 }; j < cols; ++j)
{
dp[i].push_back(matrix[i][j] ? min({ dp[i - 1][j], dp[i - 1][j - 1], dp[i][j - 1] }) + 1 : 0);
count += dp[i].back();
}
return count;
}
Why the first option runs 50% faster ??
Update 1: I timed my functions with std::chrono::system_clock::now() in visual studio (creating a really long matrix) and also using this page :
https://leetcode.com/problems/count-square-submatrices-with-all-ones/
the first option runs at 90% and the second one at 40%

Dynamic array size to calculate the determinant of a matrix

Basically, I have written a program to calculate the determinant of a matrix.
However, this feels like quite static yet (i.e. the dimension is passed as an argument). Is there any way to make it more dynamic (without vectors) with something like pointers?
#include <bits/stdc++.h>
using namespace std;
#define N 4
void getCofactor(int mat[N][N], int temp[N][N], int p, int q, int n)
{
int i = 0, j = 0;
for (int row = 0; row < n; row++)
{
for (int col = 0; col < n; col++)
{
if (row != p && col != q)
{
temp[i][j++] = mat[row][col];
if (j == n - 1)
{
j = 0;
i++;
}
}
}
}
}
int determinantOfMatrix(int mat[N][N], int n)
{
int D = 0;
if (n == 1)
return mat[0][0];
int temp[N][N];
int sign = 1;
for (int f = 0; f < n; f++)
{
getCofactor(mat, temp, 0, f, n);
D += sign * mat[0][f] * determinantOfMatrix(temp, n - 1);
sign = -sign;
}
return D;
}
There is no way to pass a pointer to an array of dynamic size. And the inner dimensions of an array cannot be dynamic anyway.
What you can do instead is use a one dimensional dynamic array, pass pointer to element of that array as usual, and store the rows one after the other, and calculate the index based on the row size passed as an array. This results in the same layout as an array of arrays would have, but the "virtual" dimensions can be dynamic.

Multiply 2-D array

I am fairly new to C++ programming language. Currently, what I am trying to accomplish is getting a short* input from MATLAB, creating its transpose and multiplying. I am having problems when I try to multiply. I am getting h_raw from MATLAB and doing some computation to get sh_data. This looks correct. Next, I am creating a transpose dst which is also correct. Finding the covariance matrix is giving me troubles. This covariance matrix should be MATALB equivalent to cov_matrix=sh_data * sh_data'; Any help is appreciated!
for (int numEl = 0; numEl < elements; numEl++) {
int shift_idx = tof[1 + (1 * pix_x * numEl)];
for (int sdex = 0; sdex < shift_idx; sdex++) {
for (int p = 0; p < nrows; p++) {
sh_data[p + (numEl*nrows)] = h_raw[(p + sdex) + (numEl*nrows)];
}
}
}
// finding the transpose
for (int n = 0; n < nrows*ncols; n++) {
int i = n / ncols;
int j = n % ncols;
dst[n] = sh_data[nrows*j + i];
}
// calculating the covariance matrix
for (int nel = 0; nel < elements; nel++) {
for (int k = 0; k < nrows; k++) {
cov_matrix[(nel*elements)+nel] += dst[(k*elements)+nel] * sh_data[k+(nel*nrows)];
}
}