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.
Solution to the previous quiz: r2. In line 1 we simply define an array of numerical items that we will use as a basis for the rest. The idea is to get an array of these same elements in random order. This is called shuffle and is a very useful and common functionality. However, only one of the instructions in the script does the shuffling correctly. Let's take a closer look at each one:
const r1 = b.toSorted(_ => Math.random()): This almost works, except that what is returned by the anom function will always be a positive value, even if it is random, so toSorted will not sort anything. To sort numeric items, you have to specify a function that allows toSorted to compare two items and determine which to put on the left or right, based on which is larger or smaller. This explains why the content of r1 is always [ 0, 1, 2, 3, 4, 5 ] at each execution.
const r2 = b.toSorted(_ => Math.random() - 0.5): This solves the above problem. Since we are subtracting 0.5 from the random value generated by Math.random, it means we will have a range of -0.5 to 0.5. There is a 50% chance that the number will be positive or negative. This will allow toSorted to sort randomly, since it will get either a positive or a negative each time.
const r3 = b.map(_ => Math.floor(Math.random())): It doesn't work because by doing Math.floor, we are rounding down, which will make every value generated by Math.random zero. Map will fill the array with pure zeros: [ 0, 0, 0, 0, 0, 0 ]. Even if we avoided this, we wouldn't be shuffling the elements of the base array, which is what we're interested in.
const r4 = b.sort(Math.random): This returns [ 0, 1, 2, 3, 4, 5 ] for the same reason as the first instruction that created r1. The difference is that sort does not create a new array, but overwrites the array to which it is applied. In this case, the original array b was altered, which is a destructive operation and you have to be very careful with it.
If you are more curious about how toSorted and sort work, you can consult some official documentations. It is not entirely clear to me how Javascript does the sorting, as it seems to depend on the web browser and there is no a priori sorting method for this function. What is known is that Javascript will prioritise stable sorting methods, leaving aside quicksort.
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.
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茅.
Soluci贸n al quiz anterior: r2. En la l铆nea 1 simplemente definimos una serie de elementos num茅ricos que usaremos como base para el resto. La idea es obtener una serie de estos mismos elementos en orden aleatorio. Esto se llama shuffle (barajeo o mezcla) y es una funcionalidad muy 煤til y com煤n. Sin embargo, s贸lo una de las instrucciones del script realiza la mezcla correctamente. Echemos un vistazo m谩s de cerca a cada una:
const r1 = b.toSorted(_ => Math.random()): Esto casi funciona, excepto que lo que devuelve la funci贸n an贸nima siempre ser谩 un valor positivo, incluso si es aleatorio, por lo que toSorted no ordenar谩 nada. Para ordenar elementos num茅ricos, debe especificar una funci贸n que permita a toSorted comparar dos elementos y determinar cu谩l colocar a la izquierda o a la derecha, seg煤n cu谩l sea m谩s grande o m谩s peque帽o. Esto explica por qu茅 el contenido de r1 es siempre [ 0, 1, 2, 3, 4, 5 ] en cada ejecuci贸n.
const r2 = b.toSorted(_ => Math.random() - 0.5): Esto resuelve el problema anterior. Dado que estamos restando 0,5 del valor aleatorio generado por Math.random, significa que tendremos un rango de -0,5 a 0,5. Hay un 50% de posibilidades de que el n煤mero sea positivo o negativo. Esto permitir谩 que toSorted ordene aleatoriamente, ya que obtendr谩 un resultado positivo o negativo cada vez.
const r3 = b.map(_ => Math.floor(Math.random())): No funciona porque al hacer Math.floor, estamos redondeando hacia abajo, lo que har谩 que cada valor generado por Math.random sea cero. Map llenar谩 la matriz con ceros puros: [ 0, 0, 0, 0, 0, 0 ]. Incluso si evit谩ramos esto, no estar铆amos mezclando los elementos de la matriz base, que es lo que nos interesa.
const r4 = b.sort(Math.random): Esto devuelve [ 0, 1, 2, 3, 4, 5 ] por el mismo motivo que el primera instrucci贸n que cre贸 r1. La diferencia es que sort no crea una nueva matriz o arreglo, sino que sobrescribe la matriz a la que se aplica. En este caso, se alter贸 el array original b, lo cual es una operaci贸n destructiva y hay que tener mucho cuidado con ella.
Si tienes m谩s curiosidad sobre c贸mo funcionan toSorted y sort, puedes consultar algunas documentaciones oficiales. No me queda del todo claro c贸mo hace Javascript el ordenamiento, ya que parece depender del navegador web y no hay ning煤n dato a priori. m茅todo de ordenamiento para esta funci贸n. Lo que s铆 se sabe es que Javascript dar谩 prioridad a los m茅todos de ordenamiento estables, dejando de lado a quicksort.
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.