Category Archives: programming

Project Euler : Problem 27 in Ruby

I’ve taken ill for the last two days, so I’ve been working on a couple Project Euler problems in between trips to the bathroom.

Problem #27

Find the product of the coefficients, a and b, for the quadratic expression that produces the maximum number of primes for consecutive values of n, starting with n = 0.

Since you start with n = 0, you know that b always has to be prime in order to satisfy n = 0.

Next, if b must be prime, and all primes greater than 2 are odd, and we don’t care about expressions resulting in less than 3 consecutive primes (example expression has 40), then we know that all values of a must be odd in order to satisfy n = 1!

I also suspect that for the number of consecutive primes we need to ‘win’, that we only need to look at negative values of a, but I’m having a heck of a time trying to prove it.

027.rb

require 'prime_generator'

# pre-calculate primes
MAX     = 1_000
primer  = Prime_Generator.new MAX
primes  = primer.stack
product = 0
highest = 0

# a must be odd
(0..MAX).each do |i| 
  next if i & 1 == 0

  # b must be prime
  primes.each do |b|
    
    # a can be positive or negative
    [i,-i].each do |a|
      n = 0
      while n += 1 do
        break unless primer.is_prime?(n ** 2 + a * n + b)
      end

      if highest < n
        highest = n
        product = a * b
      end

    end
  end
end

puts product

And here’s the prime generator I’m using:

prime_generator.rb

class Prime_Generator

  attr_reader :stack

  def initialize max = 3
    @stack  = [1,2,3]
    fill_to max
  end

  def fill_to max	
    n = 1
    while true do
      n += 4
      return @stack if n > max
      @stack << n if is_prime? n
  
      n += 2
      return @stack if n > max
      @stack << n if is_prime? n          
    end
  end
  
  def is_prime? n
    return false if n <= 0
    max = Math.sqrt(n).floor
    fill_to(max + 1) if max > @stack.last
  
    @stack.each do |i|
      next if i == 1
      return true if i > max
      return false if n % i == 0
    end
  
    true
  end

end

You can find more Project Euler solutions here: https://svn2.assembla.com/svn/joe-zack-personal/projects/euler/ruby/

The War of The Roosevelts

I’ve been tinkering around with C# and Flex a lot this year, but I haven’t been posting much.

So in the interest of posting *something* I give you…

*drumroll*

THE WAR OF THE ROOSEVELTS!

You, standing in the (uneven?) shoes of Franklin D. Roosevelt, finally get a posthumous chance to stand up to your bullying older cousin Teddy in a game of WAR…well, at least the game of war as I knew it growing up. Wikipedia’s got it’s own ideas.

I lost interest in it by the time I got to the gui, so that aspects (aka as the part people actually see) is a bit…rough. Just a bit. ENJOY!

Here’s the source, but I won’t waste my time looking up the svn link. 😉

ColdFusion CacheLocker

Pay Per Use Locker

Pay Per Use Locker

I ran into a problem the other day where I needed a way to temporarily store data between page requests. Typically I’m able to stash this sort of thing in the session scope, but these requests originated from different sources and I prefer to avoid (de)serializing when I can.

Instead I set up something akin to one of those pay-per-use lockers. You stick your items in the bin, drop in a few quarters, and take the newly unlocked key. Later you come back and use that key to retrieve your items. Your key is now ‘locked’ back into the starting position and the cycle begins anew.

Like one of those pay-per-use lockers you just stash your data, save they key, use the key, trash the data.

Simple as pie.

This isn’t the sort of thing that comes up often, but should it arise I’ve got just the tool for the job!

Example Usage:

// initialize the locker
application.cacheLocker = CreateObject("component","cacheLocker").init();

// store some arbitrary data
key = application.cacheLocker.store([1,2,3,4]);

// then retrieve the data using the saved key
// throws a CacheException if the key doesn't 'fit'
arbitraryNumbers = application.cacheLocker.retrieve(key);

The data is destroyed after being retrieved; it’s a one time only locker.

There are two important things to keep in mind when using this utility:

  1. There’s currently no mechanism for cleaning out lockers, so if you’re not regularly retrieving your data then this thing is just going to grow, and grow, and grow.
  2. The locker is not stored in any sort of persistent memory. If ColdFusion goes down, then the lockers are destroyed.

Enjoy!

Generating Mock Images in ColdFusion

Dummy Image!

Dummy Image!

My co-worker Brian passed an interesting lifehacker post along about dummyimage.com.

It’s a cool site that lets you pass in a width and a height to generate an image which could come in really handy for quickly mocking up web pages.

I can’t believe I never thought of doing something like this!

ColdFusion is a great language for doing this sort of thing, so it was trivial to whip something up quickly.

I was originally writing a file to disk because I didn’t realize you could stream an image variable to the browser, but my other co-worker Jim came to the rescue with the cfimage “writeToBrowser” action!

<cfset params = listToArray(cgi.query_string,"x") />

<cfif arrayLen(params) lt 2>
	<cfthrow message="Input should be like ?[w]x[h]"/>
</cfif>

<cfset width  = params[1] />
<cfset height = params[2] />
<cfset color  = "gray" />

<cfif not (isNumeric(width) and isNumeric(height))/>
	<cfthrow message="Width/Height should be numeric ?100x100">
</cfif>

<cfset image = ImageNew("", width, height,"rgb", color) />
<cfset ImageDrawText(image, "#width# x #height#", 0, 10)>
<cfimage source="#image#" action="writeToBrowser"/>

I’d love to link an example to you, but my hosting plan doesn’t support _cf_image_

Delving into C#

This year I’ve decided to really get into C#. My .NET experience is shall at best so aiming to rectify, I picked up C# in Depth and commenced skimming!

Now, I’ve made my fair share of M$ snide asides, but I’m having a hard time coming to gripes with C#. Everything I run into either “just works” or exceeds my expectations. And the cool features are in fact, quite cool! Color me impressed!

Noob!

Noob!


For fun I rewrote a few of my Project Euler Solutions to buff up on the syntax. After I got the semi-colons and brackets all figured out, I moved on to something a little bigger.

I wanted a simple program to run and benchmark my solutions, so I wouldn’t have to do as much leg work every time I converted a problem. I figured this would be a simple enough thing to do, and it would provide a good foundation for a future gui application and beginning unit testing.

I wanted to share some particulars that I thought were pretty cool, you can grab the code I’m talking about from the google code repository, and follow along…or something.

Generics, Delegates and Lambdas
Generic Collections provide a data structure that I can access and use just like an array, but also provides methods for dealing with delegates.

Delegates are very similar to closures, blocks, procs, and lambdas like I’ve worked with in other languages, so the transition was smooth. The lambda syntax was particularly reminiscent of pythonic list comprehensions.

Thanks to delegates, I can turn this:

var matchingTypes = new List<Type>();
foreach(t in CurrentTypes) {
	if(t.IsSubclassOf(parentType) {
		matchingTypes.Add(t);
	}
}
return matchingTypes;

Into this:

return CurrentTypes.FindAll(
	delegate(Type t)
	{
		return t.IsSubclassOf(parentType);
	}
);

And finally, via lambda, to this!

return CurrentTypes.FindAll(
	t => t.IsSubclassOf(parentType)
);

Not too shabby, eh?

Reflection
Most of my programming has been in ColdFusion, JavaScript and Ruby. There’s been a little bit of this and a little bit of that peppered in there, particually C and Java while I was at UCF, but for the most part I’ve enjoyed working with dynamic and/or interpreted languages. Meta-programming is common in these types of languages, but I was surprised and impressed to read up on reflection. In this case, reflection allows me to dynamically detect and run my problems, which makes it easier (and cleaner) for me to add new solutions.

Here’s a simplified “ClassMaster” class I use to wrap my reflection calls for listing and creating classes, so you can see what I’m on about:

class ClassMaster
{
	private Assembly CurrentAssembly { get; set; }
	private List<Type> CurrentTypes { get; set; }

	public ClassMaster()
	{
		CurrentAssembly = Assembly.GetExecutingAssembly();
		CurrentTypes = new List<Type>(CurrentAssembly.GetTypes());
	}

	// should probably take arguments to pass thru...somehow
	public Object CreateClass(Type classType)
	{
		return CurrentAssembly.CreateInstance(classType.FullName);
	}

	public List<Type> getTypesByParentClass(Type parentType)
	{
		return CurrentTypes.FindAll(
			t => t.IsSubclassOf(parentType)
		);
	}
}

That’s it for now. I’ll be looking into LINQ and unit testing in the next couple weeks, and then I’m on to the gui. ASP, SilverLight, and WPF here I come!

Here are those links again:
Release
Latest Version

2010 New Years Resolutions

I didn’t make much headway with my formal resolutions last year.

  • I went to a few user group meetings at the beginning, but I trailed off rather quickly.
  • I didn’t contribute ANYTHING to open-source.
  • I didn’t complete any money making projects.
  • And aside from playing around with a few GreaseMonkey scripts I didn’t write any plugins.

However, I did manage to do a few other things in 2009:

And I saved the best for last…

Sara!

Sara!

2009 was the year that I met and engaged the love of my life, Sara!

In short, 2009: Best year ever!

Now, on to this year’s resolutions!

Blog More!

Blog More!


Blog More!
I’ve always done a lot of programming outside of work, but I’ve found that blogging incentivizes me to actually (somewhat and sometimes) finish what I start. I’m much more likely to finish something when I plan on, or start to blog about it and I feel that the extra little nudge can make a big difference.

Unfortunately, I have half a dozen unfinished Flex projects to NOT show for my lack of blogging this year, but I hope to get back on track in 2010.

C#!

C#!

C#!
In addition to my 9-5 ColdFusion and JavaScript programming, the last couple years I’ve spent most of my free time in Ruby and ActionScript. This year I wanted to get more into general, gui type programming. It’s been a long time since I wrote a windows application, and my time spent with the Flex compiler has got me feeling nostalgic for a more structured language and programming environment.

I’ve spent a little bit of time over the holidays on a few C# projects, and I’m loving it and I’m looking forward to really diving into C# this year!

Attend User Group Meetings!

Attend User Group Meetings!

Attend User Group Meetings!
I say this every year, but there are a few active user groups in Orlando that I really like, that I should be attending more frequently and consistently.

Here’s a list, for link-love’s sake:

  1. ADOGO
  2. OJUG
  3. ONETUG
  4. ORUG

I figure I should be able to, no excuse, make at least one a month. AT LEAST!

Work Out!

Work Out!


Work Out!
This is another resolution that I make every year. I didn’t lose any weight in 2009, in fact I gained 5lbs. However I’m lifting a lot more weight now, and I feel healthier so I guess I’m doing something right. I plan on continuing this through 2010.

So that’s it for tonight folks, I’m off to bed.

Happy New Year!

ColdFusion FileSweeper

I’m tired writing scripts to clean up temporary files.

It’s a nigh trivial task. The chance for error is small, but the consequences can be dire!

DIRE!

DIRE!

I wrote a little utility that makes this a little easier. It simply deletes all the files in a folder (recursive or no) that are older than a specified number of seconds.

Example Usage:

// no init needed, but the function's there if you like
fileSweeper = CreateObject("component", "fileSweeper");   

// all arguments are actually defaulted to the values shown
// so you needn't pass any, fancy eh?
fileSweeper.deleteOldFiles(
    folder   = ExpandPath("/temp"),
    seconds  = 600,
    filter   = "*.*",
    recurse = "no",
    lockname = "deleteFiles",
    timeout  = 60,
    logging  = true
);

Download it!

ColdFusion serializeJSON Problem

I ran into a little problem with the CF8 serializeJSON function. The function doesn’t properly escape quotes in struct keys, which results in invalid JSON being generated.

For Example: (all code is in cfscript)

// Struct Key with quotes in it
heightCounts["6'0"""] = 5;

// Serialize function runs alright...
serialized = serializeJSON(heightCounts);

// But the JSON is invalid. The quotes are unescaped! 
writeOutput(serialized);
// => {"6'0"":5.0}

// As you might expect, deserializing throws an error
deserializeJSON(serialized);

I certainly don’t like the idea of having quotes in struct keys, but that’s beside the point. I filed a bug report, but I also wrote a little function to jsStringFormat my struct keys. Problem solved!

function cleanKeys(dirtyData) {
	var cleanData = structNew();
	var cleanKey = "";
	var i = "";

	if(!isStruct(dirtyData)) {
		return dirtyData;
	}

	for(i in dirtyData) {
		cleanKey = jsStringFormat(i);
		cleanData[cleanKey] = cleanKeys(dirtyData[i]);
	}

	return cleanData;
}

You just pass in your quote-fully keyed struct, and get a clean one back:

// Same example as above
heightCounts["6'0"""] = 5;

// This time we sanitize the struct keys
jsSafeHeightCounts = cleanKeys(heightCounts);

// The serializeJSON call still runs without error
serialized = serializeJSON(jsSafeHeightCounts);

// But this time the output is correct!
writeOutput(serialized);
// => {"6'0"":5.0}

// And the deserialize works as expected
deserializeJSON(serialized);

Ta Da!

Simple ColdFusion Feed Caching Manager

ColdFusion 8 added the cffeed tag, a great and simple utility for fetching and parsing rss and atom feeds. It’s a great and simple to use utility, but there are a couple of issues to keep in mind.

Every time you make a “read” call to an external source, you’re preforming an http request. Most feeds that I’ve pulled in aren’t updated more than a few times per week. Just using cffeed, even a modest hit count can quickly add up to thousands of unnecessary requests. Aside from the bandwidth, you’re fully at the mercy of that external server. Each request is potentially slow, invalid, or (ahem, Twitter) otherwise unavailable.

You can totally bypass these problems by simply caching a copy of the feed to diske, and then quickly and safely parsing that file as needed. If you can grab it once, then you’ll always have that information quickly available. I wrote a lightweight utility for doing just this. It’s simple, but it’s made my life so much easier that I thought I’d share.

First create and instantiate the feed manager.

  feedManager = createObject( "component", "feedManager" );
  feedManager.init( folder = absolutePathToSaveFeedFiles );

Then add the feeds, with unique keys for retrieval.

  feedManager.addFeedURL(
    key = "BLOG",
    url = "http://joezack.com/index.php/feed"
  );

  feedManager.addFeedURL(
    key = "CNN",
    url = "http://cnn.com/feed"
  );

Fetch and save the feeds to disk, if available and valid. I run this in a scheduled task, every hour or so.

  feedManager.cacheFeeds();

  // or to just cache one feed
  feedManager.cacheFeed("CNN");

Finally, to retrieve the cffeed parsed file, just call the getFeed method! So long as there has ever been a feed successfully retrieved, you’ll have data.

  // Request feed from disk.
  feed = feedManager.getFeed(key = "BLOG");

Download the file!