Author Archives: joe

About joe

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

Project Euler : Problem 31 in Ruby

I kept trying to make this problem harder than it actually was, but ultimately a simple greedy solution worked just fine.

I would have saved myself a lot of time by actually solving the problem before attempting to optimize. C’est la vie!

Problem #29

Investigating combinations of English currency denominations.

def count_coins coins, target, last_coin = 0

	return 1 if target == 0
	total = 0

	coins.each do |c|
		next if c < last_coin
		total += count_coins(coins, target - c, c) if (target >= c)
	end

	total
end

puts count_coins(
	[1,2,5,10,20,50,100,200],
	200
)

Searching for Read-Only Files with Ruby

Wrote a quick ruby script that someone might find useful. It will recursively find and list readonly files from a passed in directory. There’s also a an array of file extensions you can exclude.

Nothing Fancy:

require 'find'

# update to exclude by file extension
exclude_extensions = ['.jpg','.txt','.png','.gif','.git']

if(ARGV[0] == nil) then
	puts "Please pass in a directory."
	exit
end

puts "Searching for NON read only files"

puts "Excluding: " + exclude_extensions.join("s")

writable = []
Find.find(ARGV[0]) do |path|

	if File.file?(path) and File.writable?(path) then
		if exclude_extensions.include?(File.extname(path))
			writable.push path
		end
	end
end


if writable.size then

	puts "Writable Files:"

	puts "t" + writable.join("nt")

else

	puts "No writable files."

end

Flood It .NET

I’ve been playing a bit with Silverlight this weekend, and I made a little app based on little game called Flood-It! Unfortunately, at the time I started I couldn’t remember the name of the app, so it’s a bit of an interpretation…

Anyhow, the goal of the game is to ‘flood’ the screen with all one color. It’s a bit difficult to explain, so just click around a bit and it will start making sense.

So far I’ve really liked working in Silverlight, it’s very similar to Flex except that C# blows ActionScript out of the water. I’ve got a few more little projects I’d like to try before I give my final verdict, so don’t touch that dial!

Project Euler : Problem 29 in Ruby

I spent some time playing around with a way to reduce calculations by constructing something akin to a sieve, (2^16 is the same as 4^8 and 16^4), but it turns out that the brute force solutions runs in under a second on my machine so it seemed silly to spend any more time with it.

Ruby even minds the big numbers for me, so the solution is quite trivial:

Problem #29

How many distinct terms are in the sequence generated by a^(b) for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100?

MIN, MAX = 2,100
values = []

(MIN..MAX).each do |base|
  (MIN..MAX).each do |power|
    values << base**power
  end
end

puts values.uniq.length

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_