# 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 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 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 ` `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

 ``

Output

```1 3 5
2 4 6 ```

Time Complexity: O(MxN)
Auxiliary Space: O(1)

My Personal Notes arrow_drop_up
Related Articles