1
\$\begingroup\$

Write a method to compute the difference between two ranges. A range is defined by an integer low and an integer high. A - B (A “minus” B) is “everything in A that is not in B”.

This is an interview question and here is my code:

void findDiff(int a1,int a2, int a3, int a4)
{
   cout<<"("<<a1<<","<<a2<<") - ("<<a3<<","<<a4<<") = \n";

   if(a1 < a3) 
   {
         int end = (a2<a3) ? a2: a3-1;
         for(int i=a1; i<=end; i++) cout<<i<<"\t";
   }

   if(a4 < a2) 
   {
         int start = (a1>a4) ? a1 : (a4+1);
         for(int i=start; i<=a2; i++) cout<<i<<"\t";
   }
   cout<<"\n";
}

Please look at the code and tell me if it correct and if I'm missing any case. Thanks a lot in advance :)

\$\endgroup\$
1
  • \$\begingroup\$ You flaged this with unit testing, so where are they? (Don't post all, just your inputs for a that you have tested.) \$\endgroup\$ Feb 22, 2013 at 6:00

2 Answers 2

2
\$\begingroup\$

Make sure this is the signature they want. e.g. they do not expect the function to return vector, iterator or sthg. Also make sure they do not expect you to validate input. e.g. a1 <= a2 etc... after that you can remove redundant conditionals, they are already present in the for loops. And you can replace ternary operators with std::min/max for a more idiomatic c++. otherwise I could not find any missed case or off-by-one bugs.

void findDiff(int a1,int a2, int a3, int a4)
{
   cout<<"("<<a1<<","<<a2<<") - ("<<a3<<","<<a4<<") = \n";

    for(int i=a1; i<=std::min(a2, (a3-1)); i++) cout<<i<<"\t";

    for(int i=std::max(a1, (a4+1)); i<=a2; i++) cout<<i<<"\t";

    cout<<"\n";
}
\$\endgroup\$
1
\$\begingroup\$

Seems like you don't need two loops. Also your function and parameter names are badly chosen.

#include <iostream>

void range_diff(int a_lo, int a_hi, int b_lo, int b_hi)
{
    if (b_lo > b_hi) {
        return;
    }
    for (int i = a_lo; i <= a_hi; ++i) {
        if (i < b_lo || i > b_hi) {
            std::cout << i << " ";
        }
    }
    std::cout << "\n";
}
\$\endgroup\$
1
  • \$\begingroup\$ Thanks..It was a practice question so didn't bother much. \$\endgroup\$ Feb 23, 2013 at 0:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.