I'm trying to develop analytical skills

Hi,

I've encountered printing geometric figures (it's a basic kind of problem) using asterisks. These are not homeworks. I'm fascinated with patterns but don't know how to think about these problems in an analytical way. Please help if you can.

One is a diamond. Originally, I did't get how they established the constants (i.e. 5), the iteration numbers (0-2*N), or the testing values (especially 3*N-i). These numbers all seemed arbitrary. Someone pointed out that 5 is like the radius of the diamond. So I assume that means the 2*N gives the diameter and is needed in order to draw the top and bottom halves.

Something that confuses me is why are there 11 lines instead of 10 if the radius is 5?

Does the term 3*N-i just come from observation or is there a way to derive it mathematically?

The other figure is a triangle. I don't understand what about the problem tells us that we're supposed to notice that the bitwise inversion of the outer loop counter bitwise anded with the inner loop counter will give us a nice triangle pattern.

How do you know to invert the row counter and AND it against the column counter?

Any help will be greatly appreciated.

Thank You For Your Time,
lanef

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46

Diamond Figure


     *
    ***
   *****
  *******
 *********
***********
 *********
  *******
   *****
    ***
     *


Diamond Code

#include <iostream>

void main() {
   const int N=5;

   for (int i = 0; i <= 2 * N; i++) {
      for (int j = 0; j <= 2 * N; j++) {
         if (i <= N) {
            if (j < N - i || j > N + i) {
               std::cout << ' ';
            }
            else {
               std::cout << '*';
            }
         }
         else {
            if (j < i - N || j > 3 * N - i) {
               std::cout << ' ';
            }
            else {
               std::cout << '*';
            }
         }
      }
      std::cout << std::endl;
   }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
Triangle Figure

*
**
* *
****
*   *
**  **
* * * *
********
*       *
**      **
* *     * *
****    ****
*   *   *   *
**  **  **  **
* * * * * * * *
****************


Triangle Code


#include <iostream>

void main() {
   const int N = 16;
   for (int n = 0; n < N; n++) {
      for (int k = 0; k <= n; k++) {
         std::cout << ((~n & k) != 0 ? ' ' : '*'); 
      }
      std::cout << std::endl;
   }
}
It might help you to draw your designs out on a piece of grid paper. This could help you get a more exact idea of what goes where.
Topic archived. No new replies allowed.