Corporate Median Group - Solution for Coding Challenge by Capgemini

Niladri.Biswas
Posted by in C# category on for Beginner level | Points: 250 | Views : 3900 red flag

Recently, Capgemini, has launced a coding contest. This article will show the solution as proposed by myself for level 1.

Introduction

Recently, Capgemini, has launced a coding contest.This article will show the solution of the first level coding challenge.The challenge(s) can be found here.

The Challenge Question - Level 1

Solution

The below is the solution in C#

using System;
using System.Linq;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            var input1 = new int[] { 2, 7, 9, 12, 15, 17, 19, 23, 25, 27, 30 };
            var input2 = new int[] { 2, 5, 8, 10, 14, 18, 19, 20, 21, 25, 30, 300, 1, 45, 67, 88 };           
            var res =  CandidateCode.median(input1, input2);
        }
    }

    public class CandidateCode
    {
        public static int median(int[] input1, int[] input2)
        {
            var mergedArray = input1.Concat(input2).OrderBy(o=>o).ToArray();
            int totalEmployees = mergedArray.Length;
            var median = 0.0M;
            
            if (totalEmployees % 2 == 0) //even number of values
            {
                var p1 = mergedArray[(totalEmployees / 2)-1];
                var p2 = mergedArray[((totalEmployees / 2) + 1)-1];
                median = Math.Ceiling((decimal)(p1 + p2) / 2);
            }
            else //odd number of values
            {
                var p1 = mergedArray[((totalEmployees + 1) / 2) - 1];
                median = Math.Ceiling((decimal)p1);
            }
            return (int)median;
        }
    }
}

Now let us explain the code.First we are merging the two arrays by using the CONCAT method.Then performing a sort for ordering of the elements.Then based on whether the total empolyees (tokens)are even or odd, we are applying the median formula. We are using the Math.Ceiling for getting the closest whole number value.

Conclusion

From this program/challenge , we learnt

  1. how to merge two arrays
  2. how to apply median based on odd/even values
  3. use of Math.Ceiling function.

I hope that this will be a good learning exercise for those whose are beginners in C#.Also participating in challenges helps us to hone our skills.Thanks for reading.


Disclaimer: This solution has been personally prepared by me and submitted for the knowledge sharing purpose.

Page copy protected against web site content infringement by Copyscape

About the Author

Niladri.Biswas
Full Name: Niladri Biswas
Member Level: Platinum
Member Status: Member
Member Since: 10/25/2010 11:04:24 AM
Country: India
Best Regards, Niladri Biswas
http://www.dotnetfunda.com
Technical Lead at HCL Technologies

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)