tofucoder;

100% meat-free code

Month: May, 2014

Counting Sort in Ruby

I stumbled on this article from Austin G. Walters on reddit. It’s about a C implemention of counting sort which is restricted to integers but is of complexity O(n), if the range of the elements is in the order of n. I did a quick implementation in Ruby to see if I could beat Ruby’s Array#sort. Here it is:

class Array
  def counting_sort
    min,max = self.minmax
    histo = Array.new(max-min+1,0)
    self.each { |e| histo[e-min] += 1 }
    sorted = []
    histo.each_with_index { |e,i| e.times {sorted << i+min} }
    sorted
  end
end

Turns out Array#sort is  way faster than this implementation. It’s more than twice as fast on an array of 1 million elements. I assume that Array#sort is not implemented in Ruby but in native code.

Ruby: retrieve tweets that contain a certain #hashtag

Interacting with Twitter is pretty easy in Ruby. First you have to install the twitter gem

gem install twitter

To use this gem you need to register your application with Twitter here to get your CONSUMER_KEY and CONSUMER_SECRET.

The connection to Twitter is established in the following manner

client = Twitter::REST::Client.new do |config|
  config.consumer_key = CONSUMER_KEY
  config.consumer_secret = CONSUMER_SECRET
end

Now it is very easy to do a search on all recent tweets. The following loop prints all tweets of the last 24 hours containing #hashtag

now = Time.now
catch :done do
  client.search("#hashtag", :result_type=&gt;"recent").each do |tweet|
    diff = now - tweet.created_at
    throw :done if diff &gt; 24*60*60
    p tweet
  end
end

Based on this I built a little webpage that shows how much is tweeted about german soccer clubs: twuli.de