My Coding Quiz #46

View this thread on: d.buzz | hive.blog | peakd.com | ecency.com
·@eniolw·
0.000 HBD
My Coding Quiz #46
<div class="text-justify">

<center><h2>My Coding Quiz #46 👨‍💻🛠️🧩</h2></center>

<p>Welcome to the new installment of my series of <b>Coding Quizzes</b>, 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 <a href="/@eniolw">my blog</a> here on Hive and the <a href="/@eniolw/my-coding-quiz-1">first post</a> where I introduced it.</p>

<h3>Without further ado, here's the riddle...</h3>

<br>
<center>
<img src="https://images.ecency.com/DQmdv8gLVDUZfCxQFrmnxWGStb6Ls2MQXDuqzvXn1TPkSeb/imagen.png" alt="Quiz">
<h6>By @eniolw</h6>
</center>

<br><center><h3>What's your choice?</h3></center>

<p><b>Solution to the <a href="/@eniolw/my-coding-quiz-45">previous quiz</a>:</b> <b>r2</b>. 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 <i>shuffle</i> 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:</p>

<p><code>const r1 = b.toSorted(_ => Math.random())</code>: This almost works, except that what is returned by the anom function will always be a positive value, even if it is random, so <code>toSorted</code> will not sort anything. To sort numeric items, you have to specify a function that allows <code>toSorted</code> 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 <code>r1</code> is always <b>[ 0, 1, 2, 3, 4, 5 ]</b> at each execution.</p>

<p><code>const r2 = b.toSorted(_ => Math.random() - 0.5)</code>: This solves the above problem. Since we are subtracting 0.5 from the random value generated by <code>Math.random</code>, 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 <code>toSorted</code> to sort randomly, since it will get either a positive or a negative each time.</p>

<p><code>const r3 = b.map(_ => Math.floor(Math.random()))</code>: It doesn't work because by doing <code>Math.floor</code>, we are rounding down, which will make every value generated by <code>Math.random</code> zero. Map will fill the array with pure zeros: <b>[ 0, 0, 0, 0, 0, 0 ]</b>. Even if we avoided this, we wouldn't be shuffling the elements of the base array, which is what we're interested in.</p>

<p><code>const r4 = b.sort(Math.random)</code>: This returns <b>[ 0, 1, 2, 3, 4, 5 ]</b> for the same reason as the first instruction that created <code>r1</code>. The difference is that <code>sort</code> does not create a new array, but overwrites the array to which it is applied. In this case, the original array <code>b</code> was altered, which is a destructive operation and you have to be very careful with it.</p>

<p>If you are more curious about how <code>toSorted</code> and <code>sort</code> work, you can consult some <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toSorted'>official documentations</a>. It is not entirely clear to me how Javascript does the sorting, <a href="https://www.w3schools.com/js/js_array_sort.asp">as it seems to depend on the web browser and there is no a priori sorting method for this function</a>. What is known is that Javascript will prioritise stable sorting methods, leaving aside quicksort.</p>

<hr>

<p>If you want to blog about computer science and programming content, I invite you to join <a href="/">Hive</a> and participate in its communities, such as <a href="/created/hive-196387">STEM-social</a>, <a href="/created/hive-154226">Develop Spanish</a>, <a href="/created/hive-169321">Programming & Dev</a> and others.</p>

<hr>

<center><h2>Mi Quiz de Programación #46 👨‍💻🛠️🧩</h2></center>

<p>Bienvenido a mi nueva serie de <b>Quizzes de Programación</b>, 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 <a href="/@eniolw">mi blog</a> aquí en Hive y el <a href="/@eniolw/my-coding-quiz-1">primer post</a> donde la presenté.</p>

<h3>Sin más preámbulos, he aquí el acertijo...</h3>

<br>
<center>
<img src="https://images.ecency.com/DQmP2ut2hK9ZtXscevAEkrEnrXaqiSJQxVsX66UQ45Zmgpy/imagen.png" alt="Quiz">
<h6>Por @eniolw</h6>
</center>

<br><center><h3>¿Cuál es tu elección?</h3></center>

<p><b>Solución al <a href="/@eniolw/my-coding-quiz-45">quiz anterior</a>:</b> <b>r2</b>. 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 <i>shuffle</i> (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:</p>

<p><code>const r1 = b.toSorted(_ => Math.random())</code>: 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 <code>toSorted</code> no ordenará nada. Para ordenar elementos numéricos, debe especificar una función que permita a <code>toSorted</code> 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 <code>r1</code> es siempre <b>[ 0, 1, 2, 3, 4, 5 ]</b> en cada ejecución.</p>

<p><code>const r2 = b.toSorted(_ => Math.random() - 0.5)</code>: Esto resuelve el problema anterior. Dado que estamos restando 0,5 del valor aleatorio generado por <code>Math.random</code>, 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 <code>toSorted</code> ordene aleatoriamente, ya que obtendrá un resultado positivo o negativo cada vez.</p>

<p><code>const r3 = b.map(_ => Math.floor(Math.random()))</code>: No funciona porque al hacer <code>Math.floor</code>, estamos redondeando hacia abajo, lo que hará que cada valor generado por <code>Math.random</code> sea cero. Map llenará la matriz con ceros puros: <b>[ 0, 0, 0, 0, 0, 0 ]</b>. Incluso si evitáramos esto, no estaríamos mezclando los elementos de la matriz base, que es lo que nos interesa.</p>

<p><code>const r4 = b.sort(Math.random)</code>: Esto devuelve <b>[ 0, 1, 2, 3, 4, 5 ]</b> por el mismo motivo que el primera instrucción que creó <code>r1</code>. La diferencia es que <code>sort</code> 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 <code>b</code>, lo cual es una operación destructiva y hay que tener mucho cuidado con ella.</p>

<p>Si tienes más curiosidad sobre cómo funcionan <code>toSorted</code> y <code>sort</code>, puedes consultar algunas <a href='https://developer.mozilla.org/en- US/docs/Web/JavaScript/Reference/Global_Objects/Array/toSorted'>documentaciones oficiales</a>. No me queda del todo claro cómo hace Javascript el ordenamiento, <a href="https://www.w3schools.com/js/js_array_sort.asp">ya que parece depender del navegador web y no hay ningún dato a priori. método de ordenamiento para esta función</a>. Lo que sí se sabe es que Javascript dará prioridad a los métodos de ordenamiento estables, dejando de lado a quicksort.</p>

<hr>

<p>Si quieres bloguear sobre contenido informático y de programación, te invito a unirte a <a href="/">Hive</a> y participar en sus comunidades, tales como <a href="/created/hive-196387">STEM-social</a>, <a href="/created/hive-154226">Develop Spanish</a>, <a href="/created/hive-169321">Programming & Dev</a> y otras.</p>

</div>
👍 , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,