A
A
Alexander Fandeev2021-03-21 14:43:39
Algorithms
Alexander Fandeev, 2021-03-21 14:43:39

How to display a certain value in the center of an array with its different dimensions?

Hello. I ran into a small problem while solving the problem.
605730f757231044185809.jpeg
It is necessary, exactly as in the image, to create a rectangle from the characters '#' and fill the center of this rectangle with empty characters. The problem grows when the dimension of the array grows. The problem requires that its dimension could be from 3 to 100.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wataru, 2021-03-21
@alexandrfandeev

Edit:
Since the task is to build concentric nested squares, then there are 2 approaches.
Easy to understand, but less efficient (but still great fast for the ridiculous constraints of the problem) - write a function that, in a two-dimensional array, draws a square of the given size around the center. This is stupidly 4 consecutive, not nested loops. Everyone draws one side of the square. Stupidly cycle up to n, where n is the length of the side of the square. There, one coordinate is fixed, and the other runs along the side. You need to think a little and make formulas for which rows and columns will be painted over.
Get a two-dimensional array, fill it with spaces, and then loop from n%2 to n with a step of 2 draw squares.
The second, more effective, approach is to think a little. Take a checkered sheet, or in some editor draw the answer for n=9.10. Think about patterns. The first line will always be n #. The second one will be #, n-2 " ", #. Next "# #...# #" and so on.
Some lines will have a segment of "#" of some length in the middle, and a given number of alternating "#" and " " at the edges. Neighboring lines will contain a segment of spaces in the middle, and alternating bars and spaces around. From the line number, one can very simply calculate the lengths of the middle segment and alternating pieces. Accordingly, you can display the answer immediately without forming it in an array. Print alternating "#" as many times as you need. Then print "#" or " " as many times as needed. Then print "#" as many times as needed. This is one outer loop, several stupid formulas, three nested sequential loops with output.
Formula hint - matters how close the string is to the middle of the array and if n is even.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question