Project Euler problem 8

The latest in a series of paired-up problem workings with Greg Bowie. This week we’re looking at Problem 8:

Discover the largest product of five consecutive digits in a the [provided] 1000-digit number

Here’s my response, longhand:

  1. I’ll need a variable to store the (current) value of the greatest product
  2. I’ll need to iterate through the 1000-digit number, reading 5 digits at a time working out the product of each sequence, stepping one digit on with every iteration.
  3. The routine will begin from the 1st digit. The process will stop 5 digits of the final digit
  4. Using variables to store the length of the 1000-digit number and the number of digits we’re deriving the product of would make the solution more adaptable for other numbers and sequences
  5. Each product retrieved from every sequence of 5 digits must be compared to the current greatest product. If this exceeds the current greatest product, we set this as the new greatest product

This should solve the problem, but why stop now?

Refinements

The presence of zeros in the 1000-digit number is notable – any zero encountered while examining the product of multiple digits will result in a zero product. So I’ll ignore them:

  1. Create an array of smaller numbers by splitting the 1000-digit number by any zero digit – handling sequences of zeros so as to prevent empty array items
  2. Iterate through each of these numbers, deriving the product of each set of 5 digits, and checking this against the current greatest product

Chances are this refinement will not improve the performance of this test on a single number, but as it reduces the number of product-derivation runs by 398 by it may scale well, depending on the language.

ratherLongNumber = 73167176531330624919225...
numDigits = ratherLongNumber.to_s.length
considerRange = 5
totalcomparisons = 0
$greatestProduct = 0
while totalcomparisons range = ratherLongNumber.to_s[totalcomparisons,5]
rangeproduct = range.split(//).map(&:to_i).inject(:*)
$greatestProduct = $greatestProduct>rangeproduct ? $greatestProduct:rangeproduct
totalcomparisons=totalcomparisons+1
end
puts "#{$greatestProduct}"

Refined version:

ratherLongNumber = 73167176531330624919225...
def getProductOfRange(inputNumber,considerRange)
# puts inputNumber
numberofcomparisons = 0
localGreatestRange = 0
while numberofcomparisons range = inputNumber.to_s[numberofcomparisons,5]
rangeproduct = range.split(//).map(&:to_i).inject(:*)
numberofcomparisons=numberofcomparisons+1
localGreatestRange = localGreatestRange>rangeproduct ? localGreatestRange:rangeproduct
end
return localGreatestRange ,numberofcomparisons
end
$greatestProduct = 0
arrayOfNumbers = ratherLongNumber.to_s.split(/0+/).map(&:to_i)
arrayOfNumbers.each{
|a|
tmp2,comparisons = getProductOfRange(a,5)
$greatestProduct = $greatestProduct>tmp2 ? $greatestProduct:tmp2
}
puts "#{$greatestProduct}"

here’s Greg’s response, posted simultaneously today.

update 23/01/2012:

Revisiting this afresh I realise there’re other ways to skip those pesky zeros, rather than drop them into an array, better to simply skip past any such sequence:

ratherLongNumber = 73167176531330624919225...
numDigits = ratherLongNumber.to_s.length
considerRange = 5
greatestProduct = 0
cursor = 0
skipped = 0
while cursor <= numDigits-considerRange
range = ratherLongNumber.to_s[cursor,considerRange]
if range.index('0')
cursor=(cursor+range.index('0'))+1
skipped=skipped+1
else
rangeproduct = range.split(//).map(&:to_i).inject(:*)
greatestProduct = greatestProduct>rangeproduct ? greatestProduct:rangeproduct
cursor=cursor+1
end
end
puts "Greatest Product: #{greatestProduct}"
puts "#{skipped} sequences with zero in the #{considerRange}-digit range skipped"

A second week of self

Week two: surreal, desperate, but going in the right direction.

At the start of the week I found I could get a likeness without looking, just idly doodling in sketchbook. This is bad news, it’s the process of observation that’s important, not the ability to recall. So I’ve tried to take more time over the plain, representational ones this week.

I’ve thrown in some other approaches too – depicting my face upon a small matryoshka doll stood upon a notebook (‘that’s rather sinister’ was one response), and another looking out over the river but will odd, converging shadows.

I am still not producing the kind of work I would like to, but the journey’s begun and most importantly I’m thinking far more, and further ahead.

Available time remains a big factor. Thankfully at the weekend I had some time to run through various ideas and use some other media.

One Self-Portrait a day

At 6am on January the first, I sketched a self-portrait:

…it's too early for this!

…and thought that might be a fun, creative, enlightening, educative and perhaps exasperating thing to do every day.

Every day of 2012 I’ll execute a self-portrait, and share it using Twitter the same day. Sharing them provides an impetus to complete each day’s portrait, and gives me the determination to work on my methods and my approach.

An audience (even a theoretical one) gives me a reason to improve. The risk is that you end up sharing 365 crap images of yourself with the world, the pay-off is that every day you add to your experience, your conceptual and technical capabilities, and your satisfaction with your work.

Week one’s self-portraits

The output so far has been representational, brief and sketchy, possibly no surprise at the outset. Representationally, they’re not up to much. I am capable of better, but this is a journey.

Time

The greatest constraint so far has been time. Time to conceive an approach to a portrait as well as time to execute it. Thus the first week’s output has been low concept, and quickly executed. I’ve tried to vary media a little during the week but each has been a very direct method.

Not having the time to work on drawing and painting is the best reason I can think of to continue this project, regardless of the work produced.

Concept

Telling yourself you have to do this, every day, is at once a burden and a joy. Until you place constraints on what you do, you don’t realise the clarity of thought you can attain within those limits.

I have many plans for where this project will take me, my thought processes and my experience with various media. My immediate aims are to work in paint and some form of printing as soon as I can, but working with traditional media will just be one part of the project.

Every week or so, I’ll add a post here on recent works and where I think they’re heading, and more importantly where they’re taking me.

 

Inaugural Preston CodeJo, November 28th 2011

Facilitated by @ruby_gem and hosted by @phpcodemonkey, the first Preston CodeJo was held last night at Magma Digital’s offices on Winckley Square. Using themed ‘katas’, this is the first of an open-ended series of events designed to challenge and extend developer abilities and interaction across programming/development disciplines.

This month’s kata asked attendees to use a Test-Driven Development (TDD) approach to solving a simple problem using the Ruby language.

Continue reading

Final thoughts on PHP North West 2011

PHP NW 2011 informationSunday’s track choices

My second day at the PHP North West Conference 2011 kicked off with Paul Lemon’s ‘Feeling Secure?’ talk.

Paul used succinct code samples and made a point of covering the basic attack methods, assuming no great depth of knowledge for some and the need to re-iterate its importance to the rest of us. For each attack type, variant methods were demonstrated that perhaps would have been unfamiliar to some – this was certainly borne out during the Q&A session. Paul had far more topics to cover and hopefully there’ll be an extended security presentation at a future conference.

Following this I attended Walter Ebert‘s talk on URL design. Walter had gone to some trouble to locate examples of good practice in human-readable, RESTful web addressing as well as some neat workarounds for common problems – for example url handling routines for those long descriptive links that email clients break when they wrap text.

Finally I listened to Richard Backhouse talk about compiling PHP to .NET using open source tool Phalanger. Richard covered the background to his company’s adoption of the approach, client considerations, use cases and opportunities for mixing languages & libraries for a best-of-both approach.

Take Away

I tend to take away both strong themes and important (though sometimes small) messages from conferences that stick with me, influencing the design decisions and production routes on current and future projects. They’re not always from a favourite or most enjoyable presentation, but they highlight the event’s greater whole.

Laura Beth Denker‘s Saturday track 1 talk emphasised the need to retain practicality and perspective in software production (in particular, testing). Yes we have the tools, but are we using them effectively, are we curtailing our own faculties in favour automated methods, do we put enough trust in our collaborators?

The major frameworks has a strong showing, but Alistair Stead and Paul Lemon provided timely reminders of those areas that still require careful thought and action – response times, the right caching techniques regardless of chosen technology, the importance of validation and knoweldge of protocols and security basics.

Finally, Ian Barber‘s keynote brings all this together – the tools exist to allow you to contribute to great developments and create new ones. Use the right tools for right purpose and keep a keen eye on what’s around you – in programming, and in the wider world.

PHPNW11 was all about (as @Elblinkin put it) ‘Keyboard, mouse and You’.

Saturday at PHP North West 2011

The PHP North West conference gets bigger and better every year, and 2011 sees the Saturday and Sunday conference enlived by a Friday tutorial day and an unconference running alongside the scheduled tracks.

Saturday morning kicked off with keynote speaker Ian Barber‘s revealing tour of the small steps that made great software even better, and the ways that diverse personal interests, hobbies and a willingness to ignore conventional wisdom led to innovations that we in turn can build upon and contribute to.
Having a broad range of work and hobby interests, I could only agree with Ian on his belief in cross-fertilisation of ideas and approaches, and it was good to be reminded that being interested and aware is often more effective than aiming high.

Starting off Track 1, Enrico Zimuel introduced the new features and architecture of Zend Framework 2 followed by Sebastian Bergmann‘s talk on PHP Testing tools. Sebastian compared the various approaches and features of the most ubiquitous and newly released tools including his own project PHPUnit , the Atoum framework and the behaviour / scenario driven BeHat.

In the afternoon I attended Alistair Stead‘s track 2 talk about the Varnish reverse proxy cache. In addition to presenting Varnish’s impressive capabilities, Alistair examined the pitfalls of adding multiple cache layers, configuration gotchas, as well as privacy and security concerns in good depth.

Track 2 continued with Stefan Koopmanschap‘s introduction to the recently released Symfony2 framework. For those of us with experience of prior releases, Symfony2 appears to differ significantly and will take some getting used to. The Bundles approach follows the components theme running through the conference this year.

The final talk in track 1 was Laura Beth Denker‘s ‘Are your tests really helping?’. After informing the crowd that her company pushed code every 20 minutes or so, you would have expected a breakdown of intensive automated test routines, but what was presented was a practical approach involving well organised unit testing; having faith in fellow developers and trust in the external services (and if you don’t have faith or trust, you should probably replace both) in order to reduce the need for extensive integration and functional testing.

PHPNW11 continues today, Sunday 9th October. Feedback for talks can be read and provided on JoindIn.

Rustbucket and I

Rustbucket (My 1980′s Raleigh Equipe and it’s patina) and I will be riding in the Manchester to Blackpool charity cycle event this coming Sunday, 10th July.

If you’d like to sponsor me for the sixty-miler then click the JustGiving link, all funds raised go the Christie Charitable Fund.

Despite the name, Rustbucket‘s already proved capable of holding up under pressure and distance.

Let’s hope the months of training mean my riding buddies and I can do the same.

Denting from the Desktop – a shortcut for posting Identi.ca updates

One positive thing that has come out of Ideas of March is the number of new posts I’m reading on the blogs I already follow and the new blogs I’m taking the time to read.

Rick Hurst, a fellow BathCamper from a couple of years ago posted his thoughts about Twitter, Identi.ca and a future for distributed social microblogging. Like Rick I hastily bagged my identi.ca name when I heard about the service, but haven’t posted to it in anger. Continue reading