Generate a Matrix with mean of each subarray of each row as an integer
Last Updated :
29 Mar, 2022
Given two integers M and N, the task is to generate an MxN matrix having elements in range [1, MxN] such that the average of any subarray of any row is an integer. If it is not possible to do so, return -1.
Examples:
Input: M = 2, N = 3
Output:
1 3 5
2 4 6
Explanation: Subarrays of first row with size greater than 1 are {1, 3}, {3, 5}, {1, 3, 5}. Means are 2, 4 and 3 respectively.
Subarrays of 2nd row are with size greater than 1 are {2, 4}, {4, 6}, {2, 4, 6}. Means are 3, 5 and 4 respectively.
Input: M = 1, N = 3
Output: -1
Explanation: All Possible arrangements are: {1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}, {3, 1, 2}, {3, 2, 1}.
In every arrangements there is a subarray whose mean is a decimal value and not an integer.
Approach: The solution to the approach is based on the following mathematical observation:
- The size of the subarray must divide the sum of the elements completely for the mean to be an integral value.
- The elements are natural numbers from 1 to M*N.
- The sum of first 'n' odd numbers is equal to n2 and the sum of first 'n' even numbers is equal to n(n+1).
Now suppose from the 1st n odd elements we discard 1st k odd elements and consider the rest as the subarray then:
Total numbers = n
Numbers discarded = k
Numbers in subarray = n - k
Sum of 1st n numbers =n2
Sum of 1st k numbers =k2
Therefore, sum of subarray = n2 - k2
=> mean = (n2 - k2)/(n - k)
= (n + k)*(n - k)/(n - k)
= (n + k), which is an integer as both n and k are integers
Similarly, suppose from the 1st n even elements, discard 1st k even elements and consider the rest as the subarray then:
Total numbers = n
Numbers discarded = k
Numbers in subarray = n - k
Sum of 1st n numbers =n(n + 1)
Sum of 1st k numbers =k(k + 1)
Therefore, sum of subarray = n(n + 1) - k(k + 1)
=> mean = (n(n + 1) - k(k + 1))/(n - k)
= (n2 + n - k2 - k)/(n-k)
= (n2 - k2)/(n - k) + (n-k)/(n-k)
= (n + k)*(n - k)/(n - k) + 1
= (n + k) + 1, which is an integer as both n and k are integers.
Follow the steps mentioned below to implement the above observation:
- From the above observation, arrange in such a manner that each row has either all even numbers or all odd numbers.
- Check if there are equal numbers of odd and even numbers and the MxN must be even.
- If the number of rows is odd then, a valid arrangement is not possible because the odd and even elements cannot be kept together. There will always be at least one row having both odd and even elements.
Below is the implementation of the above approach.
C++
// C++ code to implement the above approach
#include <bits/stdc++.h>
using namespace std;
void validArrangement(int M, int N)
{
// If N == 1 then the only
// subarray possible is of length 1
// therefore, the mean will
// always be an integer
if (N == 1) {
for (int i = 1; i <= M; i++)
cout << i << endl;
return;
}
// If M is odd the valid
// arrangement is not possible
if (M % 2 == 1) {
cout << -1 << endl;
return;
}
// Else print all the rows
// such that all elements of each row
// is either odd or even
else {
// Count for the rows
for (int i = 1; i <= M; i++) {
// Initialize num with i
int num = i;
// Count for the columns
for (int j = 1; j <= N; j++) {
cout << num << " ";
// As M is even,
// even + even will give even
// whereas odd + even gives odd
num += M;
}
cout << endl;
}
return;
}
}
// Driver Code
int main()
{
int M = 2, N = 3;
// Function call
validArrangement(M, N);
return 0;
}
Java
// JAVA code to implement the above approach
import java.util.*;
class GFG {
public static void validArrangement(int M, int N)
{
// If N == 1 then the only
// subarray possible is of length 1
// therefore, the mean will
// always be an integer
if (N == 1) {
for (int i = 1; i <= M; i++)
System.out.println(i);
return;
}
// If M is odd the valid
// arrangement is not possible
if (M % 2 == 1) {
System.out.println(-1);
return;
}
// Else print all the rows
// such that all elements of each row
// is either odd or even
else {
// Count for the rows
for (int i = 1; i <= M; i++) {
// Initialize num with i
int num = i;
// Count for the columns
for (int j = 1; j <= N; j++) {
System.out.print(num + " ");
// As M is even,
// even + even will give even
// whereas odd + even gives odd
num += M;
}
System.out.println();
}
return;
}
}
// Driver Code
public static void main(String[] args)
{
int M = 2, N = 3;
// Function call
validArrangement(M, N);
}
}
// This code is contributed by Taranpreet
Python3
# Python3 code to implement the above approach
def validArrangement(M, N):
# If N == 1 then the only
# subarray possible is of length 1
# therefore, the mean will
# always be an integer
if (N == 1):
for i in range(1, M + 1):
print(i)
return
# If M is odd the valid
# arrangement is not possible
if (M % 2 == 1):
print(i)
return
# Else print all the rows
# such that all elements of each row
# is either odd or even
else :
# Count for the rows
for i in range(1,M+1):
# Initialize num with i
num = i
# Count for the columns
for j in range(1,N+1):
print(num,end=" ")
# As M is even,
# even + even will give even
# whereas odd + even gives odd
num += M
print("")
return
# Driver Code
M = 2
N = 3
# Function call
validArrangement(M, N)
# This code is contributed by shinjanpatra
C#
// C# code to implement the above approach
using System;
public class GFG
{
public static void validArrangement(int M, int N)
{
// If N == 1 then the only
// subarray possible is of length 1
// therefore, the mean will
// always be an integer
if (N == 1) {
for (int i = 1; i <= M; i++)
Console.WriteLine(i);
return;
}
// If M is odd the valid
// arrangement is not possible
if (M % 2 == 1) {
Console.WriteLine(-1);
return;
}
// Else print all the rows
// such that all elements of each row
// is either odd or even
else {
// Count for the rows
for (int i = 1; i <= M; i++) {
// Initialize num with i
int num = i;
// Count for the columns
for (int j = 1; j <= N; j++) {
Console.Write(num + " ");
// As M is even,
// even + even will give even
// whereas odd + even gives odd
num += M;
}
Console.WriteLine();
}
return;
}
}
// Driver Code
public static void Main(String[] args) {
int M = 2, N = 3;
// Function call
validArrangement(M, N);
}
}
// This code is contributed by shikhasingrajput
JavaScript
<script>
// JavaScript code to implement the above approach
function validArrangement(M, N)
{
// If N == 1 then the only
// subarray possible is of length 1
// therefore, the mean will
// always be an integer
if (N == 1) {
for (let i = 1; i <= M; i++)
document.write(i);
return;
}
// If M is odd the valid
// arrangement is not possible
if (M % 2 == 1) {
document.write(-1);
return;
}
// Else print all the rows
// such that all elements of each row
// is either odd or even
else {
// Count for the rows
for (let i = 1; i <= M; i++) {
// Initialize num with i
let num = i;
// Count for the columns
for (let j = 1; j <= N; j++) {
document.write(num," ");
// As M is even,
// even + even will give even
// whereas odd + even gives odd
num += M;
}
document.write("</br>");
}
return;
}
}
// Driver Code
let M = 2, N = 3;
// Function call
validArrangement(M, N);
// This code is contributed by shinjanpatra
</script>
Time Complexity: O(MxN)
Auxiliary Space: O(1)
Similar Reads
Program to find the Sum of each Row and each Column of a Matrix Given a matrix mat of size m à n, the task is to compute the sum of each row and each column of the matrix.Examples:Input: mat = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16] ] Output: Sum of row 0 = 10 Sum of row 1 = 26 Sum of row 2 = 42 Sum of row 3 = 58 Sum of column 0 = 28 Sum
7 min read
Count of Subarrays of given Array with median at least X Given an array arr[]of integers with length N and an integer X, the task is to calculate the number of subarrays with median greater than or equal to the given integer X. Examples: Input: N=4, A = [5, 2, 4, 1], X = 4Output: 7Explanation: For subarray [5], median is 5. (>= 4)For subarray [5, 2], m
9 min read
Sum of Matrix where each element is sum of row and column number Given two numbers M and N denoting the number of rows and columns of a matrix A[] where A[i][j] is the sum of i and j (indices follow 1 based indexing), the task is to find the sum of elements of the matrix. Examples: Input: M = 3, N = 3Output: 36Explanation: A[]: {{2, 3, 4}, {3, 4, 5}, {4, 5, 6}}.
14 min read
Generate a matrix having each element equal to the sum of specified submatrices of a given matrix Given a matrix mat[][] of dimensions M*N and an integer K, the task is to generate a matrix answer[][], where answer[i][j] is equal to the sum of all elements mat[r][c][/c] such that r â [i - K, i + K], c â [j - K, j + K], and (r, c) is a valid position in the matrix. Examples: Input: mat = {{1, 2,
15+ min read
Count of subarrays of size K with average at least M Given an array arr[] consisting of N integers and two positive integers K and M, the task is to find the number of subarrays of size K whose average is at least M. Examples: Input: arr[] = {2, 3, 3, 4, 4, 4, 5, 6, 6}, K = 3, M = 4Output: 4Explanation:Below are the subarrays of size K(= 3) whose aver
7 min read
Enlarge a Matrix such that each element occurs in R rows and C columns Given a matrix arr[][] of size N x M, and two numbers R and C, the task is to enlarge this matrix such that each element of the original matrix occurs in R rows and C columns in the enlarged matrix. Examples: Input: arr[][] = {{1, 2, 3}, {4, 5, 6}} R = 3, C = 2 Output: 1 1 2 2 3 3 4 4 5 5 6 6 1 1 2
9 min read
Generate a matrix having even sum of all diagonals in each 2 x 2 submatrices Given a positive integer N, the task is to construct a matrix of size N * N such that all the matrix elements are distinct from the range [1, N2] and the sum of elements in both the diagonals of every 2 * 2 submatrices is even. Examples: Input: N = 3 Output: 1 2 3 4 5 6 7 8 9 Explanation: Diagonal e
7 min read
Mean of array generated by products of all pairs of the given array Given an array arr[] consisting of N integers, the task is to find the mean of the array formed by the products of unordered pairs of the given array. Examples: Input: arr[] = {2, 5, 7}Output: 19.67Explanation:Product of unordered pairs of array arr[] are 2 * 5 = 10, 2 * 7 = 14 and 5 * 7 = 35.Theref
12 min read
Find mean of subarray means in a given array You are given an array of n-elements you have to find the mean of the array as mean of all consecutive m-elements of array for all possible m-length array with consecutive elements. Examples: Input :arr[] = {3, 5, 1, 8, 9, 4}, m = 4 Output : Mean = 5.16667 Explanation : {3, 5, 1, 8}, {5, 1, 8, 9}, {
6 min read
Swapping Two Elements in Each Row of a Matrix Without Loop in MATLAB A Matrix is a two-layered cluster of numbers. In MATLAB, we can create a Matrix by entering components in each line as comma or space-delimited numbers and also, utilizing semicolons to stamp the finish of each line. Approach:Step 1: Pick 2 elements in a row using logical()Step 2: Get all possible C
2 min read