Boost Library in C++

In this blog we will discuss about Boot Library in C++ 11. Boost is a set of libraries for the C++ programming language that provide support for tasks and structures such as pseudo random number generation, linear algebra, image processing, multi-threading,  regular expressions, and unit testing. It contains eighty plus individual libraries, most of the Boost libraries are licensed under the Boost Software License, designed to allow Boost to be used with both free and proprietary software projects. 

Advantages of Boost library :
  1. Open Source Library.
  2. Cross Platform Development. 
  3. STL library support available.
  4. Well documented, document available on www.boost.org
  5. Good execution performance. 
  6. Easy and readable coding possible with boost library. 

Installation procedure of boost :


Use this link for installation :
  1. Unix :  Getting Started on Unix
  2. Windows : Getting Started on Windows

What Does Boost Provide?


Smart Pointers: There are some limitation of  std::auto_ptr's like - cannot be stored within a standard containers,  cannot be used to implement the pImpl (pointer-to-implementation) idiom and also does not work with arrays. In Boost library 5 type for smart pointers created to overcome this problem.

Any : In C++ 11 auto datatype is created , but auto we can use only inside function, to pass as function parameter auto can't be useful. Boost::any is more power full than Auto. Any is useful when you are working with design pattern.

Bind and Function : boost::bind and boost::function  are specified as two separate components, but they are extensions (any number of arguments) of binders and functors concept which are currently in place in the Standard Library.

The Lambda Library : Powerful lambda library is provided  by boost to work with  boost::bind and boost::function.

The Boost Graph Library : The Boost Graph Library is a huge library, with a large amount of support material and good sample programs. 

Thread : The threads library makes it seem almost as easy to do threads in C++ .

Spirit parser generator framework : Parser framework is added to work with XML.

What Else?
  • Regular Expressions
  • Traits
  • File System
  • Iterator Adaptors
  • Maths and Matrices
  • A Template metaprogramming framework
  • Tuples
  • Python

Simple Program using Boost Library : 


1)
#include <iostream>
#include "boost/any.hpp"
int main()
{
boost::any var1 = 5;
std::cout << boost::any_cast<int>(var1) <<std::endl;
int i = boost::any_cast<int>(var1);
std::cout << i <<std::endl;
return 0;
}

Output: 5 5

2)
//It will cause boost::bad_any_cast exception,
#include <iostream>
#include "boost/any.hpp"
int main()
{
try
{
boost::any var1 = 5;
std::cout << boost::any_cast<std::string>(var1) <<std::endl;
}
catch(boost::bad_any_cast &e)
{
std::cout << e.what() << std::endl;
}
return 0;
}
Output:
boost::bad_any_cast: failed conversion using boost::any_cast

What is Data Science ?

Data science is a multidisciplinary blend of data inference, algorithms development and technology in order to solve analytically complex problems. In order to uncover useful intelligence for their organizations, data scientists must master in the full spectrum of the data science life cycle and possess a level of flexibility and understanding to maximize returns at each phase of the process. Data science is ultimately about using this data in creative ways to generate business value. 

Data Science is primarily used to make decisions and predictions making use of predictive causal analytics, prescriptive analytics and machine learning.


Data science – discovery of data insight

Discovery of data insight all about uncovering findings from data. Diving in at a granular level to mine and understand complex behaviors, inferences and trends. It is about surfacing hidden insight that can help enable companies to make smarter business decisions. For example:
  • Hotstar data mines movie viewing patterns to understand what drives user interest, and uses that to make decisions on which Hotstar original series to produce.
  • Flipkart identifies what are major customer segments within it's base and the unique shopping behaviors within those segments, which helps to guide messaging to different market audiences.
How do data scientists mine-out insights? This requires a big dose of analytical creativity and  quantitative technique in order to get a level deeper – e.g. inferential models, time series forecasting, segmentation analysis, synthetic control experiments.In this case, data scientists act as consultants, guiding business stakeholders on how to act on findings.

Data science – development of data product

A "data product" is a technical utility that utilizes data as input, and processes that data to return algorithmically generated results. The classic example of a data product is a recommendation engine or product, which ingests user data, and makes personalized recommendations based on that data. Here are some examples of data products:
  • Flipkart's recommendation engines suggest items for you to buy, determined by their algorithms. 
  • Mail spam filter is data product, an algorithm behind the scenes processes incoming mail and determines if a message is junk or not.
A data product is technical functionality that encapsulates an algorithm and is designed to integrate directly into core applications/Server. Respective examples of applications that incorporate data product behind the scenes: Flipkart's homepage, Mail inbox, and autonomous driving software. In this case, data scientists serve as technical developers, building assets that can be leveraged at wide scale.

Skills require to become Data Scientist:  

Mathematics Expertise

Mathematical statistics is important, it is not the only type of math utilized. First, there are two branches of mathematical statistics – classical statistics and Bayesian statistics. Many inferential techniques and machine learning algorithms and linear algebra. Overall, it is helpful for data scientists to have breadth and depth in their knowledge of mathematics and statistics.

Technology and Hacking

Hacking mean not breaking computer program, but creativity and ingenuity in using technical skills to build things and find clever solutions to problems. Data scientists utilize technology in order to get enormous data sets and work with complex algorithms and it requires tools far more sophisticated than Excel. 

Strong Business Acumen

Having this business acumen is just as important as having acumen for technology and algorithms. Data science projects and business goals should clearly aligned. Ultimately final value comes from leveraging all of the above to build valuable capabilities and have strong business influence.

In this blog I explain basic terms related with data science. I will try to explain more on this topic in my next blog.

Lambdas in C++

In this blog we will discuss, What is a Lambdas in C++ ? and How to use Lambda function as callbacks ?

What is a Lambda Function?

Lambda functions are a kind of anonymous functions in C++. Lambda function is work like a normal function .
  • Input - pass arguments 
  • Output -  returns result
Lambda function doesn’t have any name. Its mainly used to create very small functions to pass as a callback to an another API.

Lets start with what was the need of lambda functions ?

Suppose I have an array of int and I want to transverse array using  STL algorithm std::for_each.

#include <iostream>
#include <algorithm>

void display(int a)
{
    std::cout<<a<<" ";
}
int main()
{
    int arr[] = { 1, 2, 3, 4, 5 };

    std::for_each(arr, arr + sizeof(arr) / sizeof(int), &display);

    std::cout << std::endl;

}
Now with Lambdas :
#include <iostream>
#include <algorithm>
 
int main()
{
    int arr[] = { 1, 2, 3, 4, 5 };
 
    std::for_each(arr, arr + sizeof(arr) / sizeof(int), [](int x) {
            std::cout <<x <<" ";
        });
 
    std::cout << std::endl;
 
}
Here, without creating extract function we can display array elements, It is more readable than first example.
  • [] is used to pass the outer scope elements (passed by value or passed by reference)
  • (int x) is showing argument x is passed

Basic Syntax for Lambda Expressions

The following line shows the basic syntax for C++11 lambda expressions:
[ captures ] (parameters) -> returnTypes { lambda Statements; }
  • [ captures ]: The capture clause, specifies which outside variables are available for the lambda function and whether they should be captured by value or by reference. An empty capture clause [] means nothing captured, in this case lambda expression body doesn't access variables in the enclosing scope.
  • ( parameters ): This is the optional parameters list, you can omit the parameters list if you want a function that takes zero arguments.
  • -> returnType: This is the optional return type.  Most of the time, compilers can find the return type of the lambda expression when you have zero or one return statement. However, it is good to write return type to understand the code.
  • { lambda Statements; }: This is the lambda body. The statements within the lambda body can the captured variables and the parameters.

Pass Outer scope elements inside lambda functions:

1) Using [=] : Outer scope elements has been passed by value
Example:
[=](int &x) {}

2) Using [&] : Outer scope elements has been passed by reference
Example: 
[&](int &x) {}

Lets see example to pass outer scope elements:

Exmaple 1 :

#include <iostream>
#include <algorithm>

int main() {
    int arr[] = { 1, 2, 3, 4, 5 };
    int add = 5;
    std::for_each(arr, arr + sizeof(arr) / sizeof(int), [&](int x) {
        std::cout << x << " ";      
        // Can modify the add inside this lambda function because
        // Can modify the add inside this lambda function because
        // all outer scope elements has write access here.
        add = 3;
        });
    std::cout << std::endl;

    std::for_each(arr, arr + sizeof(arr) / sizeof(int), [=](int &x) {
        x= x+add;
        // Can not modify the add inside this lambda function because
        // all outer scope elements has read only access here.
        // add = 9;

        });
    std::cout << std::endl;

    std::for_each(arr, arr + sizeof(arr) / sizeof(int), [](int x) {

        // No access to add inside this lambda function because
        // all outer scope elements are not visible here.
        //std::cout << add << " ";
        });
    std::cout << std::endl;
}
Example 2: ( Mixing capturing by value and Reference )
#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

int main()
{
    int sum = 0;
    int divisor = 3;
    vector<int> numbers { 1, 2, 3, 4, 5, 10, 15, 20, 25, 35, 45, 50 };
    for_each(numbers.begin(), numbers.end(), [divisor, &sum] (int y)
    {
        if (y % divisor == 0)
        {
            cout << y << endl;
            sum += y;
        }
    });

    cout << sum << endl;
}
Here :
  • [=, &sum]: Captures any referenced variable within the lambda by value, except sum that has to be captured by reference.
  • [&, divisor]: Captures any referenced variable within the lambda by reference, except divisor that has to be captured by value..

Passing Lambda Expressions with std::function:

Example:
#include <iostream>
#include <algorithm>
#include <vector>
#include <functional>
using namespace std;
 
void for_each(std::function<void (int)> func)
{
    vector<int> numbers{ 1, 2, 3, 4, 5, 10, 15, 20, 25, 35, 45, 50 };
 
    for_each(numbers.begin(), numbers.end(), func);
}
 
int main()
{
    auto func1 = [](int y)
    {
        cout << y << endl;
    };
 
    auto func2 = [](int z)
    {
        cout << z * 2 << endl;
    };
 
    for_each(func1);
    for_each(func2);
}
The for_each function receives a std::function<void (int)>, so it is possible to call this function with a lambda expression that returns void and receives an int as an argument.

Here I provided some example for Lambdas in C++. There are many more things about Lambda Function, I will provide more details about Lambda in my next blogs. 

Count numbers of Zero's in array without using comparison operators


Logic : For counting numbers in array we are using comparison operators, but some time interviewer will ask this question check your coding knowledge. So we can count number of zeros without using comparison operator also, by using “!” operator.

Suppose my array input is like this:
5
0
6
9
0
4
0
1
0
6

If I used “!” with each array element while traversing array then values are:
0
1
0
0
1
0
1
0
1
0
Here we know !0 = 1 and !1 = 0 also !5 = 0.

Now do sum of above array values, sum is 4. So number of zero values also 4

C program :
int zeros_in_array( int a[] , int count)
{ 
   int i, sum = 0 ;
   for (i =0 ; i < count ; i++)
   {
      sum+=!a[i];
   }
   return sum;
}
int main()
{
    int arry[] = {5,	0,	6,	9,	0,	4,	0,	1,	0,	6};
    int num = 10; // Array values count 
    printf(“Zeros in array : %d”, zeros_in_array(arry, num));
}

Count Non-Zero values in array :

Some interviewer will ask count non-zero values in array or how many non-zero values are present in array without using comparison operators?

In this case we need to use “!” operator twice with each array values. Then result array after doing twice “!” operation of with each array value:
1
0
1
1
0
1
0
1
0
1
Here we know !!0 = 0 and !!1 = 1 also !!5 = 1.

Now do sum of above array values, sum is 6. So number of non-zero values also 6.
C prograom : 
int non_zeros_in_array ( int a[] , int count)
{ 
   int i, sum = 0 ;
   for (i =0 ; i < count ; i++)
   {
      sum+=!(!a[i]);
   }
   return sum;
}
int main()
{
    int arry[] = {5,	0,	6,	9,	0,	4,	0,	1,	0,	6};
    int num = 10; // Array values count 
    printf(“Non-zero values in array : %d”, non_zeros_in_array(arry, num));
}

Check if two numbers are equal without any comparison

Logic 1: 

If two numbers are equal the bitwise XOR result will be zero. In this way we can check two numbers are equal without any comparison.

For example :

1) 5^5 = 0

(5)10 = (0101)2
0101
0101
-------
0000

2) 12^12 = 0
(12)10 = (1100)2
1100
1100
------
0000

C program :
int main()
{
    int num1 = 10, num2 = 10;
    if((num1 ^ num2) == 0)
        printf("Equal");
    else
        printf("Unequal");
    return 0;
}

Logic 2 : 

We know, subtraction of two equal numbers is Zero. Means number are zero if equal other wise non-zero.
C program :
int main()
{
    int num1 = 10, num2 = 10;
    if(!(num1 - num2))
        printf("Equal");
    else
        printf("Unequal");
    return 0;
}

Set all the bits in given range of unsigned int

First discuss about what is bits setting? 
  1. Number 12 is represented as 1100 in binary format. Mathematical representation like (12)10 = (1100)2So Number (1100)2 then complete bits setting result is (1111)2, means set all bit to 1, this is called complete/all bits setting.
  2. But in some cases we need to set particular bit of Number. For example (1100)2 set 1st bit only, then result become (1110)2, (bit counted from right to left, counting started with number 0), this is single bit setting.
  3. Now we can start with set bits of number with given range. For example (1100)2 set bits from 1st to 3rd bit, then result become (1110)2. This is given rang bits setting.
Now we can start with how to code this in C.

All bits setting:

Suppose N is unsigned integer value.
 Then we can code in C like this:
unsigned int all_bits_setting(unsigned int N)
{
  return N | ~0
}


Single bit setting:

Single bit setting is possible with following method: 
Input is (1100)2  and 2nd bit need to set, then first create binary number which contain 1 as a bit value at 1nd bit. Suppose number is X, that we can create X like this 1 << 2 = (0010)2, do OR operation of both numbers (1100)2  | (0010)2 = (1110)2

Then we can code in C like this:

unsigned int single_bit_setting(unsigned int N, unsigned int k)
{
  return (N | (1 << k)); 
}

Set given range of bits:

Input is (1100)2  and range is from 1st bit to 3rd bit. Then first create binary number which contain 1 as bit value from 1st bit to 3rd bit and other bits values are 0. So required value is (1110)2. But how to created (1110)using given rang ? So first find range difference i.e. 3 -1 = 2, then (1 <<  (2+1)) -1 = (7)10 = (0111)2 , Now shift this value with lowest rang value  (0111)2  << 1 = (1110)2, Now do OR operation of Input value  (1101)2 and (1110)2 ,
(1100)2 | (1110)=  (1110)2

Then we can code in C like this:
unsigned int rang_toggling(unsigned int N, unsigned int k , unsigned int l)
{
 //Here l > k
  return N | ((1<<(l-k)+1)-1)<<k;
}

Clear all the bits in given range of unsigned int

First discuss about what is bits clearing? 
  1. Number 12 is represented as 1100 in binary format. Mathematical representation like (12)10 = (1100)2So Number (1100)2 then complete bits clearing result is (0000)2, means set all bit to 0, this is called complete/all bits clearing.
  2. But in some cases we need to clear particular bit of Number. For example (1100)2 clear 2st bit only, then result become (1000)2, (bit counted from right to left, counting started with number 0), this is single bit clearing.
  3. Now we can start with clear bits of number with given range. For example (1101)2 clear bits from 1st to 3rd bit, then result become (0001)2. This is given rang bits clearing.
Now we can start with how to code this in C.

All bits clearing:

Suppose N is unsigned integer value.
 Then we can code in C like this:
unsigned int all_bits_clearing(unsigned int N)
{
  return N & 0
}


Single bit clearing:

Single bit clearing is possible with following method: 
Input is (1100)2  and 2nd bit need to clear, then first create binary number which contain 1 as a bit value at 2nd bit. Suppose number is X, that we can create X like this 1 << 2 = (0100)2, Now do bitwise complement of (0100)2, so binary after bitwise complement is (1011)2, do AND operation of both numbers (1100)2  & (1011)2 = (1000)2

Then we can code in C like this:

unsigned int single_bit_clearing(unsigned int N, unsigned int k)
{
  return (N & (~(1 << k))); 
}

Clear a given range of bits:

Input is (1101)2  and range is from 1st bit to 3rd bit. Then first create binary number which contain 0 as bit value from 1st bit to 3rd bit and other bits values are 1. So required value is (0001)2. But how to created (0001)using given rang ? So first find range difference i.e. 3 -1 = 2, then (1 <<  (2+1)) -1 = (7)10 = (0111)2 , Now shift this value with lowest rang value  (0111)2  << 1 = (1110)2, Now do bitwise complement of (1110)2 so binary value after bitwise complement is (0001)2 ,  Now do AND operation of Input value  (1101)2 and (0001)2 ,
(1100)& (0001)=  (0001)2

Then we can code in C like this:
unsigned int rang_toggling(unsigned int N, unsigned int k , unsigned int l)
{
 //Here l > k
  return N & ~((1<<(l-k)+1)-1)<<k;
}

Toggle a given range of bits of an unsigned int

First discuss about what is bits toggling? 
  1. Number 12 is represented as 1100 in binary format. Mathematical representation like (12)10 = (1100)2So Number (1100)then complete toggled result is (0011)2, Here 1 is replaced with 0 and 0 with 1, this is called bitwise complement.
  2. But in some cases we need to toggle particular bit of Number. For example (1100)2 toggle 1st bit only, then result become (1110)2, (bit counted from right to left, counting started with number 0), this is single bit toggling.
  3. Now we can start with toggle bits of number with given range. For example (1100)2 toggle bits from 1st to 3rd bit, then result become (0010)2. This is rang bits toggling.
Now we can start with how to code this in C.

Bitwise complement: 

Suppose N is unsigned integer value.
 Then we can code in C like this:
unsigned int bitwise_complement(unsigned int N)
{
  return ~ N
}
Operator ~ is used to get bitwise complement.


Single bit toggling:

Single bit toggle is possible with following method: 
Input is (1100)2  and 2nd bit need to toggle, then first create binary number which contain 1 as bit value at 2nd bit. Suppose number is X, that we can create X like this 1 << 2 = (0100)2, Now do XOR of both number (1100)2 ^ (0100)2 = (1000)2

Then we can code in C like this:

unsigned int single_bit_toggling(unsigned int N, unsigned int k)
{
  return (N ^ (1 << k)); 
}

Toggle a given range of bits:

Input is (1100)2  and range is from 1st bit to 3rd bit. Then first create binary number which contain 1 as a bit value from 1st bit to 3rd bit and other bits values are 0. So required value is (1110)2. But how to created (1110)2 using given rang ? So first find range difference i.e. 3 -1 = 2, then (1 <<  (2+1)) -1 = (7)10 = (0111)2 , Now shift this value with lowest rang value  (0111)<< 1 = (1110)2, This is required value to do XOR with input
(1100)2 ^ (1110)2 =  (0010)2

Then we can code in C like this:
unsigned int rang_toggling(unsigned int N, unsigned int k , unsigned int l)
{
 //Here l > k
  return N ^ ((1<<(l-k)+1)-1)<<k;
}

How can I get job in IT sector in India ?

Information technology is growing very fast in India. Bangalore, Chennai, Hyderabad, Pune and Noida are now IT hub of India. Every day many startup industries are opening, but still many engineers are waiting for job. So many engineers are still jobless in India. I don't want to discuss why this is happening and who are responsible for this condition, because there are so many factors are responsible for this and one single person can't change this. So instead of doing discussion on this topic, I want to discuss about "how to get job in IT sector"?

I want to divide my discussion into two topics. First some tips for IT engineer students, those are still pursuing engineering and second who completed IT engineering.

Tips for IT students those pursuing engineering:
  1. I know academic study is important for engineering, but with academic study you can also try some certificate course which will be helpful for next future, instead of doing local class certification, please try some international certification which is more useful than local certification.
  2. Vacation period, you can use for doing internship in any small scale company, that experience you can add into your resume.
  3. Start using open source technologies like Linux, Android, QT, WordPress etc This technologies are open source, so no money is required to buy/view code.
  4. Start using development tools like Visual studio, eclipse and Android Studio, which will let you know about how project development is happening. 
  5. Start using Open Source Version control tools Like GIT, these tools are useful to maintain project with previous versions.
  6. Those students want to work in mobile application domain, then create 2-3 Android applications and also try to publish on play store.
  7. Publish some research paper in international conference.
  8. Start writing review comments in Stackoverflow site, this will increase your knowledge as well you can add Stackoverflow points into resume.
  9. Start writing Technical blogs, there are so many blogs site available free of cost.
  10. For web developer students, create your own site, there are many web hosting sites are available with some cost.
Above points will make you resume more valuable as compare to the other IT students.
 Now some tips for IT Fresher (Engineering passout students):
  1. You also can start above steps if not done still date. Interview preparation is more important with this skills.
  2. Update your skill sets properly with technical points in resume.
  3. Publish resume on job portals, also review job portal every day and keep updating some skills and experience.
  4. Try to find job using friends circles and social media.
  5. In interview session, discuss should not be like questions answer type. It should be like common discuss, mean don't give answer like students, try to give answer like professional person with confidence.
  6. Instead of showing your need of job to interviewer try to show your abilities, try to explain how you good in IT environment.
  7. If you need job very urgently because of financial conditions then keep to two-three professional field open where you are ready to work like IT development, testing, teaching, government jobs, bank officers etc.
  8. Keep learning active while attending interview also. Some freshers showing gap between engineering passout and job interview, so interviewer might ask what you did in this period ? Be prepare for this this type of questions, with proper justified answers.
Above tips definitely will help to get job in IT sector. All tips are according to my knowledge, reader please add  your opinion in comment section which will help to get job for IT Freshers.

Please share if you like...

River, Temple and Flowers Puzzle

Puzzle -
There are 3 temples and 3 rivers. The river and the temple are alternatively.
Like -  River Temple River Temple River Temple
A man with some flowers; while crossing river, flowers gets doubled and he puts equal number of flowers in each temple. At the end no flower is left with him.

How many flowers initially person carried ?
How many flowers he put in each temple ?


Solution –

River
Temple
River
Temple
River
Temple
Flowers put in Temple

X

X

X
 Start (P)
R1
T1
R1
T2
R3
T3

Let’s assume flowers put in each temple are X

Now just think about one temple at time.
First start with temple T3; assume man have A number of flowers at start point. He have to cross 3 rivers R1,R2,R3 to reach in temple T3. So Flowers get doubled 3 times,  Hence Total number of flowers after reaching temple T3 are 2 x 2 x 2 x A = 8A

Form and
Also 8A = X and A = X/8  

Now also assume B number of Flowers for temple T2, and 2 times need to cross rivers ( R1 & R2). Hence Total number of flowers after reaching temple T3 are 2  x 2 x  B = 4B

Form and
Also 4B = X and B = X/4

Same for temple T1, assume C number of flowers required and one river need to cross.
So 2 x C = X and C= X/2  

Form ①, ③, ⑤ and
Total number of flowers required = A + B + C = X/8 + X/4 + X/2
Multiply 8 by both sides
8 x (A + B + C ) = X + 2X + 4 X = 7X

A + B + C = 7X / 8
Start putting X value form 1, 2, 3, 4, 5, 6, 7, 8, …
Only X = 8 value gives perfect integer value ( Flowers count is always Integer).
And  A + B + C = 7  

Number of flowers initially person carried  = 7
Number of flowers he puts in each temple  = 8
========================================================================
Above solution will give answer for 3 rivers and 3 temples, and flowers are increased by double while moving into river.
Now find common formula which will give answer for k number of rivers and k number of temples and flowers are increased by m times while moving into river.

Form ①, ③, ⑤ and
Total number of flowers = X/2 + X/4+ X/8 = (X + X/2 + X/4 + X/8) –X
X+ X/21 + X/22 + X/23–X      
So here k = 3 and m = 2
Sum of Geometric progression formula
a + ar + ar2  + ... + ar(n-1)  =
,  r≠1 
From ⑦  and

Let a = X, n-1 = 3 = k and r = ½ = 1/m

Total number of flowers =
Solve equation by putting available values of k and m, it will give answer in term of  x/y   (Rational Number) then x = Total number of flowers and y = Number of flowers he puts in each temple.

Let verify for 4 temples and 4 rivers, and flowers get triple after crossing river.
k = 4 and m = 3solve this equation, will get answer 40/81
Total number of flowers= 40
Number of flowers he puts in each temple = 81

========================================================================

In some cases river count is less by 1 as compare to temple, means first temple will come and then River. Like - Temple River Temple River Temple.
In that case formula become
where k= Number of temple and m times flower increased in river

Verify for 3 temples, 2 rivers and 2 times flowers increased in river
Answer in terms of x/y=7/4 is 
Total number of flowers= 7
Number of flowers he puts in each temple =

I tried to solve this puzzle in terms of mathematical equation with all scenarios. 

Please share your valuable feedback in comment section and if any correction please update in comment. 

Camel and 3000 Bananas Puzzle

I want to share one puzzle which was asked to me in one technical interview. 

Puzzle- One camel owner want to transport 3000 Bananas to market, which is 1000 Km from his house. Maximum 1000 Bananas camel can carry one time. It (camel) eats one banana for every Km it travels.

What is the largest number of bananas that can be delivered to the market ?

Solution -

Let distance between A and B is 1000 Kms.
First find distance, where camel can carry 2000 bananas(Multiple of max. carrying capacity) i.e. Point C .
So 3 times camel need to travel Distance AC, also 2 times need to comeback from C to A.

Total distance traveled between AC = 3 x Distance AC + 2 x Distance CA = 3X+2X = 5X                                                                                                                                                               

Also 1 Km = 1 bananas. So 1000 bananas completed = 1000km traveled  

From  and 
                      1000 Kms = 5X means X= 200 Kms.                                                                                          
Now Same steps for Distance CD. 2 times camel need to travel Distance CD, also once need to comeback from D to C.

Total Distance traveled between CD =  2 x Distance CD + 1 x Distance DC  = 2Y+Y= 3Y   

From  and 
                       1000 Kms = 3Y means Y= 1000/3 = 333 Kms                                                    

Here 1000 not divisible by 3, So distance traveled 333 x 3 =999 Kms between CD.

So total Bananas remaining 2000 -999 = 1001 bananas                                                  

Now total distance between AD = Distance AC + Distance CD = X + Y = 200 +333 = 533.
Remaining distance = 1000 -533 = 467 Kms

Max. carrying capacity 1000 bananas and  467 bananas for remaining  467 Kms. So Bananas delivered to at  Point B is 1000 – 467= 533 bananas                                                             

Maximum possible bananas delivered to market are 533.