Blog Archive

Labels

Search This Blog

Saturday, April 1, 2017

STL Algorist; Hackerrank Solution to Birthday Cakes

Modern C++ STL Algorithm Series; Part - 001
Today:
std::count, std::max_element, std::istream_iterator


So, we have this problem birthday cake candle on Hackerrank. Its a very easy problem. :-)

Problem:
Basically, the problem reduced to:

Find the tallest cake candle within a given array and find out how many times it occurs.

As usual, there are several ways to approach this problem. But the fastest I can think of is anyone that involves traversing my favorite STL container... std::vector. :-)

The algorithm:
  • Let vec be the array of integers containing the heights of the cakes
  • Find Max to be the maximum element in vec
  • Count the number of times Max occurs in vec as Count.
  • Print Count
Simple right? Ok, let us see a newbie's C++ code.

-------------------------------------------------------------

-------------------------------------------------------------


As you can see from the code above, yea. It looks neat and documented... (err.... Don't mind me). But there is a serious problem there. Every reader of the code will require more brainwork than necessary to understand the code. 

The Standard Template Library is so powerful and short that it just works well for our problem. It will require much less brainwork to read code heavily dependent on STL.

We can use certain STL elements to reduce work for ourselves. 

  1. Use std::copy to copy elements from and std::istream_iterator<int> into the vector.
  2. Use std::max_element to find the maximum element in the array
  3. Use std::count to count the number of times the maximum element occurred. 
Remember std::copy takes three iterators as arguments. The first two iterators are InputIterators that represents the range of elements to copy. The last argument is an OutputIterator.

We use std::istream_iterator<int>(std::cin) to create an iterator that produces elements from std::cin whenever dereferenced, the iterator will be equal to an end iterator (a default constructed std::iterator<int>() ) whenever std::cin reaches End-of-File.

We use std::back_inserter to insert an element into the back of the vector. std::back_inserter basically produces an iterator such that when assigned to, it does a push_back operation on the container it was created to.

The whole code can be shortened to:

-------------------------------------------------------------

------------------------------------------------------------- 

Saturday, February 25, 2017

Welcome, Timothy

I've made several "one-off" posts about resuming blogging. Maybe, here's another short one. :-). I'll resume... Hahaha

I just tried unsuccessfully embedding Coliru into this blog.

This post will be taken down when I have something more reasonable to say. :-)