My Coding Quiz #38 馃懆鈥嶐煉火煕狅笍馃З
Welcome to the new installment of my series of Coding Quizzes, in which you will be able to test your knowledge and skills about programming and software development in a simple and fun way. If you want to learn more about it visit my blog here on Hive and the first post where I introduced it.
Without further ado, here's the riddle...
By
@eniolw
What's your choice?
Solution to the previous quiz: -1,1,2,4 | 5. Line 1 creates an array a of numeric elements and line 2 applies the built-in sort method to it. There are two things to note about this method.
First, the method modifies the original array on which it is applied and also returns a reference to that array, not to a new array. That means that both a and b are pointing to the same array; they are not distinct. If you wanted to treat variable a as immutable, that is, not modify it and return a new distinct array, then you could have used Javascript's new toSorted method.
Second, the correct use of sort is not as trivial as it looks here. Actually the correct thing to do is to provide it with a function argument that lets it know how to sort, otherwise you might be surprised by the result you get.
The original array [1,2,5,4,-1] will end up being sorted as expected: [ -1, 1, 2, 4, 5 ], but this is just an accident (I did it on purpose, actually). If you are not aware of this "feature" (not bug) of sort, you may end up making blunders in your code. I won't provide right now examples of how we should use sort more correctly, but you can learn more in the documentations and also maybe in a future issue I will talk about it.
Coming back to the script, line 3 applies the pop method that we know removes elements at the end of the array. In this case we specify an argument 1. Did you expect it to remove the item at position 1? Well, that's not going to happen! This is not Python. The JavaScript pop method takes no arguments, so it ignores the 1 and will always remove the final item. In our case, the array pointed to by a ends with 5, which is assigned to c, leaving the array pointed to by a at [ -1, 1, 2, 4 ].
The final line displays the contents of b and c on the screen.
If you want to blog about computer science and programming content, I invite you to join Hive and participate in its communities, such as STEM-social, Develop Spanish, Programming & Dev and others.
Mi Quiz de Programaci贸n #38 馃懆鈥嶐煉火煕狅笍馃З
Bienvenido a mi nueva serie de Quizzes de Programaci贸n, en la cual podr谩s poner a prueba tus conocimientos y habilidades sobre programaci贸n y desarrollo de software de una manera sencilla y divertida. Si quieres aprender m谩s sobre ella visita mi blog aqu铆 en Hive y el primer post donde la present茅.
Sin m谩s pre谩mbulos, he aqu铆 el acertijo...
Por
@eniolw
驴Cu谩l es tu elecci贸n?
Soluci贸n al quiz anterior: -1,1,2,4 | 5. La l铆nea 1 crea un arreglo a de elementos num茅ricos y la l铆nea 2 le aplica el m茅todo incorporado sort. Hay dos cosas a tener en cuenta sobre este m茅todo.
Primero, el m茅todo modifica el arreglo original en el que se aplica y tambi茅n devuelve una referencia a ese arreeglo, no a un nuevo arreglo. Eso significa que tanto a como b apuntan al mismo arreglo; no son distintos. Si quisieras tratar la variable a como inmutable, es decir, no modificarla y devolver un nuevo arreglo distinto, entonces podr铆as haber usado el nuevo m茅todo toSorted de Javascript.
En segundo lugar, el uso correcto de sort no es tan trivial como parece aqu铆. En realidad, lo correcto es proporcionarle un argumento de funci贸n que le permita saber c贸mo ordenar; de lo contrario, podr铆as sorprenderte con el resultado que obtengas.
El arreglo original [1,2,5,4,-1] terminar谩 ordenado como se esperaba: [ -1, 1, 2, 4, 5 ], pero esto es s贸lo un accidente (en realidad, lo hice a prop贸sito). Si no conoces esta "caracter铆stica" (no bug) de sort, puedes terminar cometiendo errores en tu c贸digo. No proporcionar茅 ahora ejemplos de c贸mo deber铆amos usar sort m谩s correctamente, pero puedes obtener m谩s informaci贸n en documentaciones y quiz谩s tambi茅n en una edici贸n futura hable de ello.
Volviendo al script, la l铆nea 3 aplica el m茅todo pop que sabemos que elimina elementos al final del arreglo. En este caso especificamos un argumento 1. 驴Esperaba que eliminara el elemento en la posici贸n 1? Bueno, 隆eso no va a pasar! Esto no es Python. El m茅todo pop de JavaScript no toma argumentos, por lo que ignora el 1 y siempre eliminar谩 el elemento final. En nuestro caso, el arreglo apuntada por a termina con 5, que se asigna a c, dejando el arreglo apuntada por a en [ -1, 1, 2, 4 ].
La 煤ltima l铆nea muestra el contenido de b y c en la pantalla.
Si quieres bloguear sobre contenido inform谩tico y de programaci贸n, te invito a unirte a Hive y participar en sus comunidades, tales como STEM-social, Develop Spanish, Programming & Dev y otras.