I generally start with a very simple question with my interview candidates. I ask the for writing a program for giving the integer average of 2 integers using only integer type variables. Assume that input will always be with in integer limits.
The definition of integer average is the highest smaller integer if average is floating point number. Also the condition if that they can not use any typecasting or any datatype other than int.
Example:
a = 4, b = 5, avg = 4
a = 4, b = 6, avg = 5
a = -4, b = -6, avg = -5
a = 4, b = -5, avg = -1
a = -4, b = -5, avg = -5
95% of candidates smell some issues in this problem and when I say nothing is there they don't even ask any clarification and come up with something like this:
int get_average(int a, int b) { return (a+b)/2; }
Then I ask them to have a look if this is correct on definition and then they see that it is. But there test failed on very first floating point negative average. Then most of them do a quick fix and come up with something below:
int get_average(int a, int b) { int sum = (a+b); if (sum < 0) return sum/2 - 1; return sum/2; }
The above solution is obviously wrong if sum if a even negative number. I am disheartened to see why do these candidates just solve a test case and show the solution. They don't even care to run this with some examples.
On pointing this, most of them correct the code. Others face the rejection at this stage.
int get_average(int a, int b) { int sum = (a+b); if (sum < 0 && sum%2 != 0) return sum/2 - 1; return sum/2; }
Now I ask them to make it production worthy and taking care of boundary conditions. Many of them are not able to do so but some of them go through it for my second question.
Though I expect this problem to be concluded within 30 minutes depending of their experience but candidates do a lot of silly mistakes and stretch.
Lets see if you can code this correctly.
#include <iostream> using namespace std; int get_average (int a, int b) { int a_half = a/2; int b_half = b/2; bool a_even = a%2==0? true:false; bool b_even = b%2==0? true:false; if (a>=0 && b>=0) { if (!a_even && !b_even) return a_half + b_half + 1; return a_half + b_half; } else if (a<0 && b<0) { if (a_even && b_even) return a_half + b_half; return a_half + b_half - 1; } else { int sum = a+b; if (sum < 0 && sum%2 != 0) return sum/2 - 1; return sum/2; } } int main() { int n, a, b; cout << "number of test cases: "; cin >> n; for (int i=0; i<n; i++) { cout << endl << "Enter a and b: "; cin >> a >>b; cout << "average = " << get_average(a,b) << endl; } }
Edit: We get a more efficient and concise solution in comments. Please go through it.
Notably most of the solution for binary search are wrong because of above reason. This bug was fixed in Java SDK after 9 years. Please read more about it here.
Subscribe - To get an automatic feed of all future posts subscribe here, or to receive them via email go here and enter your email address in the box. You can also like us on facebook and follow me on Twitter @akashag1001.
Thank you for the puzzle. I think I have a solution that seems to be a bit shorter and more systematic, although I'm not so sure if it is easier to understand; so please feel free to critique, OK?
My test set was as follows:
checkintAverage(4, 5, 4);
checkintAverage(4, 6, 5);
checkintAverage(4, 7, 5);
checkintAverage(-4, -5, -5);
checkintAverage(-4, -6, -5);
checkintAverage(-4, -7, -6);
checkintAverage(4, -7, -2);
checkintAverage(4, -8, -2);
checkintAverage(5, -8, -2);
checkintAverage(5, -9, -2);
checkintAverage(7, -7, 0);
checkintAverage(4, -4, 0);
checkintAverage(4, -3, 0);
checkintAverage(4, -5, -1);
checkintAverage(7, -4, 1);
checkintAverage(8, -4, 2);
checkintAverage(8, -5, 1);
checkintAverage(9, -5, 2);
Hope this is correct. One, shorter, solution would only be 100% correct in Java or on major C compilers (because the left shift on negatives is generally undefined) yet it's worth mentioning:
(a>>1) + (b>>1) + (a&b&1)
A more conservative solution is somewhat longer:
int intAverage(int a, int b) {
int rem_a = (a&1)==0 ? 0 : a<0 ? -1 : 1;
int rem_b = (b&1)==0 ? 0 : b<0 ? -1 : 1;
return a/2 + b/2 + (rem_a + rem_b-1)/2;
}
What I didn't quite like about the posted solution is that it had two different code paths depending on whether a and b are of the same sign. But this is subject to discussion!
Thank you for your excellent site.
There was a typo in my function; here is what it should look like:
int intAverage(int a, int b) {
int rem_a = a%2==0 ? 0 : a<0 ? -1 : 1; // i.e., a - a/2*2
int rem_b = b%2==0 ? 0 : b<0 ? -1 : 1;
return a/2 + b/2 + (rem_a + rem_b + 2)/2 - 1;
}
The idea is to calculate the term correction due to truncation in the integer division, which could only be 1, 0, or -1; averaging those cannot possibly overflow. The trick of adding 2 and then subtracting 2/2 = 1 in the end is to ensure that we are summing non-negative values, otherwise the rounding direction could be incorrect.
@Anonymous:
What you presented is just awesome. Thanks a lot for a more efficient and concise solution.
Though my post was inclined towards how people in a interview approach the problem and go around it.
Usually I do not read post on blogs, but I would like to say that this write-up very forced me to try and do it! Your writing style has been surprised me. Great work admin..Keep update more blog..
Web development company in Chennai
good info about pragramming interview,thanks for this blog.
Mcx Silver Tips
The following should work well for all test cases -
int average(int a,int b)
{
return (a+b)>>1;
}
Wonderful blog.. Thanks for sharing informative blog.. its very useful to me..
Android App Development Company in India
Thanks for sharing this quality information with us. I really enjoyed reading. I think I need it. Mobile Application Development services
function sum(a, b) {
var sum = a + b;
return sum%2 === 0 ? sum/2 : (sum < 0 ? sum/2 +0.5 : a > b ? b : a)
}
Superb explanation & it's too clear to understand the concept as well, keep sharing admin with some updated information with right examples.Keep updating more posts.
Python Online Training
Learn Python Online
what ??
Firstly, its not concise - look at all the branches you've created. The cpu would mush rather implement the math.
How do you know its more efficient? Did you loop it and measure perf. vs doing just the math?
And if you want to be a stickler, odd even check you can just check the last bit instead of doing a mod.
divide by 2 is just a shift.
If you think you're being so righteous and clever - you're quite out of place.
I'll probably get fired if I write code like above for a basic average function.
int average(int a,int b){
return (a + b > 0) ? ((a+b) - ((a+b) % 2)) / 2 : ((a+b) + ((a+b) % 2)) / 2;
}
You will only play puzzle instead of solving real world problems. Get over it and do some work. Why do you even ask such questions which has no real use case. WHY WILL SOME ONE LIKE TO FIND OUT AVERAGE USING JUST INTEGER TYPE WHEN THESE ARE BASIC WORKS DONE BY COMPUTER? Please dont call candidates to waste their time show your egos by cramping few puzzles from Narsimha Karumchi and other books. It is because of folks like you that many great candidates are not selected. I can ask you several such puzzle and I bet you wont be able to solve. So, stop all these bullshits.
Good Informative post Thank you Digital Marketing Company
Thanks for giving great kind of information. So useful and practical for me. Thanks for your excellent blog, nice work keep it up thanks for sharing the knowledge.
PVC Door suppliers In Karnataka
nice topic which you have choose.
second is, the information which you have provided is better then other blog.
so nice work keep it up. And thanks for sharing.
Business visa provider in Delhi
Thanks for Sharing such an nice post..
Visakhapatnam Real Estate
Ah,so beautiful and wonderful post!An opportunity to read a fantastic and imaginary blogs.It gives me lots of pleasure and interest.Thanks for sharing.
Interior Design for Home
Very informative post!
Tech News
Apple iPhone
Best Android Apps
Very Informative Article!
Tech News
Amazon Scout robot
Samsung Galaxy S10
Your article is really worth reading. I've been following your blogs for a while and you are doing a great job. Regards to your hard work and great effort.
Oracle Training in Chennai
Oracle Course in chennai
Tally Course in Chennai
Tally Classes in Chennai
Embedded System Course Chennai
Embedded Training in Chennai
Oracle Training in OMR
Oracle Training in Porur
boring blog
Porn Sex & Anel Sex Collection
I consider myself a problem solver, inventor, multi-disciplinarian, gardener and leader. I'm drawn to formulating new ideas around objects, people and motives using thesis building.
if you want more just look here Interview Answers
That was really a great Article. Thanks for sharing information. We are also help to student for Study in Singapore Process. Visit us : https://meoverseas.com/
Wonderful post! We are linking to this great post on our website. Keep up the great writing.
Java Training In Bangalore
Advanced Java Training In Bangalore
С сумкой которой пользуются женщины всё намного сложнее. Для девушки на основное место становиться то, как глядится сумка. Она согласна истратить некоторое время, чтобы привязаться к исключительной для себя сумочке в раздевалке, но несмотря ни на что произвести впечатление на мимо проходящих. В аксессуаре девушки можно найти косметику, телефон, аксессуары, перчатки. Каталог бывает гораздо больше, всё зависит от наименования облюбованного реквизита. В гардеробчике дамы параллельно несколько сумок разных форм и расцветок. Для похода на работу или учёбу мисс выбирает маленькую сумку или кросс-боди, для собрания с одногруппниками днем. Интересно, что девушке редко даруют сумку. Аксессуары девушка выбирает сама, а когда есть необходимость, то предъявляет коллегам то, что она хочет в атрибуте требующего подарка. Подарки и неожиданные приобретения здесь будут ненужны. Приобретение новой вещи – это ответственное событие, но безумно приятное. Не смотря не на что осуществляйте это как можно чаще тут сумки майкл корс !
Python is designed as a general purpose programming language, MatLab as a numerical computing environment. Python has libraries such as Numpy, Scipy, Scikit-learn, Pandas and Matplotlib that allow it to do all the use cases MatLab is designed for. ... Python is the better option..really nice to read this blog..
python training in chennai
python course in chennai
python online training in chennai
python training in bangalore
python training in hyderabad
python online training
python training
python flask training
python flask online training
python training in coimbatore
If you consider yourself a “non-technical” person, that doesn't mean you can't learn AWS or start a new career in the tech industry. ... Starting with an AWS Certification is a great way to get started.keep share some more details..i need some more information..really nice to read
..
AWS training in Chennai
AWS Online Training in Chennai
AWS training in Bangalore
AWS training in Hyderabad
AWS training in Coimbatore
AWS training
The knowledge of technology you have been sharing thorough this post is very much helpful to develop new idea. here by i also want to share this.
rpa training
rpa training online
rpa course
rpa online course
online training for rpa
rpa online training
wonderful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article resolved my all queries
Java training in Chennai
Java Online training in Chennai
Java Course in Chennai
Best JAVA Training Institutes in Chennai
Java training in Bangalore
Java training in Hyderabad
Java Training in Coimbatore
Java Training
Java Online Training
Wonderful post and more informative!keep sharing Like this!
Jira online training
Jira Course Online
Каждый посетитель, приобретая керамику Keratile в онлайн-магазине РеалГрес, получает в реальности классный продукт. Ради того чтобы купить плитку в магазине RealGres, нужно просто посетить официальный сайт фирмы. Приукрашивают стенки и пол кафельной плиткой в целом ввиду её физических параметров. Плоская и гладкая плоскость довольно просто оттирается. Самой ценной декоративной плиткой считается итальянская. Отечественные изготовители довольно давно настроили производство схожих изделий, большинство не уступают иностранным аналогам. Стоимость небольшого квадрата плитки зависит от его физических свойств, а также от места изготовления.
will omit your great writing due to this problem.
tableau training
Power bi online
Abinitio training
Hyperion training
Далее рассмотрены основные плюсы коммуникации с данной компанией. Безграничный количество оборудования для коммунальной сферы. Воспользуйтесь наибольшими преимуществами только на сайте купить комплект садовой мебели из искусственного.
Сконцентрируйтесь не только на напольной плитке западного производства, но и на наши варианты. Оптимальный выбор плитки может облагородить всякую коридор или ванную комнату. Кафельная превосходно подойдет к любому интерьеру. Отбирая качественный стройматериал как например dual gres chic sandra доведется рассмотреть максимальное количество версий.
Good post..
https://www.kitsonlinetrainings.com/course/sap-abap-on-hana-online-trainingc
https://www.kitsonlinetrainings.com/course/sap-abap-online-training-course
https://www.kitsonlinetrainings.com/course/sap-bw-on-hana-online-training
Изменение сегодняшних технологий позволило игральным площадкам серьезно оптимизировать интересные услуги. Casino x официальный сайт – воспользуйтесь преимуществом надежной игры и заработайте существенные суммы. Игры в интернете получили существенную распространенность по всему миру.
Casino x регистрация – воспользуйтесь основными преимуществами устойчивой игровой площадки, выигрывайте большие суммы. Азартные игры во все времена манили гемблеров. Отныне кто угодно имеет возможность испытать судьбу на портале Казино икс.
Подключайтесь к игровой площадке и получите «вкусные» бонусы в персональной учетке. Сделайте правильный выбор – франк официальный сайт твой шанс на победу! Регистрация на портале азартных играх «Франк» не отнимет много времени. В азартных играх FrankCasino игрок сможет элементарно обнаружить раздел авторизации на заглавной странице платформы.
Получайте массу удовольствия, развлекаясь в надежной компании сторонников. На текущей странице mr bit casino официальный сайт вход показано немало конструктивной информации о играх на компе. Число сетевых игр увеличивается с каждым годом. По игрушкам определенного типа проходят большие соревнования.
На портале джойказино бездепозитный бонус представлено большое число игрушек. Очень большие суммы в игральных аппаратах – это легкий способ дешевно передохнуть и опробовать свою фортуну. В целях познакомиться с площадкой существует демо-счет.
Фирма sotni.ru реализует axima мерида плитка в течение пятнадцати лет. Достойный и авторитетный продавец всегда сможет предложить многочисленный подбор облицовочного покрытия для коридора.
Дары моря более чем полезны, так как содержат невероятно большое множество витаминов http://allbaro.net/index.php?mid=Doc_Luther_Chang&document_srl=358414. Из морских продуктов делают крайне аппетитные кулинарные изыски. Общество потребляет дары моря уже слишком давно.
Check out our remote java jobs at the remote job
You need to be a part of a contest for one of the finest blogs on the web. I'm going to highly recommend this web site!
1000 Backlinks
With that being said, I am very excited to meet the head of banks, Fintech and crypto investors who dream of disrupting the Fintech arena.
If you are one of those individuals, let’s explore ideas together.
Ankit Jain - Join me on my journey to disrupt the Fintech field and create a frictionless banking experience for upcoming generations.
WEB Designing Services in ghaziabad
The blog is quite resourceful, however a touch of the professionals can diversity it even further. Our experts promise a fine quality all assignment The best experts in the business are here to take care of your academic needs.
Hey thanks for write this content on your website keep posting more content.software companies in kanpurdigital marketing agency
static website cost
You have shared a very informative article. I was looking for this kind of unique information. Please share more related information so I can get more knowledge.
-Web Development Services
This is one of the most beautiful blogs I've ever seen, and it's quite enjoyable. For me, this is a very useful site, and one of the most useful blogs I've ever seen.Custom Web Design and Development
Thanks for sharing such a great information.It really helpful to me.I always search to read the quality content and finally i found this in you post. keep it up!Hire A Web Developer
I enjoy this kind of blogging; please continue.
SEO Services NYC
Thank you so much for your post; it has given us a terrific idea.
Custom Web Developer
Best SEO Tool
Great post on Integer Average Of 2 Integers, thanks for sharing , keep posting Software Testing Classes in Pune
Thank you so much for your post; it has given us a terrific idea.
Here is sharing some data analytics BMC Remedy concepts may be its helpful to you.
BMC Remedy Training
Good information.
For the most current and accurate information on Kenya trade statistics, I recommend checking Import Globals. For more information about global import export data visit our website.
Kenya Import Data
Your Expertise offers us a concise yet essential solution for calculating the average of two integer values. This straightforward query simplifies arithmetic operations, providing a practical tool for data processing tasks. Its efficiency lies in its simplicity, making it a valuable addition to any programming toolkit. With clear instructions, it serves as a reliable resource for app development in los angeles seeking streamlined solutions to mathematical computations and to resolve more bug fixed of an algorithms.