Wednesday 16 September 2015

Factset Question: Subarray of k Size from a Array that has given Mean

/*
C program: print a sub-array b of size k that have mean m from a 
given array a of size n.

Description: Question asked in written (codding) test of FactSet
recruitment drive at NIT Durgapur Campus on September 14, 2016.

Example 1: int a[] = {1,2,3,4,5,6,7,8,9,0}, k = 4, m = 6
then b will be b[] = {7,8,9,0} and should print 7 8 9 0

Compiler: GNU GCC v4.8.3

Author: Mangilal Sharma (with Ramesh Kumar Thakur)

Date: September 15, 2015

Program for: world-of-c-programming.blogpost.com

Program number: 103
*/

#include <stdio.h>
#define SIZE 20
void findMeanSubarray(int a[], int k, int m, int n);

int main()
{
    int a[] = {1,2,3,4,5,6,7,8,9,0}, k = 4, m = 6;
    int n = sizeof(a)/sizeof(a[0]);
    findMeanSubarray(a,k,m,n);
    return 0;
}
//Only the following function code required to write in test.
void findMeanSubarray(int a[], int k, int m, int n)
{
 int b[SIZE], i, j, flag = 0, sum;
 for(i=0;i<=n-k+1;i++)
 {
  sum=0;
  for(j=0;j<k;j++) sum+= a[i+j];
  if(sum == m*k) break;
 }
 if(i<=n-k) for(j=i;j<i+k;j++) printf("%d\t",a[j]);
 else printf("Has not found any required subarray in given array.\n");
}
You can test program on this online c editor & compiler: http://www.tutorialspoint.com/compile_c_online.php