Author Archives: joe

About joe

.NET developer and board game geek located in the greater Atlanta region.

Project Euler: Problem 12 in Ruby

I took a couple swings at problem #12 before I finally got it. I’m definitely over my head mathematically, but that’s part of the fun and I’m certainly learning a lot along the way. Big thanks to Dr. Math for his excellent explanation of how to find a number’s number of factors.

Problem #12

What is the value of the first triangle number to have over five hundred divisors?

Surely it’s not the perfect solution, but it ran in under 4 seconds on ruby 1.9, so I’m happy with it. Looking at it now, it all seems obvious but I must have started over at least a dozen times. Here are a few recurring Project Euler themes I’ve picked up on, as applied to this problem.

  1. Like every other Project Euler problem, don’t repeat your calculations, cache it! Prime number computation is heavy.
  2. If you don’t have to store something don’t. In this case it’s enough to count the distinct factors, you don’t have to store them.
  3. Cut down your data set. Since we’re looking for a number that has over 500 factors then we don’t need to start looking until after the 500th triangle.

Enough talk, here’s the code:

require 'mathn'

primer  = Prime.new
primes  = [ primer.next ]
seed    = 500
n       = (seed * (seed + 1)) / 2
i       = seed + 1

def count_prime_factors primer, primes, n
  total = 1
  max   = Math.sqrt(n).to_i

  while primes.last < max
    primes << primer.next
  end
  
  primes.each do |i|
    count = 0
    while n % i == 0
      n = n / i
      count += 1
    end
    if count > 0
      total *= count + 1
    end
  end

  total
end

while(count_prime_factors(primer, primes, n) < seed)
  n += i
  i += 1
end

puts n

Fetching Local Tweets in Ruby

Tests take forever because of all the HTTPRequests

Tests take forever because of all the HTTPRequests

As planned, I wrote a little class incorporating Geocoder and twitter_search so you can search for tweets within x miles (or kilometers) of an address.Geocoder does an excellent job of parsing addresses and twitter_search is simple and efficient.

Four thumbs up

Next phase I’d like to set up a little web interface showing tweets and tweeters. There’s something funny about hitting the internet to find out what’s going on around you.

Here’s the class, as you can see there are a few overridable defaults

require 'rubygems'
require 'geocoder'
require 'twitter_search'

class Twitter_Interface

  attr_accessor :tpp, :distance
  attr_reader   :address, :geocode
  attr          :geocoder, :client 

  def initialize addr = "", dist = "2mi", pp = 15
    @client   = TwitterSearch::Client.new
    @tpp      = pp
    @distance = dist
    @geocoder = initialize_geocoder
    set_location addr
  end

  # Could also use Yahoo API, but it requires API key.
  def initialize_geocoder geocoder = Geocoder::GeoCoderUs.new
    geocoder
  end

  def format_geocode geocode = @geocode
    if is_geocode? geocode
      return "#{geocode.latitude},#{geocode.longitude},#{@distance}"
    end
    ""
  end

  def tweets
    @client.query :geocode => format_geocode, :tpp => @tpp
  end

  def address_to_geocode addr = @address
    if addr == ""
      return ""
    end
    @geocoder.geocode addr
  end

  def is_geocode? geocode
    geocode.respond_to? "success?" and geocode.success?
  end

  def set_location addr
    @address = addr
    @geocode = address_to_geocode @address
  end

end

And here’s how you use it

t = Twitter_Interface.new "1600 pennsylvania ave nw washington dc"

#print the twitter query formatted geocode, default distance is 2 miles
puts t.format_geocode

#=>"38.898748,-77.037684,2mi"

#fetch the Twitter_Search::Tweets within 2 miles of the white house!
tweets = t.tweets

Download a .zip of the code / tests

Fun with Wordle

I saw a post on proggit about using tag clouds to detect code noise and thought I’d have some Wordle fun of my own.

Here’s a tag cloud I generated off of my current rss feed.
My Tag Cloud

And here’s a tag cloud I generated off of my google reader feed.
My Feeds

I think my feed cloud is skewed towards tech news since I pulled it up so early, before all the lazy developer bloggers got to posting. Also, I just realized that the images I pulled are both really similar. There are a lot of options for messing with the fonts, colors and layouts…I’m just boring.

Searching Twitter with Ruby

After seeing this a few days ago, I thought it’d be fun and easy to whip up a little script that would dump tweets from around my area. Unfortunately, it was neither. I won’t bore you with my troubles, suffice it to say GitHub has now been added to my list of gem repositories.

I haven’t gone through much of the actual api yet, but so far it looks great. I did play around with a few different wrappers before finally getting down to business with twitter_search, which is nice, and thin, and jived nicely with my goal.

So here’s the code to fetch the last 15 tweets from ( thanks geocoder! ) my area. Simple, eh?

require 'rubygems'
require 'twitter_search'

tweets = TwitterSearch::Client.new.query :geocode => "28.599630,-81.289176,2mi"

tweets.each do |t|
  puts "@#{t.from_user} - #{t.text}n"
end

The next step is to figure out how to look up geocodes automatically, and maybe build some sort of web interface. But not tonight.

Implicit Getters and Setters in ColdFusion

Thanks to CF8’s new onMissingMethod method, it’s trivial to implement implicit getters and setters. As easy as it is, I couldn’t google up any code. Since it’s not the kind of thing I’d rather search for than write myself, I thought I’d go ahead and do you the favor and post it here.

I realize there’s a nasty stigma attached and I don’t disagree that it’s bad practice, but it does come in handy when building a proof of concepts or programming exploratoraly.

So here you go, irregardless of whether or not it’s bad practice:

<cfcomponent name="BaseObject">

	<cffunction name="Init" output="no">
		<cfargument name="instance" default="#StructNew()#"/>

		<cfset SetInstance( arguments.instance )/>

		<cfreturn this/>
	</cffunction>

	<cffunction name="OnMissingMethod" output="no">
		<cfargument name="missingmethodname"      required="yes" />
		<cfargument name="missingmethodarguments" />

		<cfset var prefix = Left( arguments.missingmethodname, 3 ) />
		<cfset var suffix = Mid( arguments.missingmethodname,
			4,
			Len( arguments.missingmethodname )
		) />

		<cfif ( CompareNoCase( prefix, "get" ) eq 0 ) and Has( suffix ) >
			<cfreturn Get( suffix )/>
		</cfif>
		<cfif CompareNoCase( prefix, "set" ) eq 0>
			<cfreturn Set( suffix, arguments.missingmethodarguments.1 )/>
		</cfif>

		<cfthrow message="Method #arguments.missingmethodname# not found" />
	</cffunction>

	<!--- private on down --->

	<cffunction name="GetInstance" output="no" access="private">
		<cfreturn variables.instance/>
	</cffunction>

	<cffunction name="Get" output="no" access="private">
		<cfargument name="field" required="yes"/>

		<cfset var instance = GetInstance()/>

		<cfreturn instance[ arguments.field ]/>
	</cffunction>

	<cffunction name="Has" output="no" access="private">
		<cfargument name="field" required="yes"/>

		<cfreturn StructKeyExists( GetInstance(), arguments.field )/>
	</cffunction>

	<cffunction name="Set" output="no" access="private">
		<cfargument name="field" required="yes"/>
		<cfargument name="value" required="yes"/>

		<cfset var instance = GetInstance()/>
		<cfset instance[ arguments.field ] = arguments.value/>

		<cfreturn Get( arguments.field )/>
	</cffunction>

	<cffunction name="SetInstance" output="no" access="private">
		<cfargument name="instance" required="yes">

		<cfset variables.instance = arguments.instance/>

		<cfreturn GetInstance()/>
	</cffunction>

</cfcomponent>

Download it and the MxUnit Tests!

IT Conversations and Other Podcasts

I’ve been listening to the IT Conversations Network for a few weeks now, and I couldn’t be happier with it. In short, it provides an aggregated rss feed of free tech podcasts, so if you love podcasts as much as I do, you should give it a shot.

In addition to the always great Stack Overflow Podcast, there were three I found particularly interesting this week.

While I’m on the subject here’s a few of my other favorites. In order of how much I love them:

All free, all great. Go!

MXUnit and Me

mxunit1If you’ve been keeping up with my blog over the last couple months, then you already know that I’ve been experimenting with test driven development. I love the work flow, the way it makes me view my code, and the peace of mind…I just don’t know that it will pay off in my work environment. Hence the experimentation.

Most of my TDD dabbling up to this point has been done in Ruby. I’ve finally gotten around to messing around with some of the major ColdFusion testing frameworks: cfunit, cfcUnit and finally MXUnit.

After doing small projects with each of them, I’ve finally decided to settle down with MXUnit. It’s got decent docs, a nice work around for private methods, I dig the web interface, the eclipse plug-in is great and creating my own stubs for the generator was a snap!

In short: Two thumbs up!

Here’s my test. I’m still really new to this sort of thing, so I’d love feedback should you feel so inclined:


	

		function Setup() {
			this.cfc = CreateObject( "component" , "BaseObject" );
			this.cfc = this.cfc.init();
	
			makePublic( this.cfc, "SetInstance" );
			makePublic( this.cfc, "Set" );
			makePublic( this.cfc, "Has" );
			makePublic( this.cfc, "Get" );
			makePublic( this.cfc, "OnMissingMethod" );
		}
	
		function TestSetInstance() {
			var value = "a";
			AssertEquals( value, this.cfc.SetInstance( value ) );
	
			value = StructNew();
			AssertEquals( value, this.cfc.SetInstance( value ) );
		}
	
		function TestGetInstance() {
			var value = "a";
	
			this.cfc.SetInstance( value );
			AssertEquals( value, this.cfc.GetInstance() );
	
			value = "b";
			this.cfc.SetInstance( value );
			AssertEquals( value, this.cfc.GetInstance() );
		}
	
		function Testinit() {
			var value = "a";
	
			this.cfc = this.cfc.init( value );
			AssertEquals( value, this.cfc.GetInstance() );
	
			this.cfc = this.cfc.init();
			AssertEquals( StructNew(), this.cfc.GetInstance() );
		}
	
		function TestSet() {
			var field = "a";
			var value = "1";
	
			AssertEquals( value, this.cfc.Set( field, value ) );
	
			field = "w";
			value = "2";
	
			AssertEquals( value, this.cfc.Set( field, value ) );
		}
	
		function TestHas() {
			var field = "a";
			var value = "1";
	
			AssertEquals( false, this.cfc.Has( field ) );
	
			this.cfc.Set( field, value );
			AssertEquals( true,  this.cfc.Has( field ) );
	
			field = "w";
			value = "2";
	
			AssertEquals( false, this.cfc.Has( field ) );
		}
	
		function TestGet() {
			var field = "a";
			var value = "1";
	
			this.cfc.Set( field, value );
			AssertEquals( value, this.cfc.Get( field ) );
	
			field = "w";
			value = "2";
	
			this.cfc.Set( field, value );
			AssertEquals( value, this.cfc.Get( field ) );
		}
	
		function OnMissingMethod() {
			var value = "a";
	
			AssertEquals( value, this.cfc.SetSomething( value ) );
			AssertEquals( value, this.cfc.GetSomething() );
		}

	

Click to download the component I’m testing and the file above. Now.