0
$\begingroup$

I'm writing a crossword solving program, and want an equation that will tell me how many possible strings I need to check from a box of h height and w width.

For example, if given the box:

abc
def

Im looking for the strings (a, b, c, ab, bc, cb, ba, abc, bca, d, e, f, de, ef, fe, ed, ad, da, be, eb, cf, fc). I can't figure out a general equation that will tell me how many strings there are for any W x H box.

Any help is appreciated, thanks.

  • 0
    For clarification, are you looking for diagonals as well? Do you need to count ae, ea, bf, fb, db, bd, ce, ec,...? You are missing in your example def, fed. You also include in your example bca, surely you meant to write cba here instead?2017-02-13

1 Answers 1

0

I would recommend breaking this up into cases: Horizontal strings and Vertical strings. To avoid overcounting, go ahead and include an additional case of length1 strings and specify in each of the earlier cases that they must all be length at least two.

To count horizontal strings, pick which row you are taking the string from and pick the start and end positions simultaneously of the string from among the spaces between the letters or to the left of the leftmost or right of the rightmost. Then, pick whether the string is being read from right to left or from left to right.

There are then a total of $2\times H\times \binom{W+1}{2}$ horizontal strings of any length, subtract the $2\times H\times W$ length $1$ strings to avoid overcounting these as we will count them later. ($2\times H\times W$ since we would have counted each singleton once for the left-to-right and again for the right-to-left count)

Similarly, there will be $2\times W\times \binom{H+1}{2}-2\times H\times W$ vertical strings of length at least two.

If you were to want to include diagonal strings, these would be a bit more challenging to count. Break this apart by the length of the diagonal on which the string lies and the direction. Note that some diagonals will have a smaller allowable maximum length of a string on it

Combine these with the strings of length $1$ we have a final total of

$$2H\binom{W+1}{2}+2W\binom{H+1}{2}-3HW$$

You can continue and expand the above terms if you like and simplify further, giving a final solution of $H^2W+HW^2-HW$