Function getMatrixFromArrays

Function getMatrixFromArrays: The function/method getMatrixFromArrays accepts four arguments Marr1N and arr2. M represents the size of the integer array arr1. N represents the size of the integer array arr2.

The function/method getMatrixFromArrays must return a double pointer representing an integer matrix based on the following conditions.
– The matrix to be formed is always a square matrix because the sum of M and N is always a perfect square.
– The square matrix must be filled with all the integers from the array arr1 followed by the array arr2 in the order of their occurrence (starting from the 1st row, where left to right in each row).

Your task is to implement the function getMatrixFromArrays so that it passes all the test cases.

IMPORTANT: Do not write the main() function as it is already defined.

Example Input/Output 1:
Input:
5
10 20 30 40 50
4
99 88 77 66

Output:
Matrix:
10 20 30
40 50 99
88 77 66

Explanation:
Here M = 5 and N = 4.
The sum 5 and 4 is 9, which is a perfect square.
So the size of the square matrix is 3×3.
After filling the square matrix with the integers from the given two arrays, the matrix becomes
10 20 30
40 50 99
88 77 66

Example Input/Output 2:
Input:
7
1 2 3 4 5 6 7
9
10 20 30 40 50 60 70 80 90

Output:
Matrix:
1 2 3 4
5 6 7 10
20 30 40 50
60 70 80 90

#include <stdio.h>
#include <stdlib.h>
int** getMatrixFromArrays(int M, int arr1[], int N, int arr2[])
{
    int x=sqrt(M+N),i,j,k=0,f=0;
    int **a=malloc(sizeof(int*)*x);
    for(i=0;i<x;i++)
    {
        a[i]=malloc(sizeof(int)*x);
    for(j=0;j<x;j++)
    {
        if(f==0)
        {
            a[i][j]=arr1[k];
            k++;
            if(k==M)
            {
            f=1;
            k=0;
            }
        }
        else
        {
            a[i][j]=arr2[k++];
        }
    }
    }
    return a;
}
int main()
{
    int M, N;
    scanf("%d", &M);
    int arr1[M];
    for(int index = 0; index < M; index++)
    {
        scanf("%d", &arr1[index]);
    }
    scanf("%d", &N);
    int arr2[N], SIZE = sqrt(M+N);
    for(int index = 0; index < N; index++)
    {
        scanf("%d", &arr2[index]);
    }
    int **newMatrix = getMatrixFromArrays(M, arr1, N, arr2);
    printf("Matrix:n");
    for(int row = 0; row < SIZE; row++)
    {
        for(int col = 0; col < SIZE; col++)
        {
            printf("%d ", newMatrix[row][col]);
        }
        printf("n");
    }
    return 0;
}
Previous Article

Python Test : Variable names

Next Article

Swap Every Two Vowels

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *