Project Euler Problem #32

June 16, 2010

Read the details of the problem here

Summary

Find the sum of all numbers that can be written as pandigital products.

Solution

Playing catch up writing this one up too. Straightforward to create a brute-force solution to this. Just a matter of searching across the problem space and checking for the criteria to be met. Used a Set to make sure that duplicates were being handled appropriately.

String.metaClass.isPandigital { ->
  delegate.toList().sort().join() == "123456789"
}

def nums = [] as Set

for (a in 2..98) {

  def (minb, maxb) =
      (a < 10) ? [ 1234, 9876 ] : [ 123, 987 ]

  for (b in minb..maxb) {
    def p = a * b
    def s = "$a$b$p".toString()
    if (s.length() > 9) break
    if ((s.length() == 9) && s.isPandigital()) nums << p
  }
}

def answer = nums.sum()

This runs in 0.35 seconds, so good enough to call it a success.

Conclusion

Groovy allowed the use of metaClass extensions to make the solution read neatly but it wasn’t a particularly Groovy solution apart from the isPandigital() method. Performance was adequate for the scale of the problem.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: