My Coding Quiz #46
hive-197685·@eniolw·
0.000 HBDMy 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>
👍 deadleaf, partitura.ccc, droida, quochuy, steemtelly, meins0815, davidlionfish, crimo, steemitbloggers, eliaschess333, mathowl, jd4e, mechanicalowl, regularowl, ennyta, splash-of-angs63, hispapro, enfocate, risckylu, eonwarped, jordangerder, maryelin, yonnathang, georgelys, evagavilan2, apeboy, yggdrasilwind, alvarezjessica, victordumont, caribayarte, yeidelyt, brujita18, yenmendt, beysyd, annafenix, asderhz, franvenezuela, gercripto, susurrodmisterio, esalcedo, chechostreet, universodaniel, flywithmarlin, dracrow, arzkyu97, petrarodriguez, javikun, saravm82, lqch, edfer18, enyusael, jesuspsoto, rawecz, norokochan, mairimgo23, amaillo, mcookies, ricardoeloy, eollarvesm, hiversbqto, mariiestefania, queasuluz, eleazarvo, zackygamer, juanmanuellopez1, janettyanez, esthersanchez, yiobri, jerusa777, lovver, thatcryptodave, zuerich, jesustiano, pravesh0, gaurav.art, good-karma, esteemapp, esteem.app, ecency, ecency.stats, fun.pravesh0, drwom, ahmadmangazap, allentaylor, indiaunited, shonyishere, frames, khan.dayyanz, yogeshbhatt, muterra, kamaleshwar, chandra.shekar, kannannv, codingdefined, jatinhota, bobinson, bala41288, cryptohaytham, imacryptogeek, abhay2695, biyimi, hardikv, lifecruiser, vishire, ayushthedreamer, ragavee, indiaunited-bot, godfather.ftw, disha30, deimage, pinkchic, kanibot, punkblogs, silenteyes, photographercr, balvinder294, balaz, bala-ag, ubaldonet, lemouth, steemstem-trig, steemstem, dna-replication, minnowbooster, howo, aboutcoolscience, robotics101, stemsocial, roelandp, metabs, curie, walterjay, jga, wilians, kenadis, r00sj3, sco, branbello, real2josh, geopolis, alexdory, charitybot, gadrian, michaelwrites, marcuz, javier.dejuan, meanroosterfarm, cowpatty, afarina46, andreina57, hive-108278, maar, krrizjos18, nabu.doconosor2, pinkfloyd878, cindynancy, tuba777, justtryme90, lamouthe, sustainablyyours, helo, samminator, mahdiyari, alexander.alexis, tsoldovieri, abigail-dantes, aidefr, postpromoter, madridbg, fragmentarion, leoumesh, kingabesh, nattybongo, pboulet, newton666, waraira777, nazer, oahb132, maxelitereturned, sam9999, amafable07, nazom, nwothini335, techslut, valth, bhoa, enzor, lottje, sankysanket18, intrepidphotos, pandasquad, dexterdev, francostem, de-stem, charitymemes, deholt, temitayo-pelumi, doctor-cog-diss, purelyscience, eternalsuccess, imbartley, hjmarseille, monica-ene, noelyss, waivio.curator, ehizgabriel, vagabond42069, michelle.gent, edb, dhimmel, oluwatobiloba, lugaxker, mobbs, zonguin, sorin.cristescu, hanggggbeeee, lpv, hijosdelhombre, pab.ink, cool08, emiliomoron, galam, melvin7, me2selah, crystalhuman, ilovecryptopl, gerdtrudroepke, stem.witness, jtm.support, manic.calm, kei2, checkyzk, inibless, vankushfamily, indigoocean, fsm-core, zerozeroone, technico, croctopus, modernzorker, eliel, melbourneswest, zirky, altleft, photohunt, edithbdraw, precarious, the100, davidbright, cnfund, rt395, pipiczech, redrica, sunsea, minerthreat, armandosodano, bhdc, anafae, atexoras.pub, sbtofficial, zacherybinx, martibis, michelmake, therising, tokensink, h3m4n7, juanmiguelsalas, thelordsharvest, tomatom, irgendwo, steem.services, double-negative, steemegg, aicoding, baltai, steemdiamond, doodleaday, cuzimgleb, sgt-dan, dashfit, steemiteducation, braveboat, bernardino, laxam, trisolaran, the.success.club, rondonshneezy, drhueso, azj26, clpacksperiment, coindevil, dipom98, torico, tiffin, sarahandsam, benwickenton, jjerryhan, sawyn, theskmeister, tawadak24, migka, schoolforsdg4, broncofan99, marivic10, alvinauh, netvalar, windail1, jaylatour, detlev, tazbaz, esmeesmith, gambit-x, moretea, videosteemit, movingman, yourmind, ayee11, street.curator, gmzorn, sergiomendes, pepskaram, revo, kaylinart, justyy, bartosz546, kodeblaccc, limn, communitybank, dejan.vuckovic, jigstrike, takowi, javyeslava.photo, blockgolem, finkistinger, raj808, onemedia, utube, zelenicic, death-and-taxes, cosplay.hadr, annabeth, syh7758520, diabolika, cryptononymous, hetty-rowan, greddyforce, qila, followjohngalt, federacion45, ahmedsy, kristall97, hubeyma, laviesm, mugueto2022, gunthertopp, marcolino76, carn, meritocracy, seinkalar, cugel, yixn, achimmertens, proxy-pal, boynashruddin, battebilly, bennettitalia, flyerchen, serylt, aicu, luisestaba23, sidalim88, tristancarax, hhayweaver, c0wtschpotato, quinnertronics, elgatoshawua, mario02, zerofour, matilei, justfavour, steemed-proxy, koshwe, itharagaian, vietthuy, ghastlygames, yozen, jessicaossom, therealwolf, onestrong, perpetuum-lynx, merlin7, metroair, ragnarokdel, phgnomo, steemvault, tempravis, peterpanpan, celescu, jijisaurart, skycae, cheese4ead, steemcryptosicko, knightsunited, nozzy, smartsteem, marc-allaria, letenebreux, cercle, bastionpm, hiveonboard, hive-143869, entraide.rewards, cookaiss, ausbit.dev, independance, isiksenpalvoja, nabab, ledonjon, princessmewmew, felt.buzz, dbddv01, itwithsm, didic, outtheshellvlog, palasatenea, dev.maverick, florenceboens, epicdice, tinyhousecryptos, emeraldtiger, clavdio75, bitrocker2020, joeyarnoldvn, imcore, buildahouse, minava.museum, lordnight72, hive-fr, sapphireleopard, alaqrab, minnowpowerup, doifeellucky, gabrielatravels, bflanagin, cakemonster, tggr, bambukah, dune69, arunava, caladan, gordon92, kylealex, dmoonfire, gonklavez9, jmsansan, danokoroafor, rencongland, fantasycrypto, foxyspirit, zyx066, vittoriozuccala, krisconkr, borniet, baboz, johndeeback, mcsherriff, yadamaniart, investingpennies, skippyza, steempampanga, anneporter, nyxlabs, kingz1337, kingz1338, balabambuz, cloh76, vonaurolacu, iamsaray, grindle, zirkonov, adelepazani, frissonsteemit, multifacetas, hadrgames, trippymane, daje10, chasmic-cosm, steem4all, sportscontest, superlotto, citizendog, london65, steemstorage, jadung, angelanichole, beta500, lichtkunstfoto, meno, stahlberg, neneandy, autobodhi, h-hamilton, dodovietnam, aboutyourbiz, lenasveganliving, bluemaskman, noalys, blingit, yoghurt, atomcollector, scottshots, qberry, machan, omarrojas, torz18, rhemagames, tfeldman, gazbaz4000, cryptocoinkb, brianoflondon, witkowskipawel, humbe, whitneyalexx, driptorchpress, dreamm, apon318, cryptofiloz, newtrailers, chris-uk, mejustandrew, positiveninja, dcrops, belug, thepeoplesguild, vscampbell, apshamilton, hamismsf, jpbliberty, podping, derosnec, myach, zipporah, robmolecule, thales7, dawnoner, mowemu, flemingfarm, stayoutoftherz, mhel, thelittlebank, okluvmee, dvpm, thecryptodrive, joshglen, empath, sumant, reizak, xylliana, chipdip, stickchumpion, fatman, bscrypto, lorenzopistolesi, drawmeaship, we-are-lucky, voter002, solox, we-are-palcoin, archangel21, enjar, dandesign86, jayna, fineartnow, cliffagreen, steemean, littlesorceress, hikergirl, zerotoone, zmx, aries90, deanlogic, goblinknackers, apendix1994, acantoni, steveconnor, sc000, iansart, rocky1, failingforwards, bemier, amberyooper, leomarylm, bil.prag, yaelg, hairgistix, veeart, zerothree, sam99, neumannsalva, bambinaacida, certain, michaias, trouvaille, noctury, rmach, mcsvi, firstamendment, zest, jude9, ibt-survival, elevator09, forykw, ansoe, cloudspyder, mproxima, felixgarciap, sanderjansenart, primersion, mafufuma, vixmemon, hiddendragon, markwannabee, robibasa, hivecoffee, holovision.cash, mirteg, vindiesel1980, revueh, bushradio, grapthar, atheistrepublic, andre.btc, jerrybanfield, smariam, bigtakosensei, duke77, juecoree, stem-espanol, juecoree.stem, lorenzor, inthenow, sandracarrascal, josedelacruz, erickyoussif, uche-nna, aleestra, hivelist, sevenoh-fiveoh, hk-curation, ufv, iamphysical, azulear, ydavgonzalez, miguelangel2801, delpilar, tomastonyperez, elvigia, andrick, acont, reinaseq, fran.frey, giulyfarci52, ganjafarmer, hashkings, pepeymeli, xclanleo, liuke96player, infernalcoliseum, psicoluigi, peaceandwar, fatkat, amimohan, drifter1, neddykelly, buttcoins, cordeta, bobydimitrov, warpedpoetic, mariusfebruary, alvin0617, aaronkroeblinger, lettinggotech, hivehustlers, mytechtrail, russellstockley, jglake, maddogmike, hankanon, danaedwards, shinedojo, vegan.niinja, scruffy23, beerlover, realblockchain, ragnarhewins90, acousticguitar, drsensor, sardrt, marcoriccardi, kieranstone, safrizal.mus, vaultec, nfttunz, gribouille, thelogicaldude, afifa, eric-boucher, tommyl33, robertbira, nicole-st, ajfernandez, amansharma555, lk666, chrisdavidphoto, m1alsan, nwjordan, orlandogonzalez, cyprianj, gifty-e, dandays, endopediatria, bluefinstudios, joseluis91, careassaktart, ngwinndave, gamersclassified, chesspricepool, tipu, safar01, afzalqamar, alex-hm, mia-cc, kingscrown, diosarich, tobias-g, mightypanda, kryptogames, bcm, dappstats, julesquirin, blockbroccoli, fredinks, boatymcboatface, theshell, cryptogambit, longer, el-dee-are-es,