Category Archives: code

Project Euler: Problem 33 in Ruby

It’s fugly, but it works. The hardest part was understanding the question. If the longer description didn’t say that there were exactly 4 fractions, I might have gone crazy.

For reals.

Problem 33

Discover all the fractions with an unorthodox cancelling method.

top, bottom = 1, 1

(10..98).each do |i|
	((i/10)..9).each do |jt|
		jt *= 10
		(1..9).each do |jo|
			j = jt + jo
			next if i >= j
			if i % 10 == j / 10 && i.to_f / j == (i / 10).to_f / (j % 10)
				top *= i
				bottom *= j

puts bottom / bottom.gcd(top)

Find the Longest Palindrome in a String

I recently discovered, and one of the more recent posts dealt with one of the greplin programming challenges. I figured since people were posting their code there, then it wouldn’t be too bad for me to post mine here!

Find the Longest Palindrome in a string:

I doubt this is an optimal solution, but I like how it works:

text = "FourscoreandsevenyearsagoourfaathersbroughtforthonthiscontainentanewnationconceivedinzLibertyanddedicatedtothepropositionthatallmenarecreatedequalNowweareengagedinagreahtcivilwartestingwhetherthatnaptionoranynartionsoconceivedandsodedicatedcanlongendureWeareqmetonagreatbattlefiemldoftzhatwarWehavecometodedicpateaportionofthatfieldasafinalrestingplaceforthosewhoheregavetheirlivesthatthatnationmightliveItisaltogetherfangandproperthatweshoulddothisButinalargersensewecannotdedicatewecannotconsecratewecannothallowthisgroundThebravelmenlivinganddeadwhostruggledherehaveconsecrateditfaraboveourpoorponwertoaddordetractTgheworldadswfilllittlenotlenorlongrememberwhatwesayherebutitcanneverforgetwhattheydidhereItisforusthelivingrathertobededicatedheretotheulnfinishedworkwhichtheywhofoughtherehavethusfarsonoblyadvancedItisratherforustobeherededicatedtothegreattdafskremainingbeforeusthatfromthesehonoreddeadwetakeincreaseddevotiontothatcauseforwhichtheygavethelastpfullmeasureofdevotionthatweherehighlyresolvethatthesedeadshallnothavediedinvainthatthisnationunsderGodshallhaveanewbirthoffreedomandthatgovernmentofthepeoplebythepeopleforthepeopleshallnotperishfromtheearth"

def find_longest_palindrome s1, size
	longest = ""

	s1.size.times do |start|
		break if start + size > s1.size
		s2 = s1[start, size].reverse
		if s1.include? s2
			return s2

	find_longest_palindrome s1, size - 1

puts find_longest_palindrome(text, text.length)

I found the site via this post, 10 puzzle websites to sharpen your programming skills. Now that the wedding’s over (pics soon!) I can’t wait to get back to a regular extracurricular programming schedule!

Unit Testing in PowerShell with PSUnit

I did a bit of playing around with wcf, PowerShell and PSUnit the other day.

PSUnit is a unit-testing framework based on NUnit (or should I say JUnit). It was a bit of work to set up but I was really impressed by the speed, robustness, and ISE integration.

It doesn’t make much sense to test application logic through a web service, or even with PowerShell at all, but it’s nice to know there’s such a great tool available. I’ve been having some issues with MSTest and 64 bit assemblies and although I’ll probably end up going with NUnit, it was a fun and educational journey!

Thanks PSUnit Guys!

Project Euler : Problem 32 in Ruby

My solution to this is ugly, but like the tar baby the more I mess with it the worse it gets.

I originally tried to find all the 9 digit pandigitals to cycle through, but was able to cut down the processing by a TON after I figured out that there were only 2 possible digit combinations that could satisfy the problem. (x + xxxx = xxxx and xx + xxx = xxxx)


Problem #32

Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital.

def combo size, current = 0, stack = [], results = {}

  return results[stack.join.to_i] = stack.clone if size == 0

  (1..9).each do |n|
    next if stack.include?(n)
    stack[current] = n
    combo(size - 1, current + 1, stack.clone, results)

  return results

def pandigitals a, b, c
  results = []

  $repo[a].each_pair do |a_num, a_arr|
    $repo[b].each_pair do |b_num, b_arr|
      product = a_num * b_num
      if $repo[c].include?(product)
      	c_arr = $repo[c][product]
        results.push(product) if (a_arr + b_arr + c_arr).uniq.length == 9

  return results

$repo = {
  1 => combo(1),
  2 => combo(2),
  3 => combo(3),
  4 => combo(4)

results = pandigitals(1, 4, 4) + pandigitals(2, 3, 4)

puts results.uniq.inject(:+)

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)


puts count_coins(

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."

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

if writable.size then

	puts "Writable Files:"

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


	puts "No writable files."


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

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.


require 'prime_generator'

# pre-calculate primes
MAX     = 1_000
primer  = 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)

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


puts product

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


class Prime_Generator

  attr_reader :stack

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

  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          
  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


You can find more Project Euler solutions here: