Monday, February 22, 2010

Little program to Use Integer math to find the Date

I was skimming my feeds this morning and saw a puzzle by Paul Jungwirth in the Coding Horror comments.
You have the numbers 123456789, in that order. Between each number, you must insert either nothing, a plus sign, or a multiplication sign, so that the resulting expression equals 2001. Write a program that prints all solutions. (There are two.) This is a pretty tricky problem, actually, if you don't think to use recursion. I was satisfied with pseudocode, but the Perl Mongers version was to fit the whole thing into 80 characters!
So here's my solution (in php, because I've been using that recently):


Included is a form so that you can try it out on just about any number.

4 Comments:

At February 22, 2010 8:18 PM , Blogger djcline said...

Ah, good, I see you also use minus and divide. I tried it with only plus and multiply and I was about ready to call shenanigans. Adding in the extra operations I get the same results.

 
At February 23, 2010 1:47 PM , Blogger Mike Hagen said...

Are you sure there isn't a bug in your PHP program? The problem states that you should use "nothing, a plus sign, or a multiplication sign" and that there are 2 answers. None of the answers that are outputted satisfy the criteria. Or am I mistaken?

 
At February 23, 2010 6:42 PM , Blogger Les said...

I was not able to find an answer without using the minus sign. I just consider it a test by Paul J. to make sure we were paying attention.

 
At February 24, 2010 4:28 AM , Blogger Walter said...

For 2002 you only get 2 answers with the original operators:

1*2+34*56+7+89 2002
1*23+45*6*7+89 2002

 

Post a Comment

<< Home