Algorithm, a challenge in programming | Algoritmo, un reto en programación [EN/ESP]

in Programming & Devlast year (edited)

Is it enough to solve only one problem? Is it enough to just open the editor and write code? What is the optimal algorithm and how is it found? Today I will present a short discussion about algorithms. I hope, it's interesting and enjoyable.

¿Es suficiente para resolver un solo problema? ¿Es suficiente simplemente abrir el editor y escribir código? ¿Cuál es el algoritmo óptimo y cómo se encuentra? Hoy presentaré una breve discusión sobre algoritmos. Espero que sea interesante y agradable.

Sometimes different solutions are offered to solve a problem. These solutions are problem-solving algorithms that the programmer provides in the form of coding in the form of a software. This algorithm can be optimal or not!

A veces se ofrecen diferentes soluciones para resolver un problema. Estas soluciones son algoritmos de resolución de problemas que el programador proporciona en forma de codificación en forma de software. ¡Este algoritmo puede ser óptimo o no!

It doesn't matter what programming language is used to write the algorithm codes. The algorithm itself is important. The optimality of an algorithm can be evaluated based on different criteria. This is one of the principles of software design.

No importa qué lenguaje de programación se use para escribir los códigos del algoritmo. El algoritmo en sí es importante. La optimización de un algoritmo se puede evaluar en función de diferentes criterios. Este es uno de los principios del diseño de software.

To be honest, I had never paid attention to this aspect until I read the Algorithm Design book. But then, when I looked at the past algorithms, I clearly saw how I had followed it in some of them and of course not in others.

Para ser honesto, nunca había prestado atención a este aspecto hasta que leí el libro Diseño de algoritmos. Pero luego, cuando miré los algoritmos anteriores, vi claramente cómo lo había seguido en algunos de ellos y, por supuesto, en otros no.

In general, the algorithm depends on different criteria and factors, but the two most important factors that a programmer can control and check are the time and the amount of memory consumed.

En general, el algoritmo depende de diferentes criterios y factores, pero los dos factores más importantes que un programador puede controlar y verificar son el tiempo y la cantidad de memoria consumida.

When you provide an algorithm for a problem, you'll be able to test it against these two criteria to see if it's optimal!

Cuando proporcione un algoritmo para un problema, podrá probarlo con estos dos criterios para ver si es óptimo.

When I attended an introductory robotics course at the invitation of my friends, I could clearly see mistakes in the robot coding phase with Codevision. When the microcontroller had to execute the function infinitely in a loop for a simple comparison! An additional task that was ignored and slowed down the execution!

Cuando asistí a un curso de introducción a la robótica por invitación de mis amigos, pude ver claramente los errores en la fase de codificación de robots con Codevision. ¡Cuando el microcontrolador tuvo que ejecutar la función infinitamente en un bucle para una comparación simple! ¡Una tarea adicional que fue ignorada y ralentizó la ejecución!

You can't be a perfectionist! Sometimes it's necessary to give up one. It is your perspective that will make the algorithm.

¡No se puede ser perfeccionista! A veces es necesario renunciar a uno. Es su perspectiva la que hará el algoritmo.

Imagine a function called len() returns the length of an array and you have a code like this:

Imagina una función llamada len() que devuelve la longitud de una matriz y tienes un código como este:

  for(int i = 0; i<len(arr); i++){}

If we consider the execution time of declaration,initialization, assignment, increment, comparison and the like as a constant value T(1), then the algorithm can be examined.

Si consideramos el tiempo de ejecución de la declaración, inicialización, asignación, incremento, comparación y similares como un valor constante T(1), entonces se puede examinar el algoritmo.

As you can see, the execution time of this algorithm is T = (n+1)(T(f) + 2T(1)). If the array has 3 elements and we assume the execution time of the function and T(1) to be 1 millisecond, then this algorithm will be executed with this array length for T = 12 ms.

Como puede ver, el tiempo de ejecución de este algoritmo es T = (n+1)(T(f) + 2T(1)). Si la matriz tiene 3 elementos y suponemos que el tiempo de ejecución de la función y T(1) es de 1 milisegundo, entonces este algoritmo se ejecutará con esta longitud de matriz para T = 12 ms.

Another person wrote the same code as follows:

Otra persona escribió el mismo código de la siguiente manera:

   int len = len(arr);
   for(int i = 0; i<len; i++){}

With this in mind, let's examine the algorithm. The execution time of this algorithm is T = (2n + 3)T(1) + T(f). As a result, this algorithm is executed for T = 10 ms.

Con esto en mente, examinemos el algoritmo. El tiempo de ejecución de este algoritmo es T = (2n + 3)T(1) + T(f). Como resultado, este algoritmo se ejecuta para T = 10 ms.

So the second algorithm runs faster. Maybe the difference in execution time with this array length is insignificant, but if you consider the array length as 100, then the execution time of the first algorithm is T = 303 ms and the execution time of the second algorithm is T = 204 ms.

Así que el segundo algoritmo se ejecuta más rápido. Tal vez la diferencia en el tiempo de ejecución con esta longitud de matriz sea insignificante, pero si considera que la longitud de la matriz es 100, entonces el tiempo de ejecución del primer algoritmo es T = 303 ms y el tiempo de ejecución del segundo algoritmo es T = 204 ms.

Now let's assume that the execution time of the function is 10 milliseconds and for T(1) is 1 millisecond. In this case, the execution time of the first algorithm for a 100-element array is T = 1212 ms, which means more than 1 second, and the execution time of the second algorithm is T = 213 ms. For a 3-element array, T = 48 ms and T = 19 ms, respectively.

Ahora supongamos que el tiempo de ejecución de la función es de 10 milisegundos y para T(1) es de 1 milisegundo. En este caso, el tiempo de ejecución del primer algoritmo para una matriz de 100 elementos es T = 1212 ms, lo que significa más de 1 segundo, y el tiempo de ejecución del segundo algoritmo es T = 213 ms. Para una matriz de 3 elementos, T = 48 ms y T = 19 ms, respectivamente.

As you can see, the speed of the algorithm gets bigger and bigger according to the length of the array and also the execution time of the function.

Como puede ver, la velocidad del algoritmo se vuelve más y más grande de acuerdo con la longitud de la matriz y también con el tiempo de ejecución de la función.

If we consider the amount of memory consumed by each type of int as 4 bytes, then the second algorithm consumes 4 bytes more memory than the first algorithm.

Si consideramos la cantidad de memoria consumida por cada tipo de int como 4 bytes, entonces el segundo algoritmo consume 4 bytes más de memoria que el primer algoritmo.

So we conclude, the first algorithm is slower and consumes less memory, but the second algorithm is faster and consumes more memory. Personally, I prioritize the algorithm execution speed and this factor is much more important. However, the second factor should not be ignored, especially when you are faced with limited available memory!

Entonces concluimos, el primer algoritmo es más lento y consume menos memoria, pero el segundo algoritmo es más rápido y consume más memoria. Personalmente, priorizo la velocidad de ejecución del algoritmo y este factor es mucho más importante. Sin embargo, el segundo factor no debe ignorarse, ¡especialmente cuando se enfrenta a una memoria disponible limitada!

Sort:  

!LUV

!LUV

@iscompard, sorry! You need more $LUV to use this command.

The minimum requirement is 10.0 LUV in your liquid wallet.

More LUV is available from Hive-Engine or Tribaldex

!LUV

@invis23, sorry! You need more $LUV to use this command.

The minimum requirement is 10.0 LUV in your liquid wallet.

More LUV is available from Hive-Engine or Tribaldex

!LUV

@haderegret, sorry! You need more $LUV to use this command.

The minimum requirement is 10.0 LUV in your liquid wallet.

More LUV is available from Hive-Engine or Tribaldex