# Calculate difference of two ranges given

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 :)

-
You flaged this with unit testing, so where are they? (Don't post all, just your inputs for a that you have tested.) – mnhg Feb 22 '13 at 6:00

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";
}

-

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";
}

-
Thanks..It was a practice question so didn't bother much. – user1071840 Feb 23 '13 at 0:40