pairwise maximum product

So I started doing the Coursera course for Algorithsm, mostly since I was spending a lot of time on SNS and not really learning anything. I thought to might as well start with a lil programming since I have long left it tbh.

For the first week of the course, I had a very simple problem statement

In this problem, we’re given an array, or a sequence of n numbers. And our goal is to find a number which can be obtained by multiplying some two numbers from this sequence.

So there would be two inputs when you run the program like –

3

1 2 3

The output should be the largest number, which is a multiplication of the pair, in this case it would be 6.

For another sample input

4

-10000 -20000 10 20

The output would be 20000000 because multiplying two negative numbers gives you a positive number. I was able to solve it however only after doing a stress test with multiple implementations and matching the results of each one. It really did take a lot of time to reach the answer or maybe I wasted a lot of time in not going to the stress test option first.

Below is a working and 100% successfuly solution. Do try it out and let me know if you guys have any problems running it.

require 'bigdecimal'
# Input the number of numbers
n = readline
# Input the list of numbers
array_list = readline.split(' ')
# Initializing the variables
max1 = BigDecimal("0")
max2 = BigDecimal("0")
min1 = BigDecimal("0")
min2 = BigDecimal("0")
min1_index = 0
max1_index = 0
# Finding the Biggest and Smallest Number and storing their index
array_list.each_with_index do |value, index|
if BigDecimal(value) > 0
if max1 < BigDecimal(value)
max1 = BigDecimal(value)
max1_index = index
end
end
if BigDecimal(value) < 0
if min1 < BigDecimal(value) * -1
min1 = BigDecimal(value) * -1
min1_index = index
end
end
end
#Finding the second biggest and smallest numbers.
array_list.each_with_index do |value, index|
if BigDecimal(value) > 0
max2 = BigDecimal(value) if BigDecimal(value) <= max1 and BigDecimal(value) > max2 and max1_index != index
end
if BigDecimal(value) < 0
min2 = BigDecimal(value) * -1 if BigDecimal(value) >= min1 * -1 and BigDecimal(value) < min2 * -1 and min1_index != index
end
end
#Checking if any of them is 0, else multiplying them accordingly
if( min1 != 0 or min2!= 0 or max1 != 0 or max2 !=0)
if(max1 * max2 < min1 * min2)
result1 = (min1 * min2)
else
result1 = (max1 * max2)
end
else
result1 = min1 * max1
end
#outputting to a format to pass the tests in Coursera
puts result1.to_s("F").split(".")[0]

5000+ lines of SQL Query

Why you should not use online code formatting tools? Coz most of them suck at their job.

A friend wrote a query for an Oracle Report which had 52 unions and spanned over 5000 lines. Tested and all working fine, before saving the report, she decided to format and indent the code using an online code formatter one of many many available all across the internet.

And it broke it just enough to not run anymore and just not enough to notice the difference immediately.

The error message was pretty clear that one of the unions had less/more number of selected columns but no message on which union, thanks to the bad code analyzer of Oracle BI EE.

As always, ruby magic always comes to rescue when you are in a tight pinch.

def analyse file_path
file = File.open(file_path, "r")
counter = 0 # counter for having a 2D Array
writefile = false
array = Array.new
file.readlines.each do |line|
if line.start_with? "SELECT"
writefile = true;
array[counter] = Array.new
end
if line.start_with? "FROM"
writefile = false;
counter = counter + 1
end
array[counter].push line.strip if writefile == true
end
require 'csv'
CSV.open('.\working_output_analysis.csv', 'w+') do |csv|
array.each { |ar| csv << ar }
end
end

The code is pretty straight forward to read. It starts with the line starting with “SELECT” and ends before the line starting with “FROM”. We had a total of 52 unions, so I just needed to store that list of selected columns from all these 52 unions in an Array. We cannot really define a 2-D array in Ruby however we can always define an Array within an Array and that solves our purpose of Multi dimensional Array.

The script provided us a nice sheet with all the column names and helped in figuring out the incorrect SELECTED list of columns from a specific union list.

Phew!!

How do we start?

Hi Guys

Long time no see 🙂 sometimes I feel like I should tell that to myself as well.

So how do we start, we start by noting down what we need to do, and while we are at it, we note down what we didn’t write in the first place and also few more things which you should have thought of before. To do things is to improvise, learn and also to keep on adding more things to do, obviously a to-do list never ends, because to do something or to learn something, you need to do a lot of things 🙂

To understand that lets write a blog post 🙂 This is going to be quick. All you need is rails setup in your system.

Lets start with creating a blank app

rails new todoapp # this will create a blank slate for you to work on

rails g scaffold todo task:string complete:boolean parent_task_id:integer # this will create your model/views/controller/migration etc etc files which you will do the work for you

rake db:migrate # if this throws an error, you gotta do “rake db:setup first” this will create your database migration and the schema for todo tasks.

Now we need to build something like the below to sorta have a parent child relationship between the tasks. Why ? just read the 2nd para again from top.

Parent Task 1
—- Child Task 1
—- Child Task 2
Parent Task 2
Parent Task 3
—- Child Task 1
——– Child Task 2

In your new and shiny app/models/todo.rb add these two lines to create the parent child hierarchy.

has_many :child_tasks, :class_name => 'Todo', :foreign_key => "parent_task_id"
belongs_to :parent_task, :class_name => 'Todo', :foreign_key => "parent_task_id"

Now a bit of magic is needed to the views to allow us to easily select the Parent tasks for any child task.

Head over to your app/views/todos/_form.html.haml or *.erb file depending on the templating engine and change the f.parent_task_id to a collection_select

.field
= f.label :parent_task_id
= collection_select :todo, :parent_task_id, Todo.all + [Todo.new], :id, :task

This will allow us to choose a parent task, whenever we are creating a new task with – not a very bad hack? 😛

Finally in the show and index page, we need to display the parent task.

replace your todo.parent_task_id with
Todo.find_by_id(@todo.parent_task_id).task rescue "No Parent Task"

And the end result is tada!!!

Todoapp

Series – Coding Interview Book (part 1)

So, I have started to have a look at the Coding interview book. Have been reading about how interviews happen at top 5 IT firms like Google, Amazon, Apple Inc etc.

To think, or even dream, I could be part of such awesome organizations is like a very very far fetched thought. Wouldn’t have my hopes so high ever.

Then again, that doesn’t mean, I shouldn’t start practising some cool coding questions for some interviews. In the first few pages, I found out a few easy questions, which I will try to write code of and put it somewhere online for everyone’s review. Yeah! Together we learn 😛

The questions/sample exercises seem to be pretty easy. So here we go!!!
1. Design an algorithm to sort a list
Question: What sort of a list? An array? A linked list?
Answer : An array.
Question : What does the array hold? Numbers? Characters? String?
Answer : Numbers.
Questions: And are the numbers integers?
Answers : Yes.
Question : Where did the numbers come from ? Are they IDs ? Values of something ?
Answers : They are ages of customers.
Question : And how many customers are there ?
Answers : Around a million.

I will leave some analysing of the question to you guys. Let me just quickly write down some code for solving the problem.

So the code is available here magic_sort.rb You guys can have a look, I am using the Benchmark module of ruby to capture the execution time. As always insertion sort is faster for smaller arrays. But when the array size increase beyond 10000, the performance is significant for our magic sort 🙂
Have a look and let me know, if we can improve it even further.

MongoDB class

Hey guys! Since we started with the MongoDB course. Just saw the first video, which has some writing code in it, so I thought, I will write some, since ❤ ruby ❤
The link for the class video is – link. You can go ahead have a look and see, what it does. I just wrote a similar code which lets us do the same thing in ruby. Using sinatra( bottle is being used with python in the video)

# Steps
# 1. Install the gem sinatra
gem install sinatra
# you you skip rdoc and ri using
# gem install sinatra --no-rdoc --no-ri
view raw install_gem.sh hosted with ❤ by GitHub

# hello_world.rb
# This will manage routes and display the content.
# I am sure, you did watch the video before checking this out.
require "sinatra"
set :bind, '127.0.0.1'
set :port, '8080'
get '/hello/:name' do
"Hello #{params[:name]}!"
end
view raw hello_world.rb hosted with ❤ by GitHub

# just simply run the ruby file that we created.
ruby hello_world.rb
view raw run_server.sh hosted with ❤ by GitHub

Thats it folks, we are done. Head over to http”//127.0.0.1:8080/hello/world and see for yourself.

MongoDB courseware

Hi Guys, Long time no see. Just been busy with some stuff. Today I am going to talk a bit about MongoDB. Well its too much in news, these days, your clients wanting you to use it, people telling you about scalability factors, even if you are just bulding a food recipes site. sigh!

So I thought, I might as well jump onto the bandwagon to learn some mongodb as well. So like fortunately, I found out that 10gen the company behind mongodb is having an online courseware for learning mongodb. So I enrolled with it. Oh Well, yeah its in python, I ❤ ruby. so what? Let me try and have a series of blog posts, with similar code in ruby as is taught in class in the courseware in python. Hope you guys will learns something with me too.

Time to learn 🙂

Don’t forget to check the link

A simple Tweet Retweeter

Hi Guys, So well on a lazy saturday afternoon, when you don’t have anything to do, you get this feeling to make something. So well what you do, you just make something simple, Burgers, fast food anything that you like. But well people like us who think, they are so called developers, have to feel the burden of creating something which which solve more a problem more important than the “What to have for lunch?” problem.

Anyways, so well, I have two twitter accounts, 1) @sudipto05 <– which I use and do follow me here and 2) @delhianimeclub which is my club’s twitter accout, which well, I never use, but well, its gets updated with the posts that are put on our facebook page. (If you are into anime, do like us on facebook). So the problem at hand, I had to manually retweet the tweets of @delhianimeclub from my other account, you know cross promotion, stuff like that. But this wasn’t really cool. right?

So what do Rails developers do?

This is what they do

rails new retweeter

Lets add a few gemfiles, of late I have had to work on HAML and Bootstrap so lets add those gems. Checkout my gemfile from link. We wont be really needing the twitter bootstrap gem for this iteration of the project, but we will be certainly using it for the making a statistics application for our twitter account. I don’t really like postgresql, but I wanted to host it on heroku,which only has support for pg. Oh yes, just forgot, two of the most important gems that we are going to use

1. Twitter gem – will let us post fetch and post tweets only with what 2 lines of code! I could have tried to use Twitter’s rest api too, but then, who is going to make lunch? huh?

2. Rufus Scheduler – I love this, its an awesome gem for scheduling your jobs, since we are going to check if new tweets are posted after regular intervals, we need some kind of cron job running behind our app, this is going to make it super easy.

After adding the gem files, just

bundle install

So here we go, now some actual coding starts, well yeah! twitter bootstrap gem doesnt like windows at all, so its better if you add the css and js files manually from link. You know right? they go into the assets folder 😛

Well, we are going to save the tweets in our database too, so lets generate a Tweet model with three fields.

rails g model Tweet tweet_id:string tweet_text:string tweeted_at:datetime

The advantage of specifying the attributes while generating a model is that they get automatically added to both the migration! duh! and also in the attr_accessible in the model file. Saves you 10 seconds of typing 😛

and afterwards to run the migration and setup our database

rake db:migrate

lets start with our Scheduler first. Create a new file in the config -> initializers directory, well you can name it anything, I just named it task_scheduler.rb and put in the snippet of code. A very simple explanation of the code within the file.

1) Requires the rufus scheduler gem, so we add the require line.

2) Create a new instance of the scheduler with

scheduler = Rufus::Scheduler.start_new

3) And lastly we simply call a class method within a block, which will call the method every 1 minute, now you can choose the duration of the interval according to your needs, 1 minute seems fair enough, its not like we post tweets faster. What? It requires aesthetics for tweeting? huh?

Okay so we are done with 33% percent of the work, Lets move onto our model file, Remember Tweet model that we created. Check out the file from link. Lets see what gibberish we have to put in the code now.

1. First we get the recent tweets of the user from whose account, we are going to retweet. latest_tweets = Twitter.user_timeline(“account_name”)

2. Then we run a simple loop through the recent tweets that we get from twitter and check if the tweet is present in the database, if not, the tweet will be retweeted and saved in the database.

3. Every tweet has its unique id which you can access using Tweet.attrs[:id] or Tweet.attrs[:id_str] which has the same value as :id_str, just use anyone you like, the twitter api says to not use the @attrs[:id] but thats applicable only for javascript code.

4. Oh yes! I have put this whole block of code within begin rescue end block, this twitter gem seems to throw in some weird exceptions sometimes, so just to log the errors, you can use the logger of your choice for this.

Okay, Guess we are done with 70% of the work 😀

So the next step is to create a new twitter application which is going to be used to post your tweets, don’t worry, we just need it for the config keys, nothing fancy.

1. Head over to link, to create a new twitter application. Oh yeah! sign in with the twitter account, using which you want to retweet the tweets from your other account.

2. Fill in the name and all description, just anything who cares 😛

3. After you are done with creating the app, go to settings and change the application type to “Read and Write” after this change save it and head back to the Details tab and create new access tokens. What? can’t you see, there is a button on the bottom to create new tokens.

These tokens will be used to authorize our rails app to post the tweets, oh yeah! the name you put for this app is going to show below every tweet 😛

You need to add these keys to your environments.rb file. Just check out the files here and add the lines for twitter config to the respective environment file in your app.

And we are done, just start the server and see the magic. Our initializer will run after 1 minute and fetch the latest tweets, save them in database and post them to our other twitter account. Thats it. What we have made a retweeter in less than what 30 lines of code, i guess, that is why I love ruby on rails. Oh! wait, you are going to tell me, that I made a rails app, just for this, when I could have done this using just a single ruby file, well yeah! the reason being, we are going to extend this web application in many many ways, so don’t forget to check the blog for updates. The code of this application is hosted on my github.

No Ruby Version Manager on Windows.

Its true that there is no ruby version manager on windows, which makes life really difficult for a lot of ruby or rails developers I am sure, Well it did for me at least. A lot of applications developed in version 1.8.7 aren’t compatible with the new version. A lot of applications also fix themselves to use only specific versions of ruby, so there is not much we can do, unless you are a mega-geek and can change a lot of things and ofcourse have a lot of time. On linux we always have had RVM to solve this problem which lets us have different versions of ruby, different gemsets for each version of ruby, makes life really easy. But what for the windows developers? Thankfully a noble soul known as Gordon Thiesfeld made something amazing known as pik. which essentially works the same as Ruby version manager, with a few differences in installations but none in usage. Both of them are equally easy to use.

I am not going to write about how to install and use RVM, since there is enough help for that on the WWW. But Since I love windows users(I being one). We will have a walk-through with pik today. Before we start you can have a look at the github page of the project – https://github.com/vertiginous/pik

Installations –

It does mention that you need to install ruby 1.8.7 first to install pik, Now ruby 1.8.7 is an older version and I wonder, why would I need to install an older version to install a newer version, So first I went ahead and installed ruby 1.9.2-p290 from http://rubyinstaller.org/downloads/ for installing pik. Seems it worked just fine. You can choose to install ruby 1.8.7 first and then install pik, its entirely upto you.

After installing Ruby make sure, you also have devkit installed, if you are a windows user you would know that ofcourse, dev kit is used to build the gems that are developed with native extensions, which means nothing, but those gems are made partially in ruby and partially using c. You can’t miss C anywhere can you. Anyways, I will give a quick guide about installing devkit, since you are going to need it anyways.

Head over to http://rubyinstaller.org/downloads/ and download DevKit.
Installations steps
1. The file you downloaded is just an extractor, extract is to somewhere where you wont delete it by mistake.
2. After extraction, open up CMD and cd to the location where you extracted the files.
3. run

ruby dk.rb init

4. This will let you know the ruby installed in your system.
5. run

ruby dk.rb install

and you are done. Didn’t take too much time, did it?

Now we move on to pik installation steps
1. Fire up CMD and run

gem install pik

2. Now if you type

pik list

you will be able to see that it shows the base version of ruby that you installed. In my case, it shows

* 192: ruby 1.9.2p290 (2011-07-09) [i386-mingw32]

3. There are two ways of adding ruby versions to pik, either you install them manually and add to pik or you just install them through pik. We will see how to install them from pik, since we are going to use pik anyway, less bothersome to do it from pik, than downloading from the internet, installing each of them and then adding to pik.
4. Installing other version of ruby

pik install ruby 1.8.7

And here you go it will install the version of ruby and add that to pik by itself, Less of a hassle. right?
5. Check the versions of ruby installed in your system

pik list

6. Change the version of ruby that you want to use

pik use ruby [verions]

in my case

pik use ruby 1.8.7

7. Don’t forget to use the help if you get stuck.

pik help commands