Suggested Answers for re-writing problem 3.22
The re-write problem can be attacked in several stages. Ill delineate each step I
used, but this is simply a methodology: the end result is the important part!
- Step 0:
- Get the original solution
- Step 1:
- Pull out the stuff that drew the checkerboard, which be used to make the
separate function. (Other Examples)
- Step 2:
- Turn literals into named constants in as many of the individual function calls as
possible. Notice how the individual calls start to look more and more similar as object
names are used instead of literals.
- Step 3:
- Collapse the multiple-row sections into a odd & even row
for
loops. You need to have separate odd & even loops to deal with the color of each
rows first block.
- Step 4:
- Re-write the inner calls for alternating colors. Notice how much more complex this is
than the previous step, but how much more similar each little block of code becomes...
- Step 5:
- Collapse all the inner calls into single
for
loops.
- Step 6:
- Collapse the even and odd row loops into a single
for
loop
by adding additional logic for the color alternation between rows when the row has an even
or odd number of columns.
- Step 7:
- Replace inner calculations for position and color with stand-alone functions