I finally got a chance to work on Ray's puzzler for April 27, 2007. It builds the result set by viewing the array as a table that has rows (set values) and columns (characters within a value). When you look at this way, you can build the array using a simple nested loop. The complicated part is using this RxC (row by column) index to figure out which character we are supposed to be using.
After analyzing the possible outcomes you will see that there are N^X possible values where N is the number of characters in the passed in set and X is the length of the each resultant item. This becomes our number of rows. Then, of course, the number of character columns is equal to the length of the set items (also passed id).
The alternating is a bit trickier to see. The last column has a new value for every row. The second to last column has a new value for every N rows (where N is the number of available characters). The third to last column has a new value for every N * N rows since it can only alternate after the second to last row has alternated.
You might begin to see the pattern is that a given column value alternates based on the length of the sets (X), the current column (C) and the number of characters (N) using this rule:
N^(X - C)
Once we know that, we can figure out which letter we are looking at based on the number of times our sequence has repeated and the current row. That equation is a bit complicated, so see the code below:
Launch code in new window » Download code as text file »
This uses two loops and no recursion, but is certainly a bit verbose. And now, to test; running this:
Launch code in new window » Download code as text file »
... we get the following CFDump output:
| | | | ||
| | ![]() | | ||
| | | |
I have color coded the alternating rows to help see where things are changing.
Download Code Snippet ZIP File
Comments (2) | Post Comment | Ask Ben | Permalink | Print Page
Lenny And Bo, ColdFusion Programmers (Vol. 10)
Performing Disaster Recovery After A ColdFusion Page Timeout Exception
Nice solution. I was working on something very similar by using the exponent to determine total possibilities and two loops, but I got a little stuck towards the end... I'm glad you solved it this way so that I can see where I went wrong.
Dan
Posted by Dan Sorensen on Apr 27, 2007 at 2:16 PM
@Dan,
Thanks. Yeah, that MOD equation was driving me CRAZY for a while. I kept getting the sequence "1,2,0,1,2,0" and I wanted "1,2,3,1,2,3"!!!!
Posted by Ben Nadel on Apr 27, 2007 at 2:26 PM