I write in C on arduino uno. The idea is to display pyramid from topographic view so variables that I have is the 'seedP' - middle value, the size of pyramid 'sizeP' - the amount of layers and how many letters are in a row - 'layer'.
The pyramid with those values in the code seedP = 6, sizeP = 3 would look like:
44444
45554
45654
45554
44444
Here is the code:
void setup()
{
Serial.begin(9600);
int seedP = 6; //Centre value
int sizeP = 3; //Amount of layers
int layer = (sizeP*2)-1;
for(int i=0; i<layer; i++){
for(int j=0; j<layer; j++){
Serial.print(seedP);
}
Serial.println();
}
}
I still cannot fully grasp the concept of the algorithm I could potentially check for first and last layer then display a value full of '4' in this example but I'm not sure how to deal with other layers. The code right now displays only '6'es in 5 columns and 5 in a row.
Edit: Updated code and below is the grid
void setup()
{
Serial.begin(9600);
int sizeP = 3; //Amount of layers
int layer = (sizeP*2)-1;
int seedP = 6; //Centre value
int seedX = sizeP-1;
int seedY = sizeP-1;
for(int i=0; i<layer; i++){
for(int j=0; j<layer; j++){
//i,j = x,y grid
int distanceX, distanceY, distance; //Distance between a cell and center value
distanceX = abs(seedX - j);
distanceY = abs(seedY - i);
distance = distanceX + distanceY;
}
Serial.println();
}
}
Values from each cell to the center
(0,0)=4, (0,1)=3, (0,2)=2, (0,3)=3, (0,4)=4
(1,0)=3, (1,1)=2, (1,2)=1, (1,3)=2, (1,4)=3
(2,0)=2, (2,1)=1, (2,2)=0, (2,3)=1, (2,4)=2
(3,0)=3, (3,1)=2, (3,2)=1, (3,3)=2, (3,4)=3
(4,0)=4, (4,1)=3, (4,2)=2, (4,3)=3, (4,4)=4
Nice puzzle, here is my suggestion:
#include <stdio.h>
#include <stdlib.h>
/* get the depth relative to the pyramids center, which is at origo */
int depth(int x, int y)
{
x = abs(x);
y = abs(y);
return x > y ? x : y;
}
/* walk from (-(size - 1), size - 1) along the x and y axis, and print
* the center value minus the current depth */
void pyramid(char center, int size)
{
int x, y;
size--;
for (x = -size; x <= size; x++) {
for (y = -size; y <= size; y++)
putchar(center - depth(x, y));
putchar('\n');
}
}
int main(int argc, char **argv)
{
char seedP = argv[1][0];
int sizeP = strtol(argv[2], NULL, 0);
pyramid(seedP, sizeP);
}
Note that there is no error handling of any kind here, you'd better run it with two arguments.
Example:
$ gcc pyramid.c -o pyramid && ./pyramid 6 7
0000000000000
0111111111110
0122222222210
0123333333210
0123444443210
0123455543210
0123456543210
0123455543210
0123444443210
0123333333210
0122222222210
0111111111110
0000000000000
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With