My Coding Quiz #46

in #hive-19768510 months ago

My Coding Quiz #46 👨‍💻🛠️🧩

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...




Quiz
By @eniolw


What's your choice?

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.


Mi Quiz de Programación #46 👨‍💻🛠️🧩

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...




Quiz
Por @eniolw


¿Cuál es tu elección?

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.

Sort:  

Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

You may also include @stemsocial as a beneficiary of the rewards of this post to get a stronger support. 
 

I see its a tough riddle but I hope you'll have someone with the correct answer. @tipu curate 8

Thanks.

This is not very tough ;) I have prepared a balanced combination of simple and complex riddles. For the expert programmers in this blockchain, they may seem "easy", but I am confident that some of them will challenge them.

Thank you!

You're most welcome and thanks for the clearance.

This post has been manually curated by @bhattg from Indiaunited community. Join us on our Discord Server.

Do you know that you can earn a passive income by delegating to @indiaunited. We share more than 100 % of the curation rewards with the delegators in the form of IUC tokens. HP delegators and IUC token holders also get upto 20% additional vote weight.

Here are some handy links for delegations: 100HP, 250HP, 500HP, 1000HP.

image.png

100% of the rewards from this comment goes to the curator for their manual curation efforts. Please encourage the curator @bhattg by upvoting this comment and support the community by voting the posts made by @indiaunited.

Thank you.