Graficando números en consola (0-3) [ESP-ENG] | C++

avatar
(Edited)

Portada para este post.jpg

¡Saludos! Acá les traigo otro post de programación, esta vez recordando una asignación bastante interesante que hice cuando vi "Programación Orientada a Objetos". Se trata de graficar en la consola, en el primer encuentro fue con simples "couts", sin embargo luego nos enseñaron que combinando la función gotoxy, un bucle doble de "for" y un condiciones con la sentencia "if", se puede lograr que la consola se vuelva un lienzo.

Para comenzar les dejo una captura de las librerías que usé, no detallaré mucho sobre esto pues no vengo a hablar de gotoxy, sin embargo podemos resumirlo en que facilita el trabajar con el cursor en la consola, es decir, moverlo de posición para colocar el caracter que servirá de "pincel".

Antes de entrar al ruedo, les dejo una pequeña gráfica de como está el "plano cartesiano" de la consola, de modo que puedan ver mejor qué significa cada letra, j vendría siendo el eje x, i el eje y. Por ello un ciclo for recorre el primer eje y el otro el segundo y según sean las condiciones este recorrido puede o no incluir a los negativos, como el caso de la función para graficar el 1, en la que empleé ese recorrido de negativos para poder graficar el diagonal característico de este número que va desde la punta hasta menos de la mitad de su tamaño. Podría haberlo dejado solo como un "palito" pero lo vi demasiado simple y podría confundirse con una "i" o una "l" aunque basándose en el contexto, esto puede evitarse.

El ejemplo en el plano cartesiano muestra como se grafica el "0", partiendo de las condiciones del if dentro de ambos recorridos, si y=0, coloca el caracter, si x=n-1, siendo n el tamaño ingresado, entonces coloca también el caracter, de igual manera si y=n-1, x=0. Recordando que usamos los operadores "==,>=,<=,>,<,=!" para las condiciones. El caracter que elegí fue la "x" (no confundir con el eje), pero es común el "*". Como pudieron darse cuenta este plano no es igual al clásico mostrado en bachillerato, hay una inversión, los positivos del eje y están hacia abajo y debemos considerar que en programación empezamos a contar en 0, así que por eso el "n-1" en las condiciones y no "n", partiendo directamente del tamaño que ingresa el usuario. Si se cambia en el condicional podrías hacer unas jugadas para partir de 1 y no de 0, pero es muy probable que eso te traiga confusiones más adelante.

Greetings! Here I bring you another programming post, this time remembering a quite interesting assignment I did when I saw "Object Oriented Programming". It is about graphing in the console, in the first meeting it was with simple "couts", however then they taught us that combining the gotoxy function, a double "for" loop and a conditions with the "if" statement, you can make the console become a canvas.

I will not detail much about this because I am not here to talk about gotoxy, however we can summarize it in that it makes it easier to work with the cursor in the console, that is to say, to move it of position to place the character that will serve as "brush".

Before entering the arena, I leave a small graph of how is the "Cartesian plane" of the console, so that you can better see what each letter means, j would be the x-axis, i the y-axis. Therefore a for cycle goes through the first axis and the other through the second one, and depending on the conditions this path may or may not include the negatives, as in the case of the function to plot the 1, in which I used this path of negatives to plot the characteristic diagonal of this number that goes from the tip to less than half its size. I could have left it just as a "stick" but I saw it too simple and it could be confused with an "i" or an "l" although based on the context, this can be avoided.

The example in the Cartesian plane shows how to plot the "0", starting from the if conditions within both paths, if y=0, place the character, if x=n-1, being n the size entered, then place the character as well, likewise if y=n-1, x=0. Remembering that we use the operators "==,>=,<=,>,<,=!" for the conditions. The character I chose was the "x" (not to be confused with the axis), but "*" is common. As you could realize this plane is not the same as the classic one shown in high school, there is an inversion, the positives of the y-axis are downwards and we must consider that in programming we start counting at 0, so that's why the "n-1" in the conditions and not "n", starting directly from the size entered by the user. If it is changed in the conditional you could make some moves to start from 1 and not from 0, but it is very likely that this will bring you confusion later on.


image.png

image.png

image.png

Programación c++.png

Para el dos el asunto se complica un poco, aunque partiendo de lo antes mencionado "reciclamos" la línea superior (y=0, es decir i==0), la de abajo (y=n-1, es decir i==n-1), y añadimos una en el centro tomando en cuenta el dividir n/2. Con esas tres líneas podemos añadir un condicional que considere (x=n-1 y y<n/2, es decir j==n-1 && i<n/2), que sería la parte que considera cuando el eje x sea igual a "n-1" (lateral derecho), mientras el eje y sea menor que "n/2", de modo que solo se grafique hasta la mitad de la figura en el lateral derecho. Esto porque buscamos un "2" en pantalla. Finalmente tenemos un condicional que busca otra línea donde x=0 y el eje y es mayor a "n/2", añadiendo también un pequeño detalle en la punta del "2" para darle algo de formalidad.

Para el tres las condiciones son un poco menos densas, pues partimos de que se grafique cuando "j==n-1" (lateral derecho completo), luego una línea superior, inferior y en el medio (las tres antes mencionadas con el 2). A partir de acá empezamos a ver patrones repetibles a otros números o incluso letras (Spoiler a posibles post futuros).

Puedes notar que cuando llamo las funciones el primer parámetro es su posición en x, el tercero es el tamaño y el segundo es su posición en el eje y. Por ello se repite el "6" en el segundo y tercer parámetro pero en el primero crece para tomar en cuenta la separación necesaria para que no se sobreescriban uno a otros y pierdan su forma.

For two the matter gets a bit more complicated, although starting from the above mentioned we "recycle" the top line (y=0, i.e. i==0), the bottom one (y=n-1, i.e. i==n-1), and add one in the center taking into account the dividing n/2. With those three lines we can add a conditional that considers (x=n-1 and y<n/2, i.e. j==n-1 && i<n/2), which would be the part that considers when the x-axis is equal to "n-1" (right side), while the y-axis is less than "n/2", so that only half of the figure is plotted on the right side. This is because we are looking for a "2" on the screen. Finally we have a conditional that looks for another line where x=0 and the y-axis is greater than "n/2", also adding a small detail at the tip of the "2" to give it some formality.

For the three the conditions are a little less dense, because we start with the graph when "j==n-1" (full right side), then a top, bottom and middle line (the three previously mentioned with the 2). From here we start to see patterns repeatable to other numbers or even letters (Spoiler to possible future posts).

You may notice that when I call the functions the first parameter is their x-position, the third is their size and the second is their position on the y-axis. That is why the "6" is repeated in the second and third parameter but the first one grows to take into account the necessary separation so that they do not overwrite each other and lose their shape.


image.png

image.png

image.png

image.png

Programación c++.png

image.png

image.png

image.png

¡Y bueno... Eso ha sido todo! Seguro habrás pensado ¿¡Tanto texto para cuatro números!? Pues explicar los detalles de por medio no resulta tan sencillo, pues incluye ciertas cosas que si bien son simples no es posible despreciarlas, pues de hacerlo el entendimiento de la unidad se imposibilita. Me refiero con esto a cosas como el plano cartesiano sus ejes y algunas funciones que muchos de nosotros habremos visto desde bachillerato. La otra opción es tirarla al puro azar, hallar patrones e ir cambiándolos a ciegas, pero de esta manera es necesaria mucha suerte y se terminan malgastando los recursos, desde tiempo hasta memoria. Solo incluí cuatro números porque el post se alargaría demasiado si menciono también el resto, aunque da pie a un par de post más en los que mencione los faltantes (4-9).

El método resulta útil para dejar un mensaje, hacer una portada o hasta hacer un coqueto dibujo, aunque a día de hoy esto no es tan recurrente en los programas habituales. Me gustaría saber si te gustaría ver videos al respecto de estos tutoriales que he ido haciendo sobre programación y si tienes alguna sugerencia me la dejes en un comentario, sería de gran ayuda :D

Si te interesa otro tutorial de programación acá te dejo los links a los que he realizado hasta ahora:

And well... That's it! Surely you must have thought: So much text for four numbers? Well, explaining the details in between is not so easy, because it includes certain things that although they are simple, it is not possible to disregard them, otherwise the understanding of the unit becomes impossible. By this I mean things like the Cartesian plane, its axes and some functions that many of us will have seen since high school. The other option is to throw it to the purely by chance, find patterns and change them blindly, but this way you need a lot of luck and you end up wasting resources, from time to memory. I only included four numbers because the post would get too long if I also mention the rest, although it gives rise to a couple of more posts in which I mention the missing ones (4-9).

The method is useful to leave a message, make a cover or even make a cute drawing, although nowadays this is not so recurrent in the usual programs. I would like to know if you would like to see videos about these tutorials that I have been doing about programming and if you have any suggestion leave it in a comment, it would be a great help :D

If you are interested in another programming tutorial here are the links to the ones I have done until now:


Nombre de la publicación / Name of the postLINK
Calculador de datos para un triángulo rectángulo en C++1
Concecionario de autos, ejercicio en JAVA2
Calculador de edad básico C++3
Inversor de números de tres cifras4
¿Cuántos números de 3 cifras existen cuya suma sea 10? - ¡Respondiendo a otro usuario! C++6
Calculadora simple, cifra menos significativa y portada simple C++7
¡Vistazo a BeatUDO! [ESP-ENG] JAVA9
Comprobar si un número de dos cifras es primo C++10
Conversor de pulgadas a 7 unidades distintas C++11
Comprobar si un número es capicúa (Máx 5 cifras) C++12
Comprobador de caracteres C++13
Calculadora de índice de masa corporal C++14
Calculadora de factoriales C++15
Conversor (Grados Celsius - Fahrenheit - Kelvin) C++16
Calculadora de longitud, diametro y área de una circunferencia C++17

Programación c++.png

Puedes seguirme por acá si lo deseas:
You can follow me here if you want:

Diseño sin título.gif

Cuenta secundaria
(Dibujos, edición y juegos) | Secondary account (Drawings, editing and games)



0
0
0.000
2 comments