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

Tuesday, September 22, 2015

September Projects

So, I am back working on a new Project. Didn't want to just jump into the next post without saying Hi.

Between February and now, there's been alot of goodies, but thats not for the public eye. :-)
The Project is on the Design of a Virtual Subsonic 2D Wind Tunnel. I will be writing a Software in C++ to simulate the flow and behavior of Air over various surfaces.

I will set up a page here and describe it. until then, :-)

Friday, February 13, 2015

Resuming Blogging

It's been almost 2 years since I started this blog, and I abandoned it for some reasons including my laziness, my parents' death, and a few other challenges.

Anyway, the good news, is that: I have finally found a reason to resume blogging, but this time with a realistic promise of at least 1 blog-post every month. This will not commence until later this year.

A lot has happened, and lots of things are still happening. Though, despite the fact that I am in my 20s, I haven't started growing beards... :-). Anyway, No bald head, no grey hairs, Body still intact, its a great reason to Thank God who has had much mercy on me.

I also undertook an Amazing Internship with a Multinational Energy Company. It was one heck of an amazing time. That story will be shared in another blogpost.

Well, let me give you a peck of what is to come.
  • C++14 and the Libraries I have been writing
  • Lessons I have learnt from my role model and mentor, Dr. Myles Munroe
  • My Bible stories
  • A Love story
  • My hilarious experiences in Lagos as a first timer

The reason I found for resuming this blog is quite funny. Some staff of the School I study with, had their way with a very crazy and somewhat "pathetic" academic timetable that inherently slows down every student's academic plans by several months.

For example, the undergraduate Academic calender insinuates that every student who finished a session in December 2014 will not finish the next session until March 2016!

How fantastic can that be? The wisdom and rationale behind such heinous timetable really beats my imagination till date! ...Bunch of ..... .(Well, use your imagination, but I didn't say anything. :-) )


Until my next post,
Have a wonderful time,
The amazing fellow at the other end of the line, Timothy.

Friday, September 13, 2013

Funny Programmers Jokes

This is not a complete list but. . . its a draft of what I started working on lately... I have over 20+ now and 10 are definitely as funny or more funny than these...(for a few reasons, I decieded no to post all I have).
I should have a whole lot of these in a month or two... And will post them when I am done This time, I promise not to repeat what I did at last posting...... (Frankly, I've been overwhelmingly busy)

Enjoy! --> Share the link and Comment!
  1.  Pseudo-code is the only programming language that never complains of syntax errors
    -----
  2.  The C programmer hates competing with a PERL programmer when it comes to regular expressions.
    -----
  3.   If Internet Explorer 6 was implemented in Java. . . . A snail wouldn't have been the slowest shelled thing on earth.
    -----
  4.  If processors could talk, and you are running a WebServer written in Java, the processor would have said: “Why the hell are we always traveling from earth to Pluto just to reach Mercury?” --Indirection Problem.
    ----
  5. The Assembly programmer always feels superior in running at almost 100% hardware speed but then.. What else can he boast of?
    ----
  6. Python may be as slowwww as the Old Volkswagen Beatle... but she beats every other language in elegance. → #Only an ID10T tastes and hates Python Programming Language.

Tuesday, August 7, 2012

Python Image enhancing snippet

Imaging and basic image processing with Python....

This is not going to be the typical and formal kind of blog you may know... err... em just saying, just incase;-)
So.... Ummm Python image enhancement code.

IMAGES and IMAGE ENHANCEMENT

Images and Python Imaging Libraries (PIL)

THE Geeky DEFINITION OF AN IMAGE

Images are basically binary files that contains color definitions and mappings, pixel data, compression/lookup-tables, and visual data enities of an image such as dpi(resolution), width and height, structured in a well organised format for easy read and write by computer applications. They may also contain other properties such as EXIF data and other general or unique properties as defined by the image format.

First things first, download PIL here... Download the most recent version you see there.

Well, I'll skip some stories and get you what you want...
Next, we may want to try this code

There are 3 levels of automatic image adjustment I use.... The one implemented here is only 2, the 3rd is somewhat complex and its about 100lines.....

Here is a fully usable code

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

import operator
import Image
import ImageOps

def equalize(im):
ims = im.convert("L")
h = ims.histogram()
lut = []
for b in range(0, len(h), 256):
# step size
step = reduce(operator.add, h[b:b+256]) / 255
# create equalization lookup table
n = 0
for i in range(256):
lut.append(n / step)
n = n + h[i+b]
# map image through lookup table
#return im.point(lut*im.layers)
return im.point(lut)

def autoOptimize(im):
try:
equalize(im)
except ValueError:
print "Error in Level-1 optimization method!!!!!"
im = ImageOps.autocontrast(im, cutoff = 0)
return im

-------------------------------------------------------------------------------------------
With this piece of code above, you may be able to automatically enhance images....
Just copy and paste the code, save the file as any name you may wish <Optimizer>(mine)... Import it to your code and juast call the autoOptimize function... example

test.py
--------------
import Optimizer
image = open('flowers.jpg')
Optimizer.autoOptimize(image)
image.show()
---------------------

PLEASE NOTE THAT The equalization algorithim was from EFFBOT.

I would add a step-3 optimization algorithm soon.

Thanks!. TiM
err... I am currently writing exams... i will update by 19th October, 2012 21:00hrs GMT :::Sorry for the inconveniences. 

UPDATE: Many things happened between the date I posted this and this update... more than 300 days later..
  • like, participating in ACM-ICPC 2012 South African Regional Contest
  • my Dad passing away... :-(
  • taking on a new programming language... C#
  • ...and several hundreds more that need not to be mentioned
So, I will just give you external links to help out...
UNDERSTAND SOME BASICS
for beginners

some advanced stuff... buy the book

That's that for this...