Fill My Grid

I’m fascinated by grids. Consider the chessboard, which is a grid. Or think about the most basic game grid, a 3-by-3 array for a game of tic-tac-toe. Programming a grid is a common thing, so your best hope is that this month’s Exercise is yet another super cinchy silly grid program.

And it is! Kinda.

Your challenge is to create a 20-by-20 character grid. Fill the grid with period characters, '.'. Then, at 20 random locations, set asterisks '*' into the grid. An asterisk cannot occupy a space where an asterisk already sits. So when the code is done, you must see 20 randomly-placed asterisks in a 20-by-20 grid, similar to what’s illustrated in Figure 1.

Figure 1. Twenty randomly placed asterisks in a 20-by-20 character grid.

“Well,” you say, as you swell your chest and crack your knuckles, “This one is easy!”

If you think so, great! Go ahead and code your solution to the Exercise. Remember to label it Part A because after you get it to work, you must take on Part B.

For the Part B solution to this month’s Exercise, modify your solution for Part A and add some additional logic: The Part B challenge is to ensure that no two asterisks sit in the same row or column.

Yes, the asterisks are still randomly placed. But, in addition to ensuring that an asterisk doesn’t already exist at that random location, you must check the entire row and column at the intersection for any other asterisks. Only when the rows and columns are clear can you set the asterisk.

Figure 2 illustrates how such a solution might appear.

Figure 2. Twenty randomly placed asterisks in a 20-by-20 character grid with no two asterisks sharing a row or column.

Please enjoy working on this Exercise on your own before you check my solutions.

2 thoughts on “Fill My Grid

Leave a Reply