<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Dan Romans on Medium]]></title>
        <description><![CDATA[Stories by Dan Romans on Medium]]></description>
        <link>https://medium.com/@danromans?source=rss-c8fbe0846cb0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*5LZfTzltumVVoZRsxe-BtQ.jpeg</url>
            <title>Stories by Dan Romans on Medium</title>
            <link>https://medium.com/@danromans?source=rss-c8fbe0846cb0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 21:37:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@danromans/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Importance of Being Thorough, Taking Time, and Being Okay With It]]></title>
            <link>https://medium.com/@danromans/the-importance-of-being-thorough-taking-time-and-being-okay-with-it-e0c33fee56a8?source=rss-c8fbe0846cb0------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0c33fee56a8</guid>
            <category><![CDATA[process]]></category>
            <category><![CDATA[self-care]]></category>
            <category><![CDATA[societal-pressures]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[efficiency]]></category>
            <dc:creator><![CDATA[Dan Romans]]></dc:creator>
            <pubDate>Fri, 10 Jul 2020 20:28:40 GMT</pubDate>
            <atom:updated>2020-07-13T16:02:50.528Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Luke Skywalker training with Master Yoda from the film The Empire Strikes Back(1980)." src="https://cdn-images-1.medium.com/max/800/1*2Z36hN7HqSdNPwfSE2JosQ.jpeg" /><figcaption>“You must unlearn what you have learned.”</figcaption></figure><p>This week, I really wanted to post an article about what I’m currently working on: using <a href="https://en.wikipedia.org/wiki/WebSocket">WebSockets</a> to implement private user-to-user messaging for an existing <a href="https://reactjs.org/">React</a>/<a href="https://rubyonrails.org/">Rails</a> application.</p><p>I’m still in the weeds. Trying to fully understand WebSockets, dealing with communication between frameworks, triple-checking the model relations for the database and serializers, integrating <a href="https://jwt.io/">JWT</a> authorization and authentication, debugging broadcasts being sent by <a href="https://www.npmjs.com/package/react-actioncable-provider">ActionCable Provider</a>, deciding if I should scrap that package altogether and compose cable middleware for <a href="https://redux.js.org/">Redux</a>, et cetera.</p><p>I found there is not a holy grail of tutorials which could clearly explain the setup for this particular stack and set of circumstances, so I intend to write one, but I’m simply not ready.</p><p>I like writing articles. I like meticulously digesting then relaying useful information. I like providing a resource that serves to help others. However, there is another reason why I wanted to have finished my work and felt prepared to write an article this week: a deadline.</p><p>We live in a society which is focused on competition. Plants and animals compete, too, for territory, food, dominance, but our human competition has been abstracted. The competition of humans is to be successful, which affords you wealth, status, stability, privilege. In most societies, the individual is directly or indirectly pressured to fit into a very broken, unequal system and beat the same well travelled path towards an ideal of success which has been defined for you and expected from you.</p><p>That over-arching theme trickles down into everyday life, to mundane tasks, like making sure I write an article this week to meet my deadline, despite not being prepared enough to write and share an article of substantial quality that will enrich the knowledge and pleasure of others instead of clogging the internet.</p><p>I propose that a better measure of success is an individual given time to understand as they are able, without anxiety, shame, or negative consequence, and ultimately able to empower themselves and their community with strong, foundational knowledge.</p><h4>Being Thorough:</h4><p>People tend to rush through things. We crave a working result or benefit without investing the time and energy required to understand how that thing works and how it provides benefit. Of course, it’s not necessary to know how <em>everything</em> works, but you should be confidently knowledgeable of your craft. A great chef has cooked thousands of dishes, a great musician has played thousands of songs. Both able to do so because they spent a good deal of energy learning and exercising their craft, from the first ingredient or note.</p><p>Thoroughly learning a topic allows you to master it. You can easily rely on the work of others, but are then beholden to them when a thing stops working. A strong foundation requires hard work, but it will unlock many doors on the journey from introduction to innovation. This thorough foundation and mastery tends to be less common than amateur and intermediate understanding, often for no other reason than the fact that it takes time.</p><h4>Taking Time:</h4><p>Our socially ubiquitous impulse-driven habits are often present because of the absence of institutional support and flexibility. More often than not, a result is required in a certain amount of time, and because you’re stuck working within a competitive system, a may-the-best-person-win attitude compels or requires your cursory understanding and quick delivery.</p><p>It can be tough to practically implement this idea, but, whenever possible, defy this kind of pressure and take the time you need to perform. Time may be valuable to a stakeholder, as the saying “time is money” suggests, but that time is most valuable to you, the learner, the performer.</p><p>Ironically, the pressure to rush through work seldom produces an optimal solution. I firmly believe that the right tool should be used for the job, and a job should be prepared well and done once instead of prepared poorly and done twice. Take the time you need to produce great work.</p><h4>Being Okay with Taking the Time You Need to Be Thorough:</h4><p>There is another issue which presents when faced with a situation that requires you to rush to deliver: lack of confidence and self worth. These are unfortunate feelings that can happen to all of us. The feeling of not being good enough. The feeling of comparing yourself negatively to others. Do not let these damning thoughts derail or define you because they hold no stock.</p><p>Everyone is different. Everyone has different strengths and weaknesses. Everyone has a different style of learning and ways of performing. Yet, we are typically subject to a singular standard. Just because one person learns a new skill in an afternoon and another needs a week does not certify the afternoon learner’s understanding more thorough than the leaner who took a week, but can now perform the skill with their eyes closed, for the rest of their lives. We all have worth. Be content with your mode of understanding.</p><p><a href="https://github.com/dangrammer">github.com/dangrammer</a><br><a href="https://www.linkedin.com/in/danieljromans/">linked.com/in/danieljromans</a><br><a href="http://danromans.com/">danromans.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0c33fee56a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working With Bits in JavaScript]]></title>
            <link>https://javascript.plainenglish.io/working-with-bits-edbe4daeac6c?source=rss-c8fbe0846cb0------2</link>
            <guid isPermaLink="false">https://medium.com/p/edbe4daeac6c</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[code-challenge]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Dan Romans]]></dc:creator>
            <pubDate>Mon, 06 Jul 2020 01:55:23 GMT</pubDate>
            <atom:updated>2020-07-07T15:18:32.048Z</atom:updated>
            <content:encoded><![CDATA[<h3>Working With Bits In JavaScript</h3><figure><img alt="Pac-Man trying to eat pac-dots while evading Blinky, Inky, Pinky, and Clyde." src="https://cdn-images-1.medium.com/max/910/1*kP64AXOI_oml41Xj_NxPLA.png" /><figcaption>01000110 01101001 01110110 01100101 00100000 01110000 01100001 01100011 00101101 01100100 01101111 01110100 01110011 00100000 01100001 01110111 01100001 01111001 00100000 01100110 01110010 01101111 01101101 00100000 01110011 01101111 01101101 01100101 00100000 01100010 01101111 01101110 01110101 01110011 00100000 01100110 01110010 01110101 01101001 01110100 00100001</figcaption></figure><h4>I recently did a HackerRank code challenge called <a href="https://www.hackerrank.com/challenges/flipping-bits/problem"><em>Flipping Bits</em></a> and had a ton of fun!</h4><p>It’s a pretty simple problem, but it prompted some exploration and implementation of <a href="https://en.wikipedia.org/wiki/Binary_data#:~:text=Binary%20data%20is%20data%20whose,numeral%20system%20and%20Boolean%20algebra.">binary data</a>, <a href="https://en.wikipedia.org/wiki/Algebra">algebra</a>, and <a href="https://en.wikipedia.org/wiki/Bitwise_operation">bitwise operation</a>. I programmed in JavaScript while working on this challenge. Consequently, the code examples in this article will be in JavaScript and the bitwise operators specific to the language. However, bitwise operations are mostly universal. Many programming languages utilize bitwise operators in the same way, or primarily vary in syntax, so the knowledge should be easily transferable.</p><p>A binary datum, referred to as a bit in computer science, is represented by one of only two states: 0 and 1. You can think of this as a switch: OFF and ON. At a very low level, binary data is responsible for almost every sweet computer pastime you partake in. Bits are analogous to cells of a body. We use our fingers to type and our eyes to read, but, deep within, cells comprise the engine which produces our body processes, locomotion, and more.</p><p>Bits are useful, <em>powerful</em> data. Most programmers work at a high level, especially more so as wonderful abstractions and conveniences offered by Frameworks and APIs are readily adopted and built upon. On the low level, where code needs to be solidly founded, bitwise operation is useful for real-world scenarios involving things like hardware communication, network protocols, graphics, cryptography, and permissions. The power comes from the simplistic logic of binary. At the binary level, interpreting or mutating a piece of data is as simple as flipping the switch on some zeros and ones.</p><p>We won’t be following Ant-Man to the Quantum Realm, not quite that far… but we will be delving into the binary realm to solve this code challenge and learn about bitwise operation. For this solution, I’m going to demonstrate a programmatic approach, then continue optimizing the code until the function is reduced to a single line of code, 27 characters long.</p><h3>Flipping Bits</h3><h4>Problem Statement:</h4><p>Given n, a 32-bit unsigned integer, flip the bits of its binary representation (0 -&gt; 1 | 1 -&gt; 0) and print the result as an unsigned integer. For Example:</p><pre>n = 123456</pre><pre>00000000000000011110001001000000<em>₂</em> = 123456<em>₁₀</em><br>11111111111111100001110110111111<em>₂</em> = 4294843839<em>₁₀</em></pre><pre>result = 4294843839</pre><p><em>*The base of each integer signifies its relation to decimal (base </em><em>₁₀) or binary (base </em><em>₂). Ten digits, like the decimal system, or two, as in binary: </em>0<em> and </em>1<em>.</em></p><p><em>*An </em><a href="https://www.ibm.com/support/knowledgecenter/ssw_aix_72/commprogramming/int_dat_typ.html"><em>unsigned integer</em></a><em> is a 32-bit datum that encodes a non-negative integer in the range </em>0<em> to </em>4294967295<em>. For the purposes of this challenge, just consider that we will work with 32-bit integers, and only positive values—not negative values.</em></p><h4>Function Description:</h4><p>The flippingBits() function should return an unsigned decimal integer.</p><p><strong>Input parameter:</strong></p><ul><li>n: an integer</li></ul><p><strong>Constraints:</strong></p><ul><li>0 ≤ n &lt; 2²³</li></ul><h4>Programmatic Solution:</h4><p>The logic is pretty simple: convert a decimal integer to binary, invert its zeros and ones, convert the inversion to a decimal integer. Let’s view the algorithm then explain each process.</p><pre><strong>function flippingBits(n) {<br></strong><em>// declare variables for binary, inverse binary, and decimal result<br>  </em><strong>let lowBin = &#39;&#39;<br>  let highBin= &#39;&#39;<br>  let result = 0</strong></pre><pre><em>// convert input decimal to binary</em><br> <strong> while (n &gt;= 1) {<br>    const rem = n % 2<br>    lowBin += rem<br>    rem === 1 ?<br>      n = Math.floor(n / 2) :<br>        n /= 2<br>  }</strong></pre><pre><em>// adjust binary to 32 bits<br>  </em><strong>while (lowBin.length &lt; 32) {<br>    lowBin += 0<br>  }</strong></pre><pre><em>// reverse and invert each bit of binary<br>  </em><strong>for (let i = lowBin.length - 1; i &gt;= 0; i--) {<br>    highBin += lowBin[i] === &#39;0&#39; ? &#39;1&#39; : &#39;0&#39;<br>  }</strong></pre><pre><em>// convert binary to decimal output<br> </em><strong><em> </em>for (let i = 0; i &lt; highBin.length; i++) {<br>    const expo = highBin.length - 1 - i<br>    result += highBin[i] * (2 ** expo)<br>  }</strong></pre><pre><strong>  return result<br>}</strong></pre><ol><li><strong>Declare variables for binary, inverse binary, and decimal result:</strong></li></ol><pre><strong> let lowBin = ‘’<br> let highBin= ‘’<br> let result = 0</strong></pre><p>A binary integer is represented left to right, as <em>high order</em> bit to <em>low order</em> bit. The variable lowBin will represent the binary in its first state, low to high, which will be because of how we algebraically convert the input. The variable highBin will be assigned a reversed copy of lowBin so we have a correct <em>high order</em> to <em>low order</em> bit structure. lowBin and highBin are both of type string, which will be convenient to work with. The variable result will be assigned the decimal conversion of the value held by highBin, and ultimately used as the return value. result is of type number, instantiated at 0, since it will be additively calculated.</p><p>2. <strong>Convert input decimal to binary:</strong></p><p>First let’s discuss how to perform this procedure algebraically. A decimal integer can be converted to binary by continually <em>evenly</em> dividing the integer by 2 (as in base <em>₂</em>, as in binary) until the value reaches 0, reserving the resultant remainders in sequence as bits. When evenly dividing any number by 2, the remainder must be 0 or 1. Consider this example:</p><pre>Divide 21 by 2 until the result is zero. The remainders of these divisions will be the bits used to construct the binary:</pre><pre>21 / 2 = 10 (+) rem 1 <em>low order bit</em><br>10 / 2 =  5 (+) rem 0<br> 5 / 2 =  2 (+) rem 1<br> 2 / 2 =  1 (+) rem 0<br> 1 / 2 =  0 (+) rem 1 <em>h</em><em>igh order bit</em></pre><pre>Organize the remainder bits into the binary integer: 10101</pre><p>1 / 2 = 0 (+) rem 1 is a bit confusing, but consider that we’re working with whole integers, and, once the value is reduced to 1, it can not be evenly divided as a whole integer while remaining greater than 0, so the value itself—1—becomes the remainder.</p><pre><em>// perform the last operation when the value 1 is passed in</em><strong><br>  while (n &gt;= 1) {</strong></pre><pre><em>// the </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Remainder"><em>remainder operator</em></a><em> (modulo operator) extracts <br>// the remainder of n / 2 and assigns the value, the bit, to rem</em><strong><br>    const rem = n % 2</strong></pre><pre><em>// rem is appended to the lowBin string<br>// note the importance of maintaining the binary sequence <br>// as a string, which would be more difficult numerically<br>// rem, a number, is coerced to a string and can be concatenated<br>    </em><strong>lowBin += rem</strong></pre><pre><em>// a conditional operator is used to adjust the value of n<br>// for the next iteration<br>// if rem is equal to 1, n is an odd value, so n is assigned<br>// the value of n / 2 rounded down with Math.floor()<br>// otherwise, rem must be equal to 0, indicating an even number,<br>// and n is assigned the value of n / 2<br>// this always ensures a whole integer is passed into the loop<br>    </em><strong>rem === 1 ?<br>      n = Math.floor(n / 2) :<br>        n /= 2<br>  }</strong></pre><p>3. <strong>Adjust binary to 32 bits:</strong></p><pre><strong>  while (lowBin.length &lt; 32) {<br>    lowBin += 0<br>  }</strong></pre><p>The preceding while loop which constructs the binary string only creates as many bits as are necessary to convert the decimal input. The remaining processes require a 32-bit value, so we simply use a while loop set with a limit condition of 32 to append zeros to the existing binary string. lowBin += 0 works because 0 is coerced into a string, but you can also be direct and use lowBin += ‘0’.</p><p>Note that because of the linear order of operation the preceding while loop performed, the binary string is in reverse order at this point—<em>low order</em> to <em>high order</em>—so the binary value can be padded with zeros from the right by appending them instead of the usual procedure of padding a binary value with zeros from the left by prepending them.</p><p>4. <strong>Reverse and invert each bit of binary:</strong></p><pre><strong>  for (let i = lowBin.length - 1; i &gt;= 0; i--) {<br>    highBin += lowBin[i] === &#39;0&#39; ? &#39;1&#39; : &#39;0&#39;<br>  }</strong></pre><p>We use a decrementing for loop to iterate over the binary string held by lowBin—end to beginning—i = 31 -&gt; i = 0. At each iteration, highBin is appended with the inverse of the current value (lowBin[i]), which is determined by a conditional operator: if 0, return 1; if 1, return 0. This process effectively reverses the binary string while inverting each bit.</p><p>5. <strong>Convert binary to decimal output:</strong></p><p>Again, let’s discuss how to perform this procedure algebraically. A binary integer can be converted to a decimal integer by multiplying each digit by its own power of 2 and summing the results, <em>i.e.</em> each bit, a 0 or 1, can be multiplied by 2 to the n power then summed. 2 correlates to base ₂, and n correlates to the position of the bit, like an index. For example:</p><pre>Convert 1001₂ to a decimal integer.<br>__________________________________<br>|        bit | 1  | 0  | 0  | 1  |<br>|————————————|————|————|————|————|<br>| power of 2 | 2³ | 2² | 2¹ | 2⁰ |<br>——————————————————————————————————<br>Note that the powers of 2 reflect a zero index, and <em>descend</em> because<br>binary integers are sequenced from high order to low order.</pre><pre>1001₂ = (1 * 2³) + (0 * 2²) + (0 * 2¹) + (1 * 2⁰) = 9₁₀</pre><pre>This can be further dissected like this:</pre><pre>   1 * (2 * 2 * 2) = 8<br> + 0 * (2 * 2)     = 0<br> + 0 * (2)         = 0<br> + 1 * (1)         = 1  (<em>n⁰ is always equal to 1</em>)<br>—–––––––––––––––––––––—    <br>                     9  </pre><p>By using a for loop, we conveniently have access to each bit’s value and position, or index.</p><pre><em>// instead of setting the limit condition to highBin.length - 1<br>// we set it to highBin.length (32) so we can accommodate a<br>// decrementing bit index all the way to 0 for the variable expo<br>// highBin.length - 1 would end the formula at n * 2¹<br>// if the last evaluated bit was 0 (0 * 2⁰ = 0), the last addend <br>// could be ignored, however, this condition is necessary because<br>// the last bit evaluated could be 1 (1 * 2⁰ = 1), impacting the<br>// result with a final addend of 1<br>  </em><strong>for (let i = 0; i &lt; highBin.length; i++) {</strong></pre><pre><em>// expo is assigned a number which represents each bit&#39;s position<br>// on the first iteration this would be: const expo = 32 - 1 - 0 = 31<br>    </em><strong>const expo = highBin.length - 1 - i</strong></pre><pre><em>// if the first bit was 0 (highBin[i] = 0), then the first <br>// addend of the conversion formula would be: 0 * 2³¹<br>// on each iteration the addend value is summed into result<br>    </em><strong>result += highBin[i] * (2 ** expo)<br>  }</strong></pre><p>6.<strong> Return result:</strong></p><p>Last, but not least, result will be returned by the function.</p><pre>const n = 123456 </pre><pre>flippingBits(n)</pre><pre>// lowBin = 00000010010001111000000000000000<br>// flip bits and reverse string<br>// highBin = 11111111111111100001110110111111</pre><pre>//=&gt; 4294843839</pre><h4>Optimized Programmatic Solution:</h4><p>I use the term optimized. I mean condensed for sure, but I have not tested the performance differences of these three solutions, so I can’t yet report on the true optimization. However, my cursory assessment is that yes, this solution is optimized, and the forthcoming ultra-compact bitwise solution seems pretty fast!</p><p>The previous solution seems like a lot of code to flip some bits, right? It just so happens that JavaScript, and presumably most other languages, have some built in methods and functions which can slim down our algorithm.</p><pre><strong>function flippingBits(n) {</strong><br><em>// the </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString">Number.toString()</a><em> method conveniently transforms a number<br>// into a string AND it can accept a radix argument to convert<br>// the number to a string of specific base, like base ₂ for binary<br> </em><strong><em> </em>let lowBin = n.toString(2)<br>  let highBin = &#39;&#39;</strong></pre><pre><em>// </em>Number.toString()<em> produces a binary string representation in<br>// the correct high order to low order sequence, so zeros are <br>// padded from the left by prepending them</em><br>  <strong>while (lowBin.length &lt; 32) {<br>    lowBin = 0 + lowBin<br>  }</strong></pre><pre><em>// since the high order to low order sequence is already correct<br>// this for loop only needs to flip bits, not reverse the string</em><br>  <strong>for (let i = 0; i &lt; lowBin.length; i++) {<br>    highBin += lowBin[i] === &#39;0&#39; ? &#39;1&#39; : &#39;0&#39;<br>  }</strong></pre><pre><em>// the </em>parseInt()<em> function conveniently transforms a string to a <br></em>// number AND it can accept a second argument of a radix to <br>// convert the string to a number of specific base<em>, like base ₂<br>  </em><strong>return parseInt(highBin, 2)<br>}</strong></pre><p>Comments aside, that’s a shorter, cleaner function than the previous one. It harnesses the power of built-ins, requires less memory, and performs less iteration. Is it possible that this algorithm can be condensed into a single performant line of code and achieve the same result? Drum roll, please.</p><figure><img alt="Art Blakey playing a drum roll." src="https://cdn-images-1.medium.com/max/498/1*tPKIpbk4lDGUrngYSAgykw.jpeg" /><figcaption>Thank you, jazz messenger!</figcaption></figure><h4>Bitwise Solution:</h4><pre><strong>const flippingBits = n =&gt; ~n &gt;&gt;&gt; 0</strong></pre><p>Can you believe it? I almost didn’t! The ES6 fat arrow function helps a bit (no pun), but the function statement/return value is so concise it is to be marveled at. The function receives an argument, a number n, and returns the decimal integer representation of the inverse binary sequence of n. But how?</p><ol><li><strong>The Bitwise NOT operator:</strong></li></ol><p>The Bitwise NOT operator is symbolized as ~ and it inverts the binary value of each bit of the operand. That means that under the hood a number’s binary representation is inverted. Every 0 is flipped to a 1, every 1 is flipped to a 0. 010100 would become 101011. There is one caveat, though.</p><p>The produced value is a <a href="https://www.ibm.com/support/knowledgecenter/ssw_aix_72/commprogramming/int_dat_typ.html">signed integer</a>. The <em>high order</em> bit, <em>i.e.</em> leftmost bit, of a signed integer is also know as the <a href="https://en.wikipedia.org/wiki/Sign_bit#:~:text=In%20computer%20science%2C%20the%20sign,significant%20bit%22%20in%20some%20contexts.">sign bit</a> and indicates the sign of a number, <em>i.e.</em> whether the number is positive (0) or negative (1). For our purposes, the understanding is that the sign bit is inverted along with all the other bits, transforming a positive input into a negative output.</p><p>Our code challenge requires us to return a positive, unsigned, 32-bit integer. We have none of that after using the Bitwise NOT operator. Fear not, there is another bitwise operator to save the day.</p><p>2. <strong>The Zero-fill Right Shift operator:</strong></p><p>The Zero-fill Right Shift operator is symbolized as &gt;&gt;&gt; and accepts an argument specifying a number of shifts. It shifts the <em>high order</em> bit the specified number of bits to the right. Excess bits are discarded to the right while zero (0) bits are padded onto the left. Since the sign bit becomes a zero, the value becomes positive.</p><p>For this solution, the specified number of shifts is 0, which essentially creates a situation where our binary sequence is padded with zeros until it becomes a 32-bit sequence, and the Zero-fill Right Shift operator always returns a 32-bit <em>unsigned</em> integer. Home run.</p><p>Binary data and bitwise operation are a lot to wrap your head around, and may be seldom used directly, but there is a wellspring of capability simmering in the bellies of our favorite machines that can aid in building great software and hardware. I encourage you to dive into the binary realm, read up on <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators">bitwise operators</a>, and have some fun with zeros and ones!</p><p><a href="https://github.com/dangrammer">github.com/dangrammer</a><br><a href="https://www.linkedin.com/in/danieljromans/">linked.com/in/danieljromans</a><br><a href="http://danromans.com/">danromans.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edbe4daeac6c" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/working-with-bits-edbe4daeac6c">Working With Bits in JavaScript</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DRY Your Code With Modularization]]></title>
            <link>https://medium.com/@danromans/dry-your-code-with-modularization-303afcd1389b?source=rss-c8fbe0846cb0------2</link>
            <guid isPermaLink="false">https://medium.com/p/303afcd1389b</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[constant-values]]></category>
            <category><![CDATA[modularization]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[dont-repeat-yourself]]></category>
            <dc:creator><![CDATA[Dan Romans]]></dc:creator>
            <pubDate>Fri, 26 Jun 2020 19:40:07 GMT</pubDate>
            <atom:updated>2020-06-26T19:55:08.588Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Kyle MacLachlan as Paul Atreides in the film Dune(1984)." src="https://cdn-images-1.medium.com/max/1024/1*tDy2uRIFR2WZQV9NV2JjWQ.png" /><figcaption>“The spice must flow.”</figcaption></figure><p>There is a common software development principle known as <a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself">Don’t repeat yourself</a>, popularly referred to as the acronym DRY. The DRY principle states that every piece of knowledge must have a single, unambiguous, authoritative representation within a system and is aimed at reducing repetition of software patterns.</p><p>Drying your code is a wise and beneficial practice because it requires less lines of code to type and scan through, and will produce a code base which is more refined and legible, uses less memory, and is easily adapted or altered. There are many contributors to DRY code, one of which is <a href="https://en.wikipedia.org/wiki/Modularity">modularization</a>.</p><p>Modularization provides flexibility and variety in use by reducing the complexity of a system, dividing the system into modules, or components, with varying degrees of interdependence and independence, and concealing perceived complexity by way of abstraction.</p><p>A shining example of modularization is a little ol’ JavaScript framework called <a href="https://reactjs.org/">React</a>. In terms of design principles, <em>the</em> key feature of React is composition of components. In the broader sense, the component-based structure of a React application allows a whole team of people to easily work concurrently, but modularizing code in React can be useful for just you, too.</p><p>A simple, and helpful way to start DRYing a React project is to modularize constants. A <a href="https://en.wikipedia.org/wiki/Constant_(computer_programming)#:~:text=In%20computer%20programming%2C%20a%20constant,i.e.%2C%20the%20value%20is%20constant.&amp;text=This%20is%20contrasted%20with%20a,i.e.%2C%20the%20value%20is%20variable.">constant</a> is an immutable value, differing from a <a href="https://en.wikipedia.org/wiki/Variable_(computer_science)">variable</a>, which is an identifier of a mutable value. A constant can also be identified, but it itself is considered named, sometimes specified as a “named constant”. Ultimately, though, we’re talking about values.</p><p>A constant value will not change, making it a great candidate for abstraction when the value is lengthy, repeated often, or otherwise cumbersome to your codebase. Assuming you are familiar with React, let’s explore an example to demonstrate the benefit of modularization and DRY code. Also, bear in mind that the examples are from a React/Redux application and include actions.</p><p>Say we have a React application, and, to be expected, an associated <a href="https://en.wikipedia.org/wiki/Application_programming_interface">API</a>. The client side needs to fetch data from the server-side database. You have a directory full of action files for numerous models, each containing numerous actions to fetch particular data.</p><p>Each and every fetch is going to require a <a href="https://en.wikipedia.org/wiki/URL">URL</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers">HTTP headers</a>. Let’s take this action which validates a current user as an example:</p><pre>// ./src/actions/currentUserActions.js</pre><pre>export const validateUser = (returningUser, history) =&gt; {<br>  const {userName, password} = returningUser</pre><pre>return (dispatch) =&gt; {<br>    dispatch({type: &#39;LOADING&#39;})<br>    <strong><em>// URL</em></strong><br>    fetch(<strong>&#39;http://localhost:3000/api/v1</strong>/<strong>login&#39;</strong>, {<br>      method: &#39;POST&#39;,<br>      <strong><em>// HTTP headers</em></strong><em><br>      </em>headers:<strong> {                                   <br>        &#39;Content-Type&#39;: &#39;application/json&#39;,          <br>        &#39;Accept&#39;: &#39;application/json&#39;       <br>      }</strong>,<br>      body: JSON.stringify({<br>        username: userName,<br>        password,<br>      })<br>    })<br>    .then(response =&gt; response.json())<br>    .then(data =&gt; {<br>      if (data.errors) {<br>        dispatch({type: &#39;USER_ERRORS&#39;, errors: data.errors})<br>        setTimeout(() =&gt; <br>          dispatch({type: &#39;CLEAR_USER_ERRORS&#39;}), 3000<br>        )<br>      } else {<br>        localStorage.setItem(&#39;token&#39;, data.token)<br>        dispatch(loginUser(data.user.data))<br>        history.push(&#39;/listings&#39;)<br>      }<br>    })<br>  }<br>}</pre><p>Now, imagine you have to write up to 100 actions for your application—&#39;http://localhost:3000/api/v1/[login]&#39;<strong> </strong>and headers: {‘Content-Type’: ‘application/json’, ‘Accept’: ‘application/json’}<strong> </strong>will become redundant and unsightly. A solution is to replace these lines of code with constants.</p><h4>Create a Constants File:</h4><p>Thanks to the component-based architecture of React, we can abstract the URL and HTTP headers, represent them with constants, and store those constants in another location, another file, altogether.</p><p>It is very common, perhaps conventional, to name this file constants.js—big surprise. The constants.js file needs to be globally available to any other file which requires the use of its constants. While you can place it in the file structure wherever you see fit, it’s not a bad idea to place the constants.js file at the top of the file structure, <em>i.e.</em> root of the hierarchy. Regarding scripting code, the parent directory is traditionally the src file. Your file structure could look like this:</p><pre>react-app<br> |_node_modules<br> |_public<br> |_src<br> |  |_actions<br> |  |_components<br> |  |_containers<br> |  |_css<br> |  |_reducers<br> |  |_App.js<br> |  |_configureStore.js<br> |  <strong>|_constants.js</strong><br> |  |_index.js<br> |_package.json<br> |_package-lock.json<br> |_READme.md</pre><h4>Create Constants:</h4><p>You can utilize constants.js to store and organize <em>many</em> values to be used across your entire application, but, for this example, we’ll just create constants for our URL and HTTP Headers values.</p><pre>// ./src/constants.js</pre><pre>export const API_ROOT = &#39;http://localhost:3000/api/v1&#39;<br>export const HEADERS = {<br>  &#39;Content-Type&#39;: &#39;application/json&#39;,<br>  &#39;Accept&#39;: &#39;application/json&#39;<br>}</pre><p>We’ve created two named constants: API_ROOT and HEADERS. It is conventional to capitalize constant identifiers. In a language like Ruby, capitalizing an identifier declares a value as a constant. In JavaScript, constants must be declared with the const keyword, but maintaining the capitalization convention is appropriate here.</p><p>Each constant is assigned the value which it is meant to represent and is enabled to be exported to other files with the export keyword.</p><p>Before we demonstrate how to import these values into another file and plug them into an action, let’s make note of API_ROOT. While our root URL will remain constant, the application will most definitely require multiple URL paths, <em>e.g.</em> /login, /profile, et cetera. By creating a constant for the URL root alone, we will have flexibility with different paths when writing actions.</p><h4>Use Constants:</h4><p>As we can export our constants from constants.js, we can conveniently import those constants into whichever file we need them.</p><pre>// ./src/actions/currentUserActions.js</pre><pre><strong>import {API_ROOT, HEADERS} from &#39;../constants&#39;</strong></pre><pre>export const validateUser = (returningUser, history) =&gt; {<br>  const {userName, password} = returningUser</pre><pre>  return (dispatch) =&gt; {<br>    dispatch({type: &#39;LOADING&#39;})<br>    fetch(`<strong>${API_ROOT}</strong>/<strong>login`</strong>, {<br>      method: &#39;POST&#39;,<em><br>      </em>headers:<strong> HEADERS</strong>,<br>      body: JSON.stringify({<br>        username: userName,<br>        password,<br>      })<br>    })<br>    .then(response =&gt; response.json())<br>    .then(data =&gt; {<br>      if (data.errors) {<br>        dispatch({type: &#39;USER_ERRORS&#39;, errors: data.errors})<br>        setTimeout(() =&gt; <br>          dispatch({type: &#39;CLEAR_USER_ERRORS&#39;}), 3000<br>        )<br>      } else {<br>        localStorage.setItem(&#39;token&#39;, data.token)<br>        dispatch(loginUser(data.user.data))<br>        history.push(&#39;/listings&#39;)<br>      }<br>    })<br>  }<br>}</pre><p>At the top of the file, we use <a href="https://levelup.gitconnected.com/destructuring-assignment-in-react-it-is-your-friend-b36a330533dc">destructuring assignment</a> to import our needed constants from the constants.js file. API_ROOT is plugged in as the URL argument by using a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals">template literal</a> so that the path can be dynamically set. HEADERS is simply plugged in as the HTTP headers value. That’s all there is to it! This is a small example, but it is a powerful process when your code base grows in size or complexity.</p><h4>Bonus: <strong>Using Modularization To Handle Dynamic Values</strong>:</h4><p>There are limitless arguments about how and where to include this code, but I’m going to keep to constants.js for this example since the pertinent value in this example is still HTTP headers and the same fundamentals are applied.</p><p>Suppose your HTTP headers will be different depending on the action. For example, the previously exemplified action which validated a returning user only required ‘Content-Type’ and ‘Accept’ headers. This is a different action which loads a current user profile and requires a security token:</p><pre>// ./src/actions/currentUserActions.js</pre><pre>export const loadProfile = () =&gt; {<br>  const token = localStorage.token</pre><pre>  return (dispatch) =&gt; {<br>    dispatch({type: &#39;LOADING&#39;})<br>    if (token) {<em><br>      </em>fetch(<strong>&#39;http://localhost:3000/api/v1/profile&#39;</strong>, {         <br>        method: &#39;GET&#39;,<em><br>        </em>headers:<strong> {                                   <br>          &#39;Content-Type&#39;: &#39;application/json&#39;,          <br>          &#39;Accept&#39;: &#39;application/json&#39;, <br>          &#39;Authorization&#39;: `Bearer ${token}`        <br>        }</strong><br>      })<br>      .then(response =&gt; response.json())<br>      .then(data =&gt; {<br>        data.user ?<br>          dispatch(loginUser(data.user.data)) :     <br>            localStorage.removeItem(&#39;token&#39;)<br>      })<br>    }<br>  }<br>}</pre><p>One possibility is to include a different constant for this particular set of HTTP headers in constants.js, but that approach could quickly become not DRY depending on how many HTTP headers variations you need. Also, there is a complication with the token value being dynamic and bound to the scope of the action.</p><p>An alternative is to add logic to the action which will marry the HEADERS value from constants.js with the additional needed headers for the action. For example:</p><pre>// ./src/actions/currentUserActions.js</pre><pre><strong>import {API_ROOT, HEADERS} from &#39;../constants&#39;</strong></pre><pre>export const loadProfile = () =&gt; {<br>  const token = localStorage.token</pre><pre>return (dispatch) =&gt; {<br>    dispatch({type: &#39;LOADING&#39;})<br>    if (token) {<br>      <strong>const bearerToken =</strong> <strong>`Bearer ${token}`<br>      const headersObj = {...HEADERS, &#39;Authorization&#39;: bearerToken}</strong></pre><pre><em>      </em>fetch(`<strong>${API_ROOT}/profile`</strong>, {         <br>        method: &#39;GET&#39;,<em><br>        </em>headers:<strong> headersObj</strong><br>      })<br>      .then(response =&gt; response.json())<br>      .then(data =&gt; {<br>        data.user ?<br>          dispatch(loginUser(data.user.data)) :     <br>            localStorage.removeItem(&#39;token&#39;)<br>      })<br>    }<br>  }<br>}</pre><p>This is fine, but we can get DRYer, more abstract, and dynamically empower with modularization by creating a function in constants.js which accepts a token argument and optionally returns the base HTTP headers or amended HTTP headers. Again, I know this means exporting/importing a function, not just a constant value, but the principal of the demonstration is the benefit of modularization.</p><pre>// ./src/constants.js</pre><pre>export const API_ROOT = &#39;http://localhost:3000/api/v1&#39;</pre><pre>export const headers = (token) =&gt; {<br>  const headers = {<br>    &#39;Content-Type&#39;: &#39;application/json&#39;,<br>    &#39;Accept&#39;: &#39;application/json&#39;<br>  }<br>  if (token) headers[&#39;Authorization&#39;] = `Bearer ${token}`</pre><pre>  return headers<br>}</pre><p>Now, neatly tucked away in constants.js, we have a headers() function which creates and returns an HTTP headers object when invoked, and includes ‘Authorization’: `Bearer ${token}` when the token argument is passed in. The headers() function can be imported into the action file and used appropriately:</p><pre>// ./src/actions/currentUserActions.js</pre><pre><strong>import {API_ROOT, headers} from &#39;../constants&#39;</strong></pre><pre>export const loadProfile = () =&gt; {<br>  const token = localStorage.token</pre><pre>  return (dispatch) =&gt; {<br>    dispatch({type: &#39;LOADING&#39;})<br>    if (token) {<br>      fetch(`<strong>${API_ROOT}/profile`</strong>, {         <br>        method: &#39;GET&#39;,<br><em>// this action requires a token, so it is passed as an argument<br>        </em>headers:<strong> headers(token)<br></strong><em>// otherwise, simply invoke the headers function: </em><strong>headers()<br>      </strong>})<br>      .then(response =&gt; response.json())<br>      .then(data =&gt; {<br>        data.user ?<br>          dispatch(loginUser(data.user.data)) :     <br>            localStorage.removeItem(&#39;token&#39;)<br>      })<br>    }<br>  }<br>}</pre><p>I hope this was a helpful introduction to using modularization to DRY your code and using constants and a constants file in a React application. There are many layers left to peel off the potential abstractions possible within a codebase. This approach produces cleaner code that is more powerful, and convenient. I’ll sign off with one more nugget of information:</p><p>Suppose you are ready to deploy your application and need to change the base URL for your API. Instead of having to scan through numerous files and directly edit the URL many times, you can stop by constants.js, change one line of code, and call it a day. Thank goodness you didn’t repeat yourself and modularized your code base!</p><p><a href="https://github.com/dangrammer">github.com/dangrammer</a><br><a href="https://www.linkedin.com/in/danieljromans/">linked.com/in/danieljromans</a><br><a href="http://danromans.com/">danromans.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=303afcd1389b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stack Code Challenge Breakdown]]></title>
            <link>https://medium.com/weekly-webtips/stack-code-challenge-breakdown-50523275a6a2?source=rss-c8fbe0846cb0------2</link>
            <guid isPermaLink="false">https://medium.com/p/50523275a6a2</guid>
            <category><![CDATA[stack]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[hackerrank]]></category>
            <category><![CDATA[code-challenge]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Dan Romans]]></dc:creator>
            <pubDate>Mon, 22 Jun 2020 00:31:45 GMT</pubDate>
            <atom:updated>2020-06-24T12:34:37.267Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="The Riddler Traps Batman in a puzzling knot of wire." src="https://cdn-images-1.medium.com/max/1024/1*5QrjyxTxHRyV-fpWD_pQgw.jpeg" /><figcaption><em>“I’m clever enough at [algorithms] to baffle the [programmers]—yes, and Batman, too.”</em></figcaption></figure><p>Holy HackerRank, Batman! I recently completed a HackerRank code challenge called <a href="https://www.hackerrank.com/challenges/min-max-riddle/problem#:~:text=Given%20an%20integer%20array%20of,consider%20window%20sizes%20of%20through%20."><em>Min Max Riddle</em></a>. It requires the use of a data type/structure called a <a href="https://en.wikipedia.org/wiki/Stack_(abstract_data_type)">stack</a>, and the riddle doesn’t end there. I had to refer to many resources before writing a working solution, and I decided to write an article about this challenge because I wanted to thoroughly understand it and offer a JavaScript algorithm resource to the world wide web.</p><p>Before we tackle the code challenge, let’s review what a stack is. In computer science, a stack is an <a href="https://en.wikipedia.org/wiki/Abstract_data_type">abstract data type</a> that serves as a <a href="https://en.wikipedia.org/wiki/Collection_(abstract_data_type)">collection</a> of elements from which additions and subtractions can only be performed on the back end of the collection, or—speaking vertically—from the <em>top</em> of the stack. Although some programming languages provide more, when working with a stack, there are two principal operations:</p><ul><li><strong>Push: </strong>add an element to the top of the stack</li><li><strong>Pop: </strong>remove an element from the top of the stack</li></ul><p>Because of how elements are added or removed only from the end of the collection — or top of the stack, another terminology to represent the stack data structure is <strong>LIFO</strong> (last in, first out). Here’s a visual representation of pushing on to and popping off of a stack:</p><figure><img alt="A visual representation of the push and pop operations on a stack of numbers." src="https://cdn-images-1.medium.com/max/773/1*_Y2fMTuIBSS5kwq3V4htgQ.png" /><figcaption>The push and pop operations on a stack of numbers.</figcaption></figure><p>A stack is commonly represented by an Array, which has a .push() and .pop() method in JavaScript and many other programming languages. An example of using an Array as a stack in JavaScript could look like this:</p><pre>const stack = [1, 2, 3]</pre><pre>stack.push(4)<br>// [1, 2, 3, 4]</pre><pre>stack.push(5)<br>// [1, 2, 3, 4, 5]</pre><pre>stack.pop()<br>// [1, 2, 3, 4]</pre><pre>stack.pop()<br>// [1, 2, 3]</pre><h3>Min Max Riddle:</h3><h4>Problem Statement:</h4><p>Given an Array of positive integers, use a series of sliding windows to collect the minimum value of each window, then record the maximum value of the collected minima for that window size. The window size varies from 1 to n wherein n is equal to the size, <em>i.e.</em> length, of the input Array. For example:</p><pre>const arr = [3, 5, 4, 7, 6, 2] </pre><pre>// consider window sizes 1 to n = arr.length = 6<br>// wSize1 =&gt; [3] [5] [4] [7] [6] [2]<br>// wSize2 =&gt; [3, 5] [5, 4] [4, 7] [7, 6] [6, 2]<br>// ...<br>// wSize6 =&gt; [3, 5, 4, 7, 6, 2]</pre><pre>____________________________________________________________________<br>|  <em>window</em>  |      *    <em>collected minima</em>       *      |  <em>window</em> | * |<br>|   <em>size</em>   |  <em>w1</em>  |  <em>w2</em>  |  <em>w3</em>  |  <em>w4</em>  |  <em>w5</em>  |  <em>w6</em>  | <em>maximum </em>| * |<br>|––––––––––|–––––––––––––––––––––––––––––––––––––––––|–––––––––|–––|<br>|     <em>1</em>    |   3  |   5  |   4  |   <strong>7</strong>  |   6  |   2  |    <strong>7 </strong>   | c |<br>|––––––––––|––––––|––––––|––––––|––––––|––––––|––––––|–––––––––| o |<br>|     <em>2</em>    |   3  |   4  |   4  |   <strong>6</strong>  |   2  |      |    <strong>6 </strong>   | l |<br>|––––––––––|––––––|––––––|––––––|––––––|––––––|––––––|–––––––––| l |<br>|     <em>3</em>    |   3  |   <strong>4</strong>  |   <strong>4</strong>  |   2  |      |      |    <strong>4</strong>    | . |<br>|––––––––––|––––––|––––––|––––––|––––––|––––––|––––––|–––––––––| m |<br>|     <em>4</em>    |   3  |   <strong>4</strong>  |   2  |      |      |      |    <strong>4</strong>    | a |<br>|––––––––––|––––––|––––––|––––––|––––––|––––––|––––––|–––––––––| x |<br>|     <em>5</em>    |   <strong>3</strong>  |   2  |      |      |      |      |    <strong>3</strong>    | i |<br>|––––––––––|––––––|––––––|––––––|––––––|––––––|––––––|–––––––––| m |<br>|     <em>6</em>    |   <strong>2</strong>  |      |      |      |      |      |    <strong>2</strong>    | a |<br>––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––</pre><pre>// maxima of minima = [7, 6, 4, 4, 3, 2]</pre><h4>Function Description:</h4><p>The riddle() function must return an Array of integers representing the maximum minimum value for each window of size 1 to n.</p><p><strong>Input parameter:</strong></p><ul><li>arr: an Array of integers</li></ul><h4>Solution:</h4><p>The algorithm to solve this challenge has a lot going on, but don’t worry, I’m just as confused as you might be. The gist is this:</p><ol><li>Use a for loop, while loop, and stack Array to build a hashmap of window maxima.</li><li>Use a for loop to build a hashmap of inverted window maxima.</li><li>Use a for loop, if else statement, and inverted window maxima hashmap to collect window maxima in an Array.</li><li>Return a reversed copy of the maxima Array.</li></ol><p><strong>Step 0: Outline Function</strong></p><pre><strong>function riddle(arr) {<br>  const wMaxes = {}<br>  const wInver = {}<br>  const stack = []<br>  const maxima = []<br>  <br>  const result</strong></pre><pre><strong>  return result<br>}</strong></pre><p>We start by outlining the function riddle() with its included parameter arr. We know from the outline that we’ll need two Object to use as hashmaps: wMaxes for the first hashmap of window maxima, and wInver for the second hashmap of inverted window maxima. We know we need two Array: stack to use as a stack, and maxima to contain values from the inverted window maxima hashmap. We know we need to create a reversed copy of the maxima Array values, so we’ll declare the reserved variable result, ultimately using it as the return value.</p><p><strong>Step 1: Build Window Maxima Hashmap</strong></p><pre>function riddle(arr) {<br>  const wMaxes = {}<br>  const wInver = {}<br>  const stack = []<br>  const maxima = []</pre><pre>  <strong>arr.push(0)  </strong></pre><pre><strong>  for (let i = 0; i &lt; arr.length; i++) {<br>    let idx = i</strong></pre><pre><strong>    while (stack.length &amp;&amp; stack[stack.length - 1][0] &gt;= arr[i]) {<br>      let [val, prevIdx] = stack.pop()</strong></pre><pre><strong>      wMaxes[arr[i]] = Math.max(<br>        wMaxes[arr[i]] || 0, i - prevIdx + 1<br>      )<br>      wMaxes[val] = Math.max(wMaxes[val] || 0, i - prevIdx)<br>      idx = prevIdx<br>    }<br>    stack.push([arr[i], idx])<br>  }</strong></pre><pre><strong>  delete wMaxes[&#39;0&#39;]</strong></pre><pre>  const result</pre><pre>  return result<br>}</pre><p>The first thing to notice is the first line of active code: arr.push(0). By adding a 0 to the end of the input array we can efficiently create an extra iteration of the for loop and force the while loop to evaluate any remaining content of the stack. We’ll come back to this.</p><p>The for loop evaluates each element of arr. The variable idx is assigned the index of the current element. If stack is empty, as it will be on the first iteration, or the value on the top of stack is <em>less</em> than the current element, the while loop is skipped and a sub-Array containing the current element and its index is pushed on to stack. Note that idx is mutable.</p><p>If stack is <em>not</em> empty and the value on the top of stack is <em>greater</em> than or <em>equal</em> to the current element, the while loop is triggered, and this is where wMaxes is built.</p><p>stack.pop() removes the sub-Array from the top of stack. <a href="https://levelup.gitconnected.com/destructuring-assignment-in-react-it-is-your-friend-b36a330533dc">Destructuring assignment</a> is used to assign the element to the variable val and the index to the variable prevIdx.</p><p>Next, two bracket notation operations are performed to add entries to wMaxes. In the first, an entry is made with a key equal to the current element (wMaxes[arr[i]]) and a value equal to the greater of: the current value of wMaxes[arr[i]], if it exists, <em>or</em> the value of the current index minus the previous index plus one (i — prevIdx + 1). In the second, an entry is made with a key equal to the last element on top of stack, or previous qualifying element (wMaxes[val]), and a value equal to the greater of: the current value of wMaxes[val], if it exists, <em>or</em> the value of the current index minus the previous index (i — prevIdx).</p><p>Note that the Logical OR operator (||) within each Math.Max() function sets the first argument to 0 if an entry with the specified key does not yet exist in wMaxes. This is a shorthand way to create a default entry with the second argument, the calculated index, as the value if the key does not yet exist in wMaxes.</p><p>The last operation within the while loop is to set the variable idx, in the for loop scope, to the index from the previous element popped off the top of stack. Note that the calculation for wMaxes[arr[i]] considers i — prevIdx <strong>+ 1 </strong>to accommodate the difference of iteration beginning at 0 and window size beginning at 1.</p><p>So, what on earth is going on here? In short, we’re creating a hashmap—wMaxes—which stores key value pairs as ‘arr element&#39;: ‘window size&#39; wherein ‘arr element’ is an element from the arr which represents the maximum value of the collected minima of ‘window size’. Consider this example:</p><pre>const arr = [3, 5, 4, 7, 6, 2]</pre><pre>wMaxes =&gt; {&#39;0&#39;: 7, &#39;2&#39;: 6, &#39;<strong>3</strong>&#39;: <strong>5</strong>, &#39;4&#39;: 4, &#39;5&#39;: 1, <strong>&#39;6&#39;: 2</strong>, &#39;7&#39;: 1}</pre><pre>____________________________________________________________________<br>|  <em>window</em>  |      *    <em>collected minima</em>       *      |  <em>window</em> | * |<br>|   <em>size</em>   |  <em>w1</em>  |  <em>w2</em>  |  <em>w3</em>  |  <em>w4</em>  |  <em>w5</em>  |  <em>w6</em>  | <em>maximum </em>| * |<br>|––––––––––|–––––––––––––––––––––––––––––––––––––––––|–––––––––|–––|<br>|     <strong><em>2</em></strong>    |   3  |   4  |   4  |   6  |   2  |      |    <strong>6 </strong>   | m |<br>|––––––––––|––––––|––––––|––––––|––––––|––––––|––––––|–––––––––| a |<br>|     <strong><em>5</em></strong>    |   3  |   2  |      |      |      |      |    <strong>3</strong>    | x |<br>––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––</pre><p>How the stack data structure plays a key role here is that it stores, in linear order, data that has come previous to the currently evaluated data. The end of this article will include a nifty process log to demonstrate how the data is being manipulated throughout the function, but consider this process log from the third iteration of the for loop, evaluating arr[2] // 4:</p><pre>const arr = [3, 5, 4, 7, 6, 2]</pre><pre>loop #3<br>  current element: 4<br>  stack:  [[3, 0], [5, 1]]<br>    while loop<br>      element on top of stack(5) is &gt;= current element(4)<br>      stack.pop(): [5, 1]<br>      load window maxes map<br>        build or update key:value with curEl(4) as key<br>        set value to max of existing key(set to 0) <br>          or index - last index + 1: 2<br>        wMaxes: {&#39;4&#39;: 2}</pre><pre>        build or update key:value with lastEl(5) as key<br>        set value to max of existing key(set to 0) <br>          or index - last index: 1<br>        wMaxes: {&#39;4&#39;: 2, &#39;5&#39;: 1}</pre><pre>        change curIdx from 2 to 1</pre><pre>  push [4, 1] (curEl, curIdx) on top of stack<br>  stack: [[ 3, 0 ], [ 4, 1 ]]</pre><p>This shows us that, if each element in arr is <em>greater</em> than the last, it is added to the stack for future calculations, and once we reach an element in arr that is <em>less</em> than the last, we can start evaluating some results with the data we have so far; expanding the window, so to speak, back to the previous element. The act of expanding the window back is also controlled by setting idx to the prevIdx from the last sub-Array at the top of stack, assigning that index to the next sub-Array to be pushed on to stack, preparing the next iteration of the for loop.</p><p>In the process log of loop #3, we can evaluate the current element: 4, and add it to wMaxes with window size 2 since, so far:</p><pre>minimum of [3, 5] = 3<br>minimum of [5, 4] = 4<br>maximum of  3, 4  = 4<br>wMaxes[&#39;4&#39;] = 2 // {&#39;4&#39;: 2}</pre><p>Then, we can peek back at the previous element: 5, via stack, and add it to wMaxes with window size 1 since, so far:</p><pre>minimum of [3] = 3<br>minimum of [5] = 5<br>minimum of [4] = 4<br>maximum of  3, 5, 4 = 5<br>wMaxes[&#39;5&#39;] = 1 // {&#39;5&#39;: 1}</pre><p>The 0 that was added to arr at the top of the riddle() function will force the while loop to process any remaining sub-Array in stack upon the last iteration of the for loop, and appropriately adjust the maximum window sizes recorded in the wMaxes hashmap.</p><p>The last process for this step is optional, but I’ve included it to remove extraneous code. After wMaxes is built, it will include a key of ‘0’ due to the final iteration of the for loop. If left, this key will just be ignored in next steps, but we can clean up the code by deleting the key value pair from wMaxes with delete wMaxes[‘0’].</p><p><strong>Step 2: Build Inverted Window Maxima Hashmap</strong></p><pre>function riddle(arr) {<br>  const wMaxes = {}<br>  const wInver = {}<br>  const stack = []<br>  const maxima = []</pre><pre><strong>  </strong>arr.push(0)</pre><pre>  for (let i = 0; i &lt; arr.length; i++) {<br>    let idx = i</pre><pre>    while (stack.length &amp;&amp; stack[stack.length - 1][0] &gt;= arr[i]) {<br>      let [val, prevIdx] = stack.pop()</pre><pre>      wMaxes[arr[i]] = Math.max(<br>        wMaxes[arr[i]] || 0, i - prevIdx + 1<br>      )<br>      wMaxes[val] = Math.max(wMaxes[val] || 0, i - prevIdx)<br>      idx = prevIdx<br>    }<br>    stack.push([arr[i], idx])<br>  }</pre><pre>  delete wMaxes[&#39;0&#39;]</pre><pre>  <strong>for (let k in wMaxes) {<br>    wInver[wMaxes[k]] = Math.max(wInver[wMaxes[k]] || 0, k)<br>  }</strong></pre><pre>  const result</pre><pre>  return result<br>}</pre><p>To more easily build our forthcoming maxima Array, we can invert the key value pairs of wMaxes and assign them to the wInver hashmap. This step will also handle needed amendments to the window size maxima. Consider this:</p><pre>const arr = [3, 5, 4, 7, 6, 2]</pre><pre>wMaxes = {&#39;2&#39;: 6, &#39;3&#39;: 5, &#39;4&#39;: 4, &#39;5&#39;: 1, &#39;6&#39;: 2, &#39;7&#39;: 1}</pre><p>Because of the order of operations conducted in building wMaxes, multiple values can be assigned to the same window size. Illustrated above: ‘5’ and ‘7’ are both assigned as maximums of window size 1. There can be only one maximum, so we favor the <em>greater</em> of the two values: ‘7’.</p><p>Quite simply, the for loop iterates through the keys (k) of wMaxes and uses bracket notation to add entries to wInver with a key equal to the value of wMaxes[k], and a value equal to the greater of: the current value of wInver[wMaxes[k]], if it exists, <em>or</em> the value of the current key: k. Our example will provide this transformation:</p><pre>const arr = [3, 5, 4, 7, 6, 2]</pre><pre>wMaxes = {&#39;2&#39;: 6, &#39;3&#39;: 5, &#39;4&#39;: 4, &#39;5&#39;: 1, &#39;6&#39;: 2, &#39;7&#39;: 1}</pre><pre>wInver = {&#39;1&#39;: 7, &#39;2&#39;: 6, &#39;4&#39;: 4, &#39;5&#39;: 3, &#39;6&#39;: 2}</pre><p><strong>Step 3: Build Maxima Array</strong></p><pre>function riddle(arr) {<br>  const wMaxes = {}<br>  const wInver = {}<br>  const stack = []<br>  const maxima = []</pre><pre>  arr.push(0)</pre><pre>  for (let i = 0; i &lt; arr.length; i++) {<br>    let idx = i</pre><pre>    while (stack.length &amp;&amp; stack[stack.length - 1][0] &gt;= arr[i]) {<br>      let [val, prevIdx] = stack.pop()</pre><pre>      wMaxes[arr[i]] = Math.max(<br>        wMaxes[arr[i]] || 0, i - prevIdx + 1<br>      )<br>      wMaxes[val] = Math.max(wMaxes[val] || 0, i - prevIdx)<br>      idx = prevIdx<br>    }<br>    stack.push([arr[i], idx])<br>  }</pre><pre>  delete wMaxes[&#39;0&#39;]</pre><pre><strong>  </strong>for (let k in wMaxes) {<br>    wInver[wMaxes[k]] = Math.max(wInver[wMaxes[k]] || 0, k)<br>  }</pre><pre>  <strong>maxima.push(wInver[arr.length - 1])</strong></pre><pre><strong>  for (let i = arr.length - 2; i &gt; 0; i--) {<br>    if (!wInver[i] || wInver[i] &lt; maxima[maxima.length - 1]) {<br>      maxima.push(maxima[maxima.length - 1])<br>    } else {<br>      maxima.push(wInver[i])<br>    }<br>  }<br> <br>  </strong>const result</pre><pre>  return result<br>}</pre><p>This step begins by pushing a value into the maxima Array: the window maxima which correlates to the largest window size, or n: the size/length of arr. Bracket notation is used to access the window maximum value from wInver with a key of arr.length — 1, which considers the extra element—0—which was previously added to arr.</p><p>Next, the for loop traverses arr in reverse, using a decrementing index based on arr.length, which evaluates the maximum for window sizes n to 1 by referencing the wInver hashmap. Since we preload the maxima Array with wInver[arr.length — 1], the for loop begins with a counter set to arr.length — 2.</p><p>Within the for loop, an if else statement evaluates each value of wInver accessed by the key of the current index (i). If wInver does not include the key, or the accessed value is <em>less</em> than the last element of maxima, the last element of maxima is added to maxima—repeated. Otherwise (but, principally, if the accessed value is <em>greater</em> than the last element of maxima), the accessed value is added, <em>or *pushed on</em>, to maxima. Note that maxima is being used as a stack, only referencing the end, or top, of the stack, and only pushing elements on top of the stack.</p><p>This step seems a bit mysterious, but its purpose and benefit is that it can properly use the values we collected in wInver, properly sequence the window maxima to correlate with window size, and easily produce correct values when repeated window minima are encountered. The minutia can be explored in the process log, but consider this transformation and recall the chart from the problem statement:</p><pre>const arr = [3, 5, 4, 7, 6, 2]</pre><pre>wMaxes = {&#39;2&#39;: 6, &#39;3&#39;: 5, &#39;4&#39;: 4, &#39;5&#39;: 1, &#39;6&#39;: 2, &#39;7&#39;: 1}</pre><pre>wInver = {&#39;1&#39;: 7, &#39;2&#39;: 6, &#39;4&#39;: 4, &#39;5&#39;: 3, &#39;6&#39;: 2}</pre><pre>maxima = [2, 3, 4, 4, 6, 7]</pre><p><strong>Step 4: Reverse Maxima Array and Return</strong></p><pre><strong>// complete solution</strong></pre><pre>function riddle(arr) {<br>  const wMaxes = {}<br>  const wInver = {}<br>  const stack = []<br>  const maxima = []</pre><pre>  arr.push(0)</pre><pre>  for (let i = 0; i &lt; arr.length; i++) {<br>    let idx = i</pre><pre>    while (stack.length &amp;&amp; stack[stack.length - 1][0] &gt;= arr[i]) {<br>      let [val, prevIdx] = stack.pop()</pre><pre>      wMaxes[arr[i]] = Math.max(<br>        wMaxes[arr[i]] || 0, i - prevIdx + 1<br>      )<br>      wMaxes[val] = Math.max(wMaxes[val] || 0, i - prevIdx)<br>      idx = prevIdx<br>    }<br>    stack.push([arr[i], idx])<br>  }</pre><pre>  delete wMaxes[&#39;0&#39;]</pre><pre>  for (let k in wMaxes) {<br>    wInver[wMaxes[k]] = Math.max(wInver[wMaxes[k]] || 0, k)<br>  }</pre><pre><strong>  </strong>maxima.push(wInver[arr.length - 1])</pre><pre>  for (let i = arr.length - 2; i &gt; 0; i--) {<br>    if (!wInver[i] || wInver[i] &lt; maxima[maxima.length - 1]) {<br>      maxima.push(maxima[maxima.length - 1])<br>    } else {<br>      maxima.push(wInver[i])<br>    }<br>  }<strong><br> <br>  </strong>const result <strong>= maxima.reverse()</strong></pre><pre>  return result<br>}</pre><p>The one last thing to address is the order of the maxima Array. While all of our work so far required a certain order, the resulting maxima Array is in reverse order from what the function description dictates. Recall that while building the maxima Array, arr was traversed from the end (largest window size) to beginning (smallest window size). However, the function description explains that the riddle() function must return an Array of integers representing the maximum minimum value for each window of size <strong>1 to </strong><strong>n</strong>, or beginning to end.</p><p>This operation is easily achievable by many means, <em>e.g.</em> a for loop or a convenient built-in like .reverse(), which the test cases on HackerRank did not mind the use of. To properly compile our result, we assign maxima.reverse() to a reserved variable, in our case result, and then return it.</p><pre>const arr = [3, 5, 4, 7, 6, 2]</pre><pre>riddle(arr)</pre><pre>// [7, 6, 4, 4, 3, 2]</pre><p>I’m not the most experienced coder or mathematician, but I feel even Batman would be hard pressed to out-do the Riddler with a puzzle like <em>Min Max Riddle</em>! As noted previously, I’ve included a nifty process log of the riddle() function for you to more deeply analyze the code mechanics. There may be a better solution to this challenge, but, now, there’s a decent, correct, thoroughly analyzed, JavaScript solution for others to reference. Nanana 🦇!</p><p><a href="https://github.com/dangrammer">github.com/dangrammer</a><br><a href="https://www.linkedin.com/in/danieljromans/">linked.com/in/danieljromans</a><br><a href="http://danromans.com/">danromans.com</a></p><h4>Process Log:</h4><pre>const arr = [3, 5, 4, 7, 6, 2]</pre><pre>riddle(arr)</pre><pre>// LOG /////////////////////////////////////////////////////////////</pre><pre><em>arr input</em><br>[ 3, 5, 4, 7, 6, 2 ]</pre><pre><em>add 0 to end of arr</em><br>[ 3, 5, 4, 7, 6, 2, 0 ]<br>______________________________________________________________<br><em>first for loop: build window maxes map</em></pre><pre>  <strong>loop #1</strong><br>    current element, index: 3, 0<br>    stack:  []<br>    stack empty<br>    push [3, 0] on top of stack<br>    stack: [ [ 3, 0 ] ]</pre><pre>  <strong>loop #2</strong><br>    current element, index: 5, 1<br>    stack:  [ [ 3, 0 ] ]<br>    element on top of stack(3) is &lt; current element(5)<br>    push [5, 1] on top of stack<br>    stack: [ [ 3, 0 ], [ 5, 1 ] ]</pre><pre>  <strong>loop #3</strong><br>    current element, index: 4, 2<br>    stack:  [ [ 3, 0 ], [ 5, 1 ] ]</pre><pre>      <em>while loop</em><br>        element on top of stack (5) is &gt;= current element: 4<br>        stack.pop(): [ 5, 1 ]<br>          load window maxes map<br>            build or update key:value with curEl(4) as key<br>            set value to max of [no key](0) <br>            or [index - last index + 1](2)<br>              wMaxes: { &#39;4&#39;: 2 }<br>            build or update key:value with prevEl(5) as key<br>            set value to max of [no key](0) <br>            or [index - last index](1)<br>              wMaxes: { &#39;4&#39;: 2, &#39;5&#39;: 1 }<br>        change curIdx from 2 to 1</pre><pre>    push [4, 1] on top of stack<br>    stack: [ [ 3, 0 ], [ 4, 1 ] ]</pre><pre><strong>  loop #4</strong><br>    current element, index: 7, 3<br>    stack:  [ [ 3, 0 ], [ 4, 1 ] ]<br>    element on top of stack(4) is &lt; current element(7)<br>    push [7, 3] on top of stack<br>    stack: [ [ 3, 0 ], [ 4, 1 ], [ 7, 3 ] ]</pre><pre><strong>  loop #5</strong><br>    current element, index: 6, 4<br>    stack:  [ [ 3, 0 ], [ 4, 1 ], [ 7, 3 ] ]</pre><pre>      <em>while loop</em><br>        element on top of stack (7) is &gt;= current element: 6<br>        stack.pop(): [ 7, 3 ]<br>          load window maxes map<br>            build or update key:value with curEl(6) as key<br>            set value to max of [no key](0) <br>            or [index - last index + 1](2)<br>              wMaxes: { &#39;4&#39;: 2, &#39;5&#39;: 1, &#39;6&#39;: 2 }<br>            build or update key:value with prevEl(7) as key<br>            set value to max of [no key](0) <br>            or [index - last index](1)<br>              wMaxes: { &#39;4&#39;: 2, &#39;5&#39;: 1, &#39;6&#39;: 2, &#39;7&#39;: 1 }<br>        change curIdx from 4 to 3</pre><pre>    push [6, 3] on top of stack<br>    stack: [ [ 3, 0 ], [ 4, 1 ], [ 6, 3 ] ]</pre><pre><strong>  loop #6</strong><br>    current element, index: 2, 5<br>    stack:  [ [ 3, 0 ], [ 4, 1 ], [ 6, 3 ] ]</pre><pre>      <em>while loop</em><br>        element on top of stack (6) is &gt;= current element: 2<br>        stack.pop(): [ 6, 3 ]<br>          load window maxes map<br>            build or update key:value with curEl(2) as key<br>            set value to max of [no key](0) <br>            or [index - last index + 1](3)<br>              wMaxes: { &#39;2&#39;: 3, &#39;4&#39;: 2, &#39;5&#39;: 1, &#39;6&#39;: 2, &#39;7&#39;: 1 }<br>            build or update key:value with prevEl(6) as key<br>            set value to max of existing key(2) <br>            or [index - last index](2)<br>              wMaxes: { &#39;2&#39;: 3, &#39;4&#39;: 2, &#39;5&#39;: 1, &#39;6&#39;: 2, &#39;7&#39;: 1 }<br>        change curIdx from 5 to 3</pre><pre>      <em>while loop</em><br>        element on top of stack (4) is &gt;= current element: 2<br>        stack.pop(): [ 4, 1 ]<br>          load window maxes map<br>            build or update key:value with curEl(2) as key<br>            set value to max of existing key(3) <br>            or [index - last index + 1](5)<br>              wMaxes: { &#39;2&#39;: 5, &#39;4&#39;: 2, &#39;5&#39;: 1, &#39;6&#39;: 2, &#39;7&#39;: 1 }<br>            build or update key:value with prevEl(4) as key<br>            set value to max of existing key(2) <br>            or [index - last index](4)<br>              wMaxes: { &#39;2&#39;: 5, &#39;4&#39;: 4, &#39;5&#39;: 1, &#39;6&#39;: 2, &#39;7&#39;: 1 }<br>        change curIdx from 3 to 1</pre><pre>      <em>while loop</em><br>        element on top of stack (3) is &gt;= current element: 2<br>        stack.pop(): [ 3, 0 ]<br>          load window maxes map<br>            build or update key:value with curEl(2) as key<br>            set value to max of existing key(5) <br>            or [index - last index + 1](6)<br>          wMaxes: { &#39;2&#39;: 6, &#39;4&#39;: 4, &#39;5&#39;: 1, &#39;6&#39;: 2, &#39;7&#39;: 1 }<br>            build or update key:value with prevEl(3) as key<br>            set value to max of [no key](0) <br>            or [index - last index](5)<br>          wMaxes: { &#39;2&#39;: 6, &#39;3&#39;: 5, &#39;4&#39;: 4, &#39;5&#39;: 1, &#39;6&#39;: 2, &#39;7&#39;: 1 }<br>        change curIdx from 1 to 0</pre><pre>    push [2, 0] on top of stack<br>    stack: [ [ 2, 0 ] ]</pre><pre><strong>  loop #7</strong><br>    current element, index: 0, 6<br>    stack:  [ [ 2, 0 ] ]</pre><pre>      <em>while loop</em><br>        element on top of stack (2) is &gt;= current element: 0<br>        stack.pop(): [ 2, 0 ]<br>          load window maxes map<br>            build or update key:value with curEl(0) as key<br>            set value to max of [no key](0) <br>            or [index - last index + 1](7)<br>  wMaxes: { &#39;0&#39;: 7, &#39;2&#39;: 6, &#39;3&#39;: 5, &#39;4&#39;: 4, &#39;5&#39;: 1, &#39;6&#39;: 2, &#39;7&#39;: 1 }<br>            build or update key:value with prevEl(2) as key<br>            set value to max of existing key(6) <br>            or [index - last index](6)<br>  wMaxes: { &#39;0&#39;: 7, &#39;2&#39;: 6, &#39;3&#39;: 5, &#39;4&#39;: 4, &#39;5&#39;: 1, &#39;6&#39;: 2, &#39;7&#39;: 1 }<br>        change curIdx from 6 to 0</pre><pre>    push [0, 0] on top of stack<br>    stack: [ [ 0, 0 ] ]</pre><pre>______________________________________________________________<br><em>window maxes map (wMaxes)</em><br>{ &#39;0&#39;: 7, &#39;2&#39;: 6, &#39;3&#39;: 5, &#39;4&#39;: 4, &#39;5&#39;: 1, &#39;6&#39;: 2, &#39;7&#39;: 1 }</pre><pre><em>remove 0 key from wMaxes</em><br>{ &#39;2&#39;: 6, &#39;3&#39;: 5, &#39;4&#39;: 4, &#39;5&#39;: 1, &#39;6&#39;: 2, &#39;7&#39;: 1 }</pre><pre>______________________________________________________________<br><em>second for loop: create inverted window maxes map</em></pre><pre><em>  </em><strong>loop #1<br>    </strong>current key: 2<br>    add key(wMaxes[2]) to wInver: 6<br>    set value for wInver key(6) to the greater of:<br>      [wInver[wMaxes[2]] || 0](0) &amp; current key(2)<br>    { &#39;6&#39;: 2 }</pre><pre><strong>  loop #2<br>    </strong>current key: 3<br>    add key(wMaxes[3]) to wInver: 5<br>    set value for wInver key(5) to the greater of:<br>      [wInver[wMaxes[3]] || 0](0) &amp; current key(3)<br>    { &#39;5&#39;: 3, &#39;6&#39;: 2 }</pre><pre><strong>  loop #3<br>    </strong>current key: 4<br>    add key(wMaxes[4]) to wInver: 4<br>    set value for wInver key(4) to the greater of:<br>      [wInver[wMaxes[4]] || 0](0) &amp; current key(4)<br>    { &#39;4&#39;: 4, &#39;5&#39;: 3, &#39;6&#39;: 2 }</pre><pre><strong>  loop #4<br>    </strong>current key: 5<br>    add key(wMaxes[5]) to wInver: 1<br>    set value for wInver key(1) to the greater of:<br>      [wInver[wMaxes[5]] || 0](0) &amp; current key(5)<br>    { &#39;1&#39;: 5, &#39;4&#39;: 4, &#39;5&#39;: 3, &#39;6&#39;: 2 }</pre><pre>  <strong>loop #5<br>    </strong>current key: 6<br>    add key(wMaxes[6]) to wInver: 2<br>    set value for wInver key(2) to the greater of:<br>      [wInver[wMaxes[6]] || 0](0) &amp; current key(6)<br>    { &#39;1&#39;: 5, &#39;2&#39;: 6, &#39;4&#39;: 4, &#39;5&#39;: 3, &#39;6&#39;: 2 }</pre><pre><strong>  loop #6<br>    </strong>current key: 7<br>    add key(wMaxes[7]) to wInver: 1<br>    set value for wInver key(1) to the greater of:<br>      [wInver[wMaxes[7]] || 0](5) &amp; current key(7)<br>    { &#39;1&#39;: 7, &#39;2&#39;: 6, &#39;4&#39;: 4, &#39;5&#39;: 3, &#39;6&#39;: 2 }</pre><pre>______________________________________________________________<br><em>inverted window maxes map (wInver)</em><br>{ &#39;1&#39;: 7, &#39;2&#39;: 6, &#39;4&#39;: 4, &#39;5&#39;: 3, &#39;6&#39;: 2 }</pre><pre><em>load maxima arr with value from wInver[6(last index of input arr)]</em><br>[ 2 ]</pre><pre>______________________________________________________________<br><em>third for loop: create maxima arr</em></pre><pre><em>  </em><strong>loop #1 </strong> <br>    the value of wInver[5](3) is &gt;= the last element of maxima(2) <br>    so add new value<br>    [ 2, 3 ]</pre><pre><strong>  loop #2<br>    </strong>the value of wInver[4](4) is &gt;= the last element of maxima(3) <br>    so add new value<br>    [ 2, 3, 4 ]</pre><pre>  <strong>loop #3<br>    </strong>wInver has no key of 3 so repeat last element<br>    [ 2, 3, 4, 4 ]</pre><pre>  <strong>loop #4<br>    </strong>the value of wInver[2](6) is &gt;= the last element of maxima(4) <br>    so add new value<br>    [ 2, 3, 4, 4, 6 ]</pre><pre> <strong> loop #5<br>    </strong>the value of wInver[1](7) is &gt;= the last element of maxima(6) <br>    so add new value<br>    [ 2, 3, 4, 4, 6, 7 ]</pre><pre>______________________________________________________________<br><em>reverse the maxima arr and assign it to result arr<br>print result arr</em><br>[ 7, 6, 4, 4, 3, 2 ]</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50523275a6a2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/weekly-webtips/stack-code-challenge-breakdown-50523275a6a2">Stack Code Challenge Breakdown</a> was originally published in <a href="https://medium.com/weekly-webtips">Webtips</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Be Ready For Cognitive Aptitude Testing]]></title>
            <link>https://medium.com/@danromans/be-ready-for-cognitive-aptitude-testing-beb4fff17465?source=rss-c8fbe0846cb0------2</link>
            <guid isPermaLink="false">https://medium.com/p/beb4fff17465</guid>
            <category><![CDATA[logic]]></category>
            <category><![CDATA[verbal-reasoning]]></category>
            <category><![CDATA[cognitive-test]]></category>
            <category><![CDATA[cognitive-psychology]]></category>
            <category><![CDATA[spatial-thinking]]></category>
            <dc:creator><![CDATA[Dan Romans]]></dc:creator>
            <pubDate>Fri, 12 Jun 2020 22:35:05 GMT</pubDate>
            <atom:updated>2020-06-12T22:35:05.239Z</atom:updated>
            <content:encoded><![CDATA[<h3>Job Seekers: Be Ready For Cognitive Aptitude Testing</h3><figure><img alt="A scene from Blade Runner(1982) wherein Leon Kowalski is being subject to the Voight-Kampff test by blade runner Dave Holden." src="https://cdn-images-1.medium.com/max/1024/1*V3y6pRBRR0ZUMl0ejuFVmA.png" /><figcaption>“It’s your birthday. Someone gives you a calfskin wallet.”</figcaption></figure><p>You may go through your entire life and never be faced with a Cognitive Aptitude Test, but, if you were, it would be better to be prepared. Cognitive testing can be performed on any thinker, including animals. As a child, a similar test called a <a href="https://en.wikipedia.org/wiki/Cognitive_Abilities_Test">Cognitive Abilities Test</a> can be used to determine reasoning and problem solving skills. Children may be tested to aid in appropriately assigning their mode of education.</p><p>As an adult, you might be tested as a pre-employment screening. Companies from virtually any industry can use cognitive aptitude testing as an objective, standardized way to evaluate the potential of a candidate—from intern to CEO—to perform in a workspace. Research suggests that the results of cognitive aptitude testing are more predictive than interviews, previous job experience, and education level.</p><p>I recently applied for a role at a technology company and was assigned a pre-employment test to be reviewed before I could be considered for the interview process. Truthfully, I was unaware of this practice, had to quickly prepare, and wished I could have felt a bit more confident while testing. Hopefully, this article will provide a heads up for others seeking a job or career position!</p><p><em>*Note: For the remainder of this article, I will use the acronym CAT to refer to “Cognitive Aptitude Testing” and “Cognitive Aptitude Test”.</em></p><h4>How Cognitive Aptitude Testing is conducted:</h4><p>The main purpose of CAT is to measure the candidate’s ability to problem-solve, digest and apply information, and think critically. These abilities are universally important, but a note for my fellow programmers: <em>these are quintessential abilities needed for programming</em>!</p><p>A typical <strong>CAT</strong> involves <strong>50 total multiple-choice questions</strong> of three types: <strong>verbal</strong>, <strong>math/logic</strong>, and <strong>spatial</strong>(abstract)<strong> reasoning</strong>. The candidate is to answer as many questions as possible <strong>within 15 minutes</strong>. That produces an average time of 18 seconds per question. The fact that the test is timed is a major factor in difficulty, and intimidation. Add to that, resources and tools are <em>not</em> permitted to be used during the test. <strong>No dictionary</strong>, <strong>no calculator</strong>, <strong>no internet</strong>, just your brain.</p><h4>Examples of Cognitive Aptitude Test questions:</h4><p><strong>VERBAL:</strong></p><p>Verbal questions evaluate your communication skills, which are invaluable in the workplace, in any team environment, or, frankly, in <em>any</em> relationship. The answers to verbal questions reflect the candidate’s ability to discern a word’s precise meaning, understand how words relate to one another, and understand how context is used.</p><p>Common themes:</p><ul><li>word analogies</li><li>sentence completion</li><li>antonyms</li><li>attention to detail</li></ul><pre>Choose the word that is most nearly OPPOSITE of the word in capital letters.</pre><pre>PRAISE</pre><pre>A. defile<br>B. criticize<br>C. kudos<br>D. defeat<br>E. surmise</pre><p><strong>MATH/LOGIC:</strong></p><p>Math/Logic questions evaluate your numerical reasoning skills and your number sense, which are directly related to your ability to think critically and problem-solve. Whether you’re a cashier, accountant, or physicist, mathematics will be used in your daily work. The Pythagorean philosophy of <a href="https://en.wikipedia.org/wiki/Mathematicism">Mathematicism</a> states that <em>everything</em> is mathematics. 😉</p><p>Common themes:</p><ul><li>direct calculations</li><li>math word problems</li><li>table/chart problems</li><li>number/letter series</li><li>critical thinking</li></ul><pre>A group of 3 numbers has an average of 18. The first two numbers are 13 and 20. What is the third number?</pre><pre>A. 18<br>B. 20<br>C. 21<br>D. 24<br>E. 31</pre><p><strong>SPATIAL REASONING:</strong></p><p>Spatial, or Abstract, Reasoning questions evaluate your innate aptitude and how well you’ll be able to learn, solve problems, and correctly apply new information. Every job has training, or at least a first day, when you are exposed to a new system, routine, tool, skill set, et cetera. Those that can sharply produce a solution to a problem or quickly perform a task will gain attention and successfully contribute to their workplace.</p><p>Common themes:</p><ul><li>shape sequence</li><li>odd one out</li><li>matrix completion</li></ul><pre>Which of the following sequences should replace the question mark (?) to complete the pattern?</pre><pre>  ({[({[        }])}])        [({[({        )}])}]           ?</pre><pre>A. }])}])<br>B. ({[({[<br>C. [({[({<br>D. {[({[(<br>E. ])}])}</pre><h4>How to prepare for a Cognitive Aptitude Test:</h4><p><strong>Read the instructions:</strong></p><p>This seems obvious, but many rush past instructions. There is invariably useful information given to you by instructions. Regarding the testing instructions, take as much time as you need to thoroughly read them, reread them, re<em>-</em>reread them. If you have a very clear understanding of what is expected of you, you will be less prone to making mistakes. Regarding test questions, although you are being timed, take enough time to thoroughly understand the question. It would be better to answer question one correctly, skip question two, and answer question three correctly, then rush through question one and two and provide two incorrect answers.</p><p><strong>Time management:</strong></p><p>This is a very important fact to understand, accept, remember, and be comforted by: <em>less than one percent (1%) of all candidates who take a CAT answer all 50 questions</em>. That is a feat for the anomalous super-brains among us. The results of the test are an evaluation of your aptitude, not your speed. It could be possible that you know all the answers to the last 25 questions, but got stumped on many of the first 25 questions and timed out halfway through the test. That scenario would essentially halve your potential score. It is better to keep a steady pace. If you don’t know the answer to a question, or are struggling to understand the question, and 30+ seconds have passed by—make a guess and move on. Note that the score for this test is determined by correct answers, without penalty for incorrect answers.</p><p><strong>Identify, recognize, and prioritize your strengths:</strong></p><p>In general, persons tend to be better at some things than others. You might be great at math and logic, but cannot cannot differentiate <em>there</em> and <em>their</em>. You might be a true wordsmith, but cannot tell a circle from a square. Knowing that the CAT is comprised of three types of questions: verbal, math/logic, and spatial reasoning, you can tend towards guessing for the types of questions you know are not your strong suit, or spend less time on those questions.</p><p><strong>Prepare and practice and practice and practice:</strong></p><p>We live in the information age. There are tools at your disposal, accessible from your living room via the internet, often at no cost. There are specific websites and apps built to help you study, learn, and practice the material presented in a CAT. Take advantage of those resources! Use your favorite web browser to search something like “cognitive aptitude test prep” or simply “cognitive aptitude test ”, and behold! If you’re an analog person, head to your local library or favorite book shop and ask for the goods. Actively learning and simulating the test experience will absolutely improve your ability to test and result in high performance, <em>and</em> increase and improve your knowledge and skills in general. It can only help you, and can be fun. The material presented in a CAT is basically puzzles, or games, which are fun!</p><p>I wish you the best of luck if you are preparing for a Cognitive Aptitude Test, or some other cognitive test. I hope this article served you! See below: the answers to the example questions presented in this article. Did you answer all of them?</p><p><a href="https://github.com/dangrammer">github.com/dangrammer</a><br><a href="https://www.linkedin.com/in/danieljromans/">linked.com/in/danieljromans</a><br><a href="http://danromans.com/">danromans.com</a></p><pre>answers: verbal - B | math/logic - C | spatial reasoning - D</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=beb4fff17465" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Customize Semantic Token Colorization With Visual Studio Code]]></title>
            <link>https://medium.com/@danromans/how-to-customize-semantic-token-colorization-with-visual-studio-code-ac3eab96141b?source=rss-c8fbe0846cb0------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac3eab96141b</guid>
            <category><![CDATA[how-to]]></category>
            <category><![CDATA[vscode]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[customization]]></category>
            <dc:creator><![CDATA[Dan Romans]]></dc:creator>
            <pubDate>Fri, 05 Jun 2020 23:22:51 GMT</pubDate>
            <atom:updated>2020-06-06T16:30:24.627Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A Node.js terminal printout which exclaims in colorful text: “COLORS!”." src="https://cdn-images-1.medium.com/max/1024/1*EDrOGKQquVjleQcrGV8Z9A.png" /></figure><p>When I installed the most recent <a href="https://code.visualstudio.com/">Visual Studio Code</a> release (Update 1.45.1, April 2020 (version 1.45), I noticed something funky occurring with the syntax highlighting. The short story is that the default colors for some tokens had changed, and I wanted the default colors to stay as I was used to! This is a guide to customizing semantic token colorization for VS Code users.</p><h4>Syntax Highlighting:</h4><p><a href="https://code.visualstudio.com/api/language-extensions/syntax-highlight-guide">Syntax highlighting</a> determines the color and style of source code in the text editor. This is extremely useful. It provides contrast to key words, <em>e.g.</em> if &amp; for in JavaScript, so that your eyes can more immediately locate a particular text among a sea of strings, variables, comments, et cetera.</p><p>The two processes that make syntax highlighting possible are:</p><ul><li><a href="https://code.visualstudio.com/api/language-extensions/syntax-highlight-guide#tokenization">Tokenization</a>: segmenting the text based on lexical rules (regular expressions contained in a <a href="https://macromates.com/manual/en/language_grammars">TextMate grammar</a>) and classifying each segment with a token type.</li><li><a href="https://code.visualstudio.com/api/language-extensions/syntax-highlight-guide#theming">Theming</a>: using themes or user settings to map the tokens to specific colors and styles.</li></ul><h4>Semantic Highlighting:</h4><p><a href="https://code.visualstudio.com/api/language-extensions/semantic-highlight-guide">Semantic highlighting</a> is an adjunct to syntax highlighting. It’s basically fancier syntax highlighting. The same idea as benefitting from a promotional deal and getting a new computer with additional memory and storage. <em>The basic model works just fine, but the deluxe model is really worth it!</em></p><p>Semantic highlighting is language specific. Currently, it is available for TypeScript and JavaScript. Semantic tokenization allows language servers to improve and refine the syntax highlighting of tokens based on knowledge of how to resolve symbols in the context of a project.</p><p>This is useful because it enables greater specificity, offering the user more flexibility and control. For example, one can assign a different color or style to constant variables to distinguish them among all variables.</p><h3>Customization:</h3><p>VS Code, and most text editors, provide built-in themes for the editor view. It is also possible to create your own theme, but many are content to select one of the available built-ins. I use a built-in theme, hence, upon updating VS Code, I was subject to its defaults. Semantic highlighting is a default for built-in themes, but there is the ability to customize elements of the theme.</p><h4>Settings:</h4><p>The first step is to access settings so they can be edited. There are <em>user settings</em> (global) and <em>workspace settings</em> (local). I’ll be demonstrating how to edit user settings since I’d like my color customization to persist across all projects. There are multiple ways to access the user settings. In particular, I’m targeting the settings.json file, for there I can customize. Here’s how to find it:</p><p><strong>Command Line:</strong> Navigate to the file in the terminal.</p><ul><li>macOS: $HOME/Library/Application\ Support/Code/User/settings.json</li><li>Linux: $HOME/.config/Code/User/settings.json</li><li>Windows: %APPDATA%\Code\User\settings.json</li><li><em>Note: for macOS, once in the User directory, you can open the </em>settings.json<em> file in the current window with this command: </em>code -r settings.json<em>.</em></li></ul><figure><img alt="Animated GIF of command line navigation of terminal." src="https://cdn-images-1.medium.com/max/600/1*5QnbQmQxFRFaDRJjfly-jQ.gif" /><figcaption><em>Demonstration for macOS (sorry for the low resolution)</em></figcaption></figure><p><strong>UI:</strong> Navigate to the file from the application.</p><ul><li>macOS:</li></ul><pre>1. Code -&gt; Preferences -&gt; Settings || keyboard: [⌘][,] (command + ,)<br>2. Click icon of dog-eared page with flip arrow that is located on the right-hand side of the tabs header.</pre><ul><li>Linux &amp; Windows:</li></ul><pre>1. File -&gt; Preferences -&gt; Settings || keyboard: [^][,] (control + ,)<br>2. Click icon of dog-eared page with flip arrow that is located on the right-hand side of the tabs header.</pre><figure><img alt="Animated GIF of UI navigation of application." src="https://cdn-images-1.medium.com/max/600/1*j6uvGAptDXOoEnfRM2eXSA.gif" /><figcaption><em>Demonstration for macOS (sorry for the low resolution)</em></figcaption></figure><h4>Inspection &amp; Identification:</h4><p>The next step is to inspect the source code in order to determine the scope of what you want to customize, and evaluate its metadata. There is a convenient built-in tool for this called the <a href="https://code.visualstudio.com/api/language-extensions/syntax-highlight-guide#scope-inspector">Scope Inspector</a>. You can activate the scope inspector from the <a href="https://code.visualstudio.com/docs/getstarted/userinterface#_command-palette">Command Palette</a>. You can launch the Command Palette with this keyboard shortcut: [⇧][⌘][P](shift + command + P), or control-click/right-click the text you want to inspect, then select “Command Palette” from the context menu.</p><p>From the Command Palette, you can type Developer: Inspect Editor Tokens and Scopes and select the matching option from the selection box to launch the Scope Inspector. With the Scope Inspector, click on or highlight the text you mean to evaluate.</p><figure><img alt="A screen capture of using the VSC Scope Inspector." src="https://cdn-images-1.medium.com/max/1024/1*nRpNyBejCEusAwxA02-RZw.png" /><figcaption>Highlight the text/token console to evaluate its metadata.</figcaption></figure><p>In the screen capture above, the text/token console has been inspected. This is how I discovered the cause of the new colorization that I did not want from the VS Code update. In the metadata, the semantic token is assigned the color theming {“foreground”: “#9CDCFE”} (blue), and it overrides the TextMate scopes assignment {“foreground”: “#4EC9B0”} (green)—the previous color. Notice in the screen shot that console is the same color blue as variables like arr and tempArr. I like to easily find console.log, so my goal was to revert this theming.</p><p>in order to customize the theming for this token, we need to use the information listed by the Scope Inspector for semantic token type: variable, and modifier: defaultLibrary.</p><h4>Editing:</h4><p>Now, with the needed information, we can add a key-value pair to the JSON object in settings.json. This is a model of what you’d insert:</p><pre>&quot;editor.semanticTokenColorCustomizations&quot;: {<br>  // location<br>  &quot;rules&quot;: {<br>    // identifier // theme<br>    // identifier // theme<br>},</pre><p>In terms of location, suppose you wanted this styling to apply globally. You could enable semantic highlighting for all themes with a key-value pair like this:</p><pre>&quot;editor.semanticTokenColorCustomizations&quot;: {<br>  &quot;enabled&quot;: true,<br>  &quot;rules&quot;: {<br>    // identifier // theme<br>    // identifier // theme<br>},</pre><p>In my case, I only designated the styling for the theme I use, so the location is represented by a key-value pair of the theme name and an object:</p><pre>&quot;editor.semanticTokenColorCustomizations&quot;: {<br>  &quot;[Default Dark+]&quot;: {<br>    &quot;rules&quot;: {<br>      // identifier // theme<br>      // identifier // theme<br>},</pre><p>Identifier and theme represent the targeted token and how it should be styled. The identifier is referred to as the <em>selector</em> and is formatted as tokenType.tokenModifier. The value of the selector represents the theme and is formatted as a value, or an object containing key-value pairs, which dictate styling.</p><pre>&quot;editor.semanticTokenColorCustomizations&quot;: {<br>  &quot;[Default Dark+]&quot;: {<br>    &quot;rules&quot;: {<br>      // different color for all constants<br>      &quot;property.readonly&quot;: &quot;#35166d&quot;,<br>      // make all symbol declarations bold and italic<br>      &quot;*.declaration&quot;: {&quot;bold&quot;: true, &quot;italic&quot;: true}<br>},</pre><p>In my case, I just wanted to revert the color for support variables like console and Math, and I preferred a different color for constant variables.</p><pre>&quot;editor.semanticTokenColorCustomizations&quot;: {<br>  &quot;[Default Dark+]&quot;: {<br>    &quot;rules&quot;: {<br>      &quot;variable.defaultLibrary&quot;: &quot;#4EC9B0&quot;,<br>      &quot;variable.readonly&quot;: &quot;#51a3c4&quot;<br>    }<br>  }<br>}</pre><p>Once I edited my settings.json file, I had the semantic token colorization just the way I like it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r8-R_aICcfPiTZCFyKwjiQ.png" /></figure><p>This is just the tip of the iceberg when it comes to VS Code customizations! Dig in to the <a href="https://code.visualstudio.com/docs">documentation</a>, get some <a href="https://marketplace.visualstudio.com/">extensions</a>, and optimize your editor to be the coding powerhouse it needs to be.</p><p><a href="https://github.com/dangrammer">github.com/dangrammer</a><br><a href="https://www.linkedin.com/in/danieljromans/">linked.com/in/danieljromans</a><br><a href="http://danromans.com/">danromans.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac3eab96141b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sorting Code Challenge Breakdown]]></title>
            <link>https://medium.com/weekly-webtips/sorting-code-challenge-breakdown-19229b32be02?source=rss-c8fbe0846cb0------2</link>
            <guid isPermaLink="false">https://medium.com/p/19229b32be02</guid>
            <category><![CDATA[big-o-notation]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[counting-sort]]></category>
            <category><![CDATA[code-challenge]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Dan Romans]]></dc:creator>
            <pubDate>Sat, 30 May 2020 23:54:06 GMT</pubDate>
            <atom:updated>2020-06-03T19:00:43.460Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A representative from Friends of Surely holds up a giant check for five hundred dollars for Surely Fünke for life." src="https://cdn-images-1.medium.com/max/718/1*ZiEFlewTH_zVSy_8ejyViQ.jpeg" /><figcaption>Hold on Surely Fünke! Surely Fünke –how we ♥ thee–</figcaption></figure><p>It’s time once again for a breakdown of a HackerRank code challenge. In particular, a code challenge called <a href="https://www.hackerrank.com/challenges/fraudulent-activity-notifications/problem"><em>Fraudulent Activity Notifications</em></a>. The theme is befitting of Maeby Fünke’s dubious alter ego: Surely, who suffers from a disease called “BS”, and will gladly accept monetary donations in her support.</p><p>This code challenge is a tricky and interesting one. Its principal facet is efficiently sorting things, but it requires the use of a less common algorithm: counting sort. (There is a solution which employs priority queues, but that’s another article.) Additionally, this challenge requires the calculation of medians, careful consideration for how certain numeric values are treated, and the use of a sliding window to isolate specific data per iteration.</p><p>I struggled to solve this challenge for quite a while. At first, because I didn’t know about counting sort, so I learned about counting sort. Then, I still struggled to find a solution because I couldn’t make sense of how to properly integrate counting sort into the context. I danced around the solution for a while, then submitted, and accessed the problem’s editorial explanation. I <em>still</em> struggled to understand, so I referenced solutions by others, but they were in languages I’m not most familiar with, and in some cases erroneous.</p><p>After further dissecting the problem and piecing together clues, I finally succeeded in writing a solution in JavaScript that met the performance requirements and passed all test cases. I’d like to thank a programmer who goes by <a href="https://jjromi.github.io/">JJromi</a>. They posted a Java solution to this challenge that was clever and finally provided me with the <em>Aha!</em> moment of understanding. In addition to explaining the code mechanics of the solution for everyone, this article provides a solution to be referenced by others working with JavaScript!</p><h3>Fraudulent Activity Notifications:</h3><h4>Problem Statement:</h4><p>There is a bank that has a policy for notifying its clients of possible fraudulent activity in their account. If the amount spent by a client on a particular day is greater than or equal to twice (2x) the median spending amount of a specified number of trailing days—days which precede the present day—the bank will send the client a notification of potential fraudulent activity. The bank will not send a notification to the client until the specified number of trailing days has occurred.</p><p>Given the number of trailing days and the client’s total daily debits for a period of n days, determine the number of notifications the client will receive during the period. For example:</p><pre>const days = 3<br>const debits = [10, 20, 30, 40, 50]</pre><pre>// the first three days (idx 0, 1, 2), the bank just collects data</pre><pre>// on day four (idx 3), there are 3 trailing days: 10, 20, 30<br>// the daily debit is 40, and the median is 20<br>// 40 &gt;= 20 * 2 =&gt; true<br>// 1 fraud notification is sent to the client</pre><pre>// on day five (idx 4), there are 3 trailing days: 20, 30, 40<br>// the daily debit is 50, and the median is 30<br>// 50 &gt;= 30 * 2 =&gt; <strong>false</strong><br>// no fraud notification is sent to the client</pre><pre>// total notifications for the period is <strong>1</strong></pre><p><strong>Note:</strong></p><p>The <a href="https://en.wikipedia.org/wiki/Median">median</a> of a list of numbers can be found by arranging the numbers from smallest to greatest—<em>sorting</em> them. If there is an odd amount of numbers, the median is the middle number. If there is an even amount of numbers, the median is the <a href="https://en.wikipedia.org/wiki/Arithmetic_mean">average</a> of the <em>two</em> middle numbers.</p><h4>Function Description:</h4><p>The activityNotifications() function must return an integer representing the number of notifications sent to the client.</p><p><strong>Input Parameters:</strong></p><ul><li>debits: an Array of integers representing daily expenditures</li><li>days: an integer representing the required number of trailing days</li></ul><p><strong>Constraints:</strong></p><ul><li>0 &lt;= debits[i] &lt;= 200: any daily debit amount cannot exceed 200.</li></ul><h4>Brute Force Solution:</h4><p>Let’s start by reviewing my first draft. It functions correctly and produces the desired output, but is not efficient enough to pass all test cases, primarily because it is not time efficient.</p><pre>function activityNotifications(debits, days) {<br>  let notices = 0</pre><pre>  for (let i = days; i &lt; debits.length; i++) {<br>    const trail = debits.slice(i - days, i).sort((a, b) =&gt; a - b)<br>    const median = trail.length % 2 === 0 ?<br>      trail[(trail.length / 2) - 1] + trail[(trail.length / 2)] :<br>        trail[Math.floor(trail.length / 2)] * 2</pre><pre>    if (debits[i] &gt;= median) notices++<br>  }</pre><pre>  return notices<br>}</pre><p>This brute force solution is good to analyze because it approximates the basic mechanics of the needed function and highlights the needed improvements.</p><ul><li>There is a function declaration with its parameters.</li><li>There is a counter variable notices which will keep track of how many notifications are sent and act as the return value.</li><li>There is a for loop which iterates over the debits Array <em>starting from </em>the first index greater than the specified trailing days.</li><li>There is a sliding window used to highlight and evaluate specific portions of the debits Array, built by using the .slice() method and .sort() method and assigned to the variable trail. *<em>Put a pin in this</em>.</li><li>There is a rather convoluted conditional operator assigned to the variable median which uses the window (trail) to take advantage of the values being sorted, evaluate whether there is an odd or even amount of values within the trailing days, and produce a median of the daily debits with the appropriate mathematical calculation.</li><li>There is an if statement which performs a straightforward evaluation to check whether the daily debit is greater than or equal to the median spending amount of the trailing days. If so, the counter variable notices is incremented by 1.</li><li>There is a return statement which returns the integer represented by notices—the amount of fraudulent activity notices sent to the client.</li></ul><p>This function follows decent logic, but has some crucial flaws that require a major refactor. Convoluted median calculation by conditional operator aside, notice that, for each iteration of the for loop, the sliding window trail is constructed with iterators: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice">.slice()</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort">.sort()</a>. This majorly impacts the time and space complexity of the function.</p><p>Consider that .slice() affects the space complexity by creating a shallow copy of the debits Array at each iteration, but, more specific to this challenge’s test cases, when regarding nested loops, <em>e.g.</em> for loop () { Array.sort() }, the time complexity becomes quadratic (O(n²)), which is not optimal and becomes an issue when the input size becomes great.</p><p>The calculation of medians is essential to this function, which requires a sorted list of numbers. How can the process of sorting lists of integers at each window slide be performed while optimizing the function, improving its time complexity, and enhancing its performance?</p><h4>Optimized Solution:</h4><p>The solution this code challenge seeks performs in linear time (O(n)), and to achieve this we’ll need to employ a sorting algorithm capable of performing linearly. In this case, we can use <a href="https://en.wikipedia.org/wiki/Counting_sort">counting sort</a>. I’m going to focus explanation on how counting sort applies to this solution, and on the solution itself, more so than <em>exactly</em> how counting sort works. If you don’t know how counting sort works, I recommend you pause here and learn about how it works. I can recommend <a href="https://medium.com/@danromans/counting-sort-a10abdbbf45f">this informational article</a> I wrote about it.</p><p>There is a key reason that counting sort is applicable. Notice that in the function description there is a constraint which dictates that the value of any daily debit, <em>i.e.</em> any element in the input Array, cannot exceed 200. This relatively small number allows us to create the frequency Array that counting sort depends on. Let’s start with the good bones from the brute force solution and build upon them to produce the optimized solution.</p><pre>function activityNotifications(debits, days) {<br>  let notices = 0</pre><pre>  for (let i = days; i &lt; debits.length; i++) {<br>    const median = // work to figure the median<br>    if (debits[i] &gt;= median * 2) notices++<br>  }</pre><pre>  return notices<br>}</pre><p>Those are the bones we want to work with. The next step is to integrate counting sort. We start by initializing the frequency Array. We can call it countArr. Recall that the 0 index needs to be accommodated, so the size of the Array is set to 201, not 200.</p><pre>function activityNotifications(debits, days) {<br>  <strong>const countArr = new Array(201).fill(0)</strong><br>  let notices = 0</pre><pre>  for (let i = days; i &lt; debits.length; i++) {<br>    const median = // work to figure the median<br>    if (debits[i] &gt;= median * 2) notices++<br>  }</pre><pre>  return notices<br>}</pre><p>Now that the countArr is initialized, we can load it. Recall that we want to use a sliding window to evaluate only the required number of trailing days at each iteration. Knowing this, we start by loading countArr for only the first window by using a for loop with the counter limit set to the number of days.</p><pre>function activityNotifications(debits, days) {<br>  const countArr = new Array(201).fill(0)<br>  let notices = 0</pre><pre>  <strong>for (let i = 0; i &lt; days; i++) {<br>    countArr[debits[i]]++<br>  }</strong></pre><pre>  for (let i = days; i &lt; debits.length; i++) {<br>    const median = // work to figure the median<br>    if (debits[i] &gt;= median * 2) notices++<br>  }</pre><pre>  return notices<br>}</pre><p>The function prepares countArr for the first iteration of the for loop, but we need to slide that window to the next set of trailing days at each iteration so an updated countArr is available for each next iteration. In case this procedure is unclear at this point, picture this:</p><pre>// loop 1<br>[ 0 0 0 ] 0 0 0</pre><pre>// loop 2<br>0 [ 0 0 0 ] 0 0</pre><pre>// loop 3<br>0 0 [ 0 0 0 ] 0</pre><p>The way to achieve this with counting sort and its complex index magic is to <em>decrement</em> the value in countArr at the index equal to the <em>first</em> value of the trailing days, and <em>increment</em> the value in countArr at the index equal to the value <em>just after</em> the trailing days. In other words, use an origin and a terminus regarding the window, <em>e.g.</em> debits: 0 0 [o 0 0] t, as corresponding indices for countArr, and increment/decrement accordingly.</p><p>Yes, that <em>is</em> confusing, but, once you learn how counting sort works, you’ll be able to make sense of it. The terminus falling outside of the window is to account for an index shift, so you can think of this more simply as using the numbers from the <em>beginning</em> and <em>end</em> of the window. Shifting the entire window by its ends, like if you were to grab either end of a dining tray and move it to the next station in a cafeteria line. This article will also include a log of the function work to help demonstrate how the mechanics are manipulating values.</p><p>Let’s add the code that will handle the sliding window procedure. Notice that it comes at the end of the work done in the for loop, allowing the median calculation to be performed before countArr is adjusted for the next iteration.</p><pre>function activityNotifications(debits, days) {<br>  const countArr = new Array(201).fill(0)<br>  let notices = 0</pre><pre><strong>  </strong>for (let i = 0; i &lt; days; i++) {<br>    countArr[debits[i]]++<br>  }</pre><pre>  for (let i = days; i &lt; debits.length; i++) {<br>    const median = // work to figure the median<br>    if (debits[i] &gt;= median * 2) notices++<br>    <strong>countArr[debits[i - days]]--<br>    countArr[debits[i]]++</strong><br>  }</pre><pre>  return notices<br>}</pre><p>At this point, this function is practically complete. Except, of course, for the line that says: const median = // work to figure the median. As convenient as that would be, we’re going to need to help the computer out. We’re going to outsource this work by way of a helper function. The purpose of the helper function will be to calculate the median spending amount of each window of trailing days.</p><p>This helper function will accept two arguments: countArr and days, which will come from the scope of the main function. The helper function will return the currently evaluated median times two (* 2), which, at this point, is work done in the main function, but will be more valuable to calculate within the helper function. Let’s call our helper function getMedianx2().</p><pre>function getMedianx2(countArr, days) {<br>  let sum = 0</pre><pre>  for (let i = 0; i &lt; countArr.length; i++) {<br>    sum += countArr[i]<br>    if (sum * 2 === days) return (i * 2 + 1)<br>    if (sum * 2 &gt; days) return (i * 2)<br>  }<br>}</pre><p>Let’s break down the getMedianx2() helper function. Firstly, let’s highlight the significance of the arguments given to the function. countArr is used to find the median of each window because countArr is a sorted reference to the debits Array, and we need a sorted list of numbers to determine a median. days is used to determine how the median needs to be calculated. Recall that different operations are required depending on whether the list of numbers is odd or even. The median of an odd list is the middle number. The median of an even list is the average of the middle two numbers. days is either an odd or even number.</p><p>Next, we have a counter variable called sum. This will represent the accumulative sum of the values in countArr as they are iterated over. Calculating an accumulative sum is a necessary step for counting sort. A for loop performs the iteration over countArr, adding the current value to sum at each iteration.</p><p>Now, here’s the clever part: There are two conditionals—two if statements— within the loop that if met will break out of the loop and produce a return value. Instead of division, which is more computationally expensive and can produce pitfalls like floating point decimals, multiplication is used to determine if days is odd or even. The multiplier we’ll use is 2 because we want to double the value we’re evaluating, as the main function checks if the median <em>times two</em> (* 2) is greater than or equal to the daily debit. Hence, our helper is called getMedian<strong>x2</strong>().</p><p>If, on any iteration, sum * 2 is equal to days, we can determine that sum is even because days can be evenly divided by 2. Because of how counting sort hashes indices, we can use days as an upper limit for sum, which breaks the loop and targets the current index i, which correlates to the value from the debits Array, and consequently translates to the median value of the current window.</p><p>Note, though, that since the first conditional considers an even list of numbers in the window, the average of the middle two numbers is the desired value. Because of how this clever line of code and the counting sort magic work out, and because multiplication is used instead of division, the same result can be achieved by simply adding 1, or rounding up the result: (i * 2) + 1.</p><p>If the first conditional is passed by and the second conditional—sum * 2 &gt; days—is met, it can be determined that days is an odd number, and the correct median can be returned by simply multiplying the current index i by 2. No rounding is necessary in this case.</p><p>Now that our helper function is set, the last thing to do is plug it into the main function. Note that the variable previously called median will be changed to medianx2 to be more specific about what value the variable is holding. One more added nicety is to place a conditional paired with a break statement before the window sliding procedure. This way, when the <em>last</em> daily debit is evaluated, the window sliding procedure will not be performed, as it would be unnecessary. Here’s the complete solution:</p><pre>function getMedianx2(countArr, days) {<br>  let sum = 0</pre><pre>  for (let i = 0; i &lt; countArr.length; i++) {<br>    sum += countArr[i]<br>    if (sum * 2 === days) return (i * 2 + 1)<br>    if (sum * 2 &gt; days) return (i * 2)<br>  }<br>}</pre><pre>function activityNotifications(debits, days) {<br>  const countArr = new Array(201).fill(0)<br>  let notices = 0</pre><pre>  for (let i = 0; i &lt; days; i++) {<br>    countArr[debits[i]]++<br>  }</pre><pre>  for (let i = days; i &lt; debits.length; i++) {<br>    <strong>const medianx2 = getMedianx2(countArr, days)</strong><br>    if (debits[i] &gt;= <strong>medianx2</strong>) notices++<br>    <strong>if (i === debits.length - 1) break</strong><br>    countArr[debits[i - days]]--<br>    countArr[debits[i]]++<br>  }</pre><pre>  return notices<br>}</pre><h4>Process Log:</h4><p>Here’s a log of how the data is being passed through the function and manipulated. Hopefully, it helps to further illustrate the explanation.</p><pre>const days = 5<br>const debits = [2, 3, 4, 2, 3, 6, 8, 4, 5]</pre><pre>activityNotifications(debits, days)</pre><pre>// LOG /////////////////////////////////////////////////////////////</pre><pre><strong>input:</strong><br>  debits array: [2, 3, 4, 2, 3, 6, 8, 4, 5]<br>  days span: 5</pre><pre><strong>initialize:</strong><br>  count array: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]<br>  notices: 0</pre><pre><strong>load count array:</strong><br>  count array: [0, 0, 2, 2, 1, 0, 0, 0, 0, 0]</pre><pre><strong>main loop:</strong><br>  <em>iteration 1</em><br>    daily debit: 6<br>    trailing days: [2, 3, 4, 2, 3]</pre><pre>    get median function:<br>      count array: [0, 0, 2, 2, 1, 0, 0, 0, 0, 0]<br>      trailing day count: 5<br>      getMedian loop:<br>        iteration 1<br>          accumulation sum: 0<br>          current index: 0<br>        iteration 2<br>          accumulation sum: 0<br>          current index: 1<br>        iteration 3<br>          accumulation sum: 2<br>          current index: 2<br>        iteration 4<br>          accumulation sum: 4<br>          current index: 3</pre><pre>    medianx2: 6<br>    daily debit(6) is greater than or equal to median * 2 = 6<br>    increment notices<br>    notices + 1 = 1</pre><pre>    count array before adjustment: [0, 0, 2, 2, 1, 0, 0, 0, 0, 0]<br>      countArr[2]--<br>      countArr[6]++<br>    count array after adjustment : [0, 0, 1, 2, 1, 0, 1, 0, 0, 0]</pre><pre>  <em>iteration 2</em><br>    daily debit: 8<br>    trailing days: [3, 4, 2, 3, 6]</pre><pre>    get median function:<br>      count array: [0, 0, 1, 2, 1, 0, 1, 0, 0, 0]<br>      trailing day count: 5<br>      getMedian loop:<br>        iteration 1<br>          accumulation sum: 0<br>          current index: 0<br>        iteration 2<br>          accumulation sum: 0<br>          current index: 1<br>        iteration 3<br>          accumulation sum: 1<br>          current index: 2<br>        iteration 4<br>          accumulation sum: 3<br>          current index: 3</pre><pre>    medianx2: 6<br>    daily debit(8) is greater than or equal to median * 2 = 6<br>    increment notices<br>    notices + 1 = 2</pre><pre>    count array before adjustment: [0, 0, 1, 2, 1, 0, 1, 0, 0, 0]<br>      countArr[3]--<br>      countArr[8]++<br>    count array after adjustment : [0, 0, 1, 1, 1, 0, 1, 0, 1, 0]</pre><pre>  <em>iteration 3</em><br>    daily debit: 4<br>    trailing days: [4, 2, 3, 6, 8]</pre><pre>    get median function:<br>      count array: [0, 0, 1, 1, 1, 0, 1, 0, 1, 0]<br>      trailing day count: 5<br>      getMedian loop:<br>        iteration 1<br>          accumulation sum: 0<br>          current index: 0<br>        iteration 2<br>          accumulation sum: 0<br>          current index: 1<br>        iteration 3<br>          accumulation sum: 1<br>          current index: 2<br>        iteration 4<br>          accumulation sum: 2<br>          current index: 3<br>        iteration 5<br>          accumulation sum: 3<br>          current index: 4</pre><pre>    medianx2: 8<br>    daily debit(4) is less than median * 2 = 8<br>    no adjustment to notices<br>    notices = 2</pre><pre>    count array before adjustment: [0, 0, 1, 1, 1, 0, 1, 0, 1, 0]<br>      countArr[4]--<br>      countArr[4]++<br>    count array after adjustment : [0, 0, 1, 1, 1, 0, 1, 0, 1, 0]</pre><pre> <em> iteration 4</em><br>    daily debit: 5<br>    trailing days: [2, 3, 6, 8, 4]</pre><pre>    get median function:<br>      count array: [0, 0, 1, 1, 1, 0, 1, 0, 1, 0]<br>      trailing day count: 5<br>      getMedian loop:<br>        iteration 1<br>          accumulation sum: 0<br>          current index: 0<br>        iteration 2<br>          accumulation sum: 0<br>          current index: 1<br>        iteration 3<br>          accumulation sum: 1<br>          current index: 2<br>        iteration 4<br>          accumulation sum: 2<br>          current index: 3<br>        iteration 5<br>          accumulation sum: 3<br>          current index: 4</pre><pre>    medianx2: 8<br>    daily debit(5) is less than median * 2 = 8<br>    no adjustment to notices<br>    notices = 2</pre><pre><strong>output:</strong><br>  notices: 2</pre><p>Counting sort is a little hard to wrap your head around, but it can be very powerful in the right situation. Try to dig deeper into the magic that’s occurring under the hood while using counting sort. It’s a good brain builder. And try your hand at solving the <a href="https://www.hackerrank.com/challenges/fraudulent-activity-notifications/problem"><em>Fraudulent Activity Notifications</em></a> challenge!</p><p><a href="https://github.com/dangrammer">github.com/dangrammer</a><br><a href="https://www.linkedin.com/in/danieljromans/">linked.com/in/danieljromans</a><br><a href="http://danromans.com/">danromans.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19229b32be02" width="1" height="1" alt=""><hr><p><a href="https://medium.com/weekly-webtips/sorting-code-challenge-breakdown-19229b32be02">Sorting Code Challenge Breakdown</a> was originally published in <a href="https://medium.com/weekly-webtips">Webtips</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The isNaN() Function For JavaScript]]></title>
            <link>https://levelup.gitconnected.com/the-isnan-function-for-javascript-955a424bbd36?source=rss-c8fbe0846cb0------2</link>
            <guid isPermaLink="false">https://medium.com/p/955a424bbd36</guid>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[numbers]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[debugging]]></category>
            <dc:creator><![CDATA[Dan Romans]]></dc:creator>
            <pubDate>Thu, 21 May 2020 21:06:57 GMT</pubDate>
            <atom:updated>2020-05-24T00:23:11.916Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A pair of Owl butterflies imitating the face of an owl." src="https://cdn-images-1.medium.com/max/960/1*FyfBjOb6jny9z0Kd4nAL2w.jpeg" /><figcaption>Not an… owl?</figcaption></figure><p>In JavaScript, there is a property of the global object called <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN">NaN</a>. NaN is an abbreviation, rather, an acronym, of “Not a Number”, and is not to be confused with the delicious flatbread: <a href="https://en.wikipedia.org/wiki/Naan">naan</a>. NaN is rarely used in writing programs or scripts. In modern web browsers it is a non-configureable and non-writeable property. It is most often received as a return value when a mathematic (<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math">Math</a>) function fails, or when a function fails to parse a number, <em>e.g.</em> parseInt(). NaN is quirky and uncommon, but is occasionally presented and needs to be handled.</p><p>In a recent project, with a React client side, the user account included a portfolio of collected stocks and corresponding prices. The portfolio had to include a gross sum of total earnings. Sounds easy enough: gather all the stock prices from the portfolio and add them together. Of course, things are never quite as easy as first assumed to be.</p><p>Upon a returning user logging into their account, the state was loaded with that user’s stocks, but the prices of these stocks—and, consequently, the total earnings—were dynamically rendered by fetching to an external API for current market prices. The difficulty was properly timing and dispatching actions to fetch data from the server side database and external API while properly rendering components on the client side. Within that chain of events, an action is dispatched which calculates the gross sum of the user’s total earnings, resolved by a function called setTotalEarnings.</p><p>Best solutions were to first properly sequence the fetches, promises, and component renders, or craft the setTotalEarnings function to better control the return value, or more simply handle a falsy return value while conditionally rendering, but, as I was building this application in a short time frame for an assessment, I pushed ahead and addressed what was needed to just get the thing working in time! Long story short, the setTotalEarnings function was intermittently returning NaN, and I was having trouble handling it to be rendered correctly in the appropriate React component.</p><p>I realized that the equality operator could not reliably determine if the return value of setTotalEarnings was NaN because NaN === NaN evaluates to false! This is a bizarre and unique occurrence in JavaScript. NaN is the only value in JavaScript which is not equal to itself. There is a helpful shortcut to more accurately handle NaN: the isNaN() function. It is quite easy to employ. Simply pass an argument to the function:</p><pre>isNaN(NaN) // true<br>isNaN({})  // true<br>isNaN(5)   // false</pre><p>While the function is simple enough, there exists special-case behavior that can still be bizarre and problematic. For example:</p><pre>isNaN(true) // false</pre><p>In other words, “Is true <strong>not</strong> a number?”, which you would expect to be correct, to evaluate true. true is <strong>not</strong> a number, yet the isNaN() function returns: false, implying that true is <strong>not</strong> not a number, <em>i.e.</em> true <em>is</em> a number, which is incorrect. This behavior occurs because the isNaN() function is meant to accept numeric values, values of the type number. When a non-numeric value is passed to the isNaN() function, the value is first coerced into a number and then evaluated. Regarding the previous example, the argument true is first coerced to the binary representation of 1. 1 is a number, <strong>not</strong> NaN, so the function returns false.</p><p>To add extra insurance and predictability to the evaluation of NaN values, there is a successor to the isNaN() function: the Number.isNaN() method. This method additively evaluates whether the type of value being evaluated is number before evaluating whether or not it is NaN.</p><p>To revisit a previous example:</p><pre>isNaN({}) // true<br>Number.isNaN({}) // false</pre><p>The input value {} is not a number, as the first case confirms, however, in the second case, it evaluates to false since it is of type object, not type number, meaning the input value is not numeric and cannot be properly compared to NaN.</p><p>isNaN() and Number.isNaN() are particular tools that you may never have to use, but when the day comes that you do, they are handy tools to properly handle the data. It’s always fun to scrape through the lesser used abilities of a programming language and maximize your resolution when faced with a peculiar scenario!</p><p><a href="https://github.com/dangrammer">github.com/dangrammer</a><br><a href="https://www.linkedin.com/in/danieljromans/">linked.com/in/danieljromans</a><br><a href="http://danromans.com/">danromans.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=955a424bbd36" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/the-isnan-function-for-javascript-955a424bbd36">The isNaN() Function For JavaScript</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Is Space Complexity, and How Is It Determined?]]></title>
            <link>https://javascript.plainenglish.io/what-is-space-complexity-and-how-is-it-determined-fa2ab0354b?source=rss-c8fbe0846cb0------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa2ab0354b</guid>
            <category><![CDATA[big-o-notation]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Dan Romans]]></dc:creator>
            <pubDate>Sat, 16 May 2020 02:02:10 GMT</pubDate>
            <atom:updated>2020-05-18T19:11:44.137Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A photograph of an interstellar nebula taken by NASA." src="https://cdn-images-1.medium.com/max/1024/0*fLjqlDruqJF8rkUo" /><figcaption>The Carina Nebula, in outer space</figcaption></figure><p>When evaluating the efficiency of an algorithm, more likely than not, the initial focus will be on <a href="https://en.wikipedia.org/wiki/Time_complexity">time complexity</a>: the amount of time it takes to run. This is natural—humans tend to focus on time. Benjamin Franklin once said: “Time is money”. Tony Stark, having traveled back in time, once relayed to his father words spoken to him by his father’s future self: “No amount of money ever bought a second of time”. Wise!</p><p>There is another performance evaluation which comes part and parcel with time complexity: <a href="https://en.wikipedia.org/wiki/Space_complexity">space complexity</a>: the memory required by an algorithm to run. In a sense, space complexity is the base consideration. Even if an algorithm is painfully <em>s l o o o o w w</em>, it can still run, but if the space required by an algorithm exceeds the allotted memory of the program, it won’t run.</p><p>Space complexity includes two factors: auxiliary space and input space. Auxiliary space is temporary space used by the algorithm for execution. Input space is space needed during execution considering the size of the input. There are scenarios wherein only auxiliary space is used to evaluate space complexity, but, for this article, total space—auxiliary and input—will be used. Consider this analogy:</p><p>Where I come from, Italian-American cuisine is ubiquitous. Say you have Sunday dinner with your big family, and you’re in charge of making the red sauce, the tomato sauce, the gravy. I make my sauce in an enameled Dutch oven on the stove. The Dutch oven is analogous to the auxiliary space. You want to make sauce without a vessel? GOOD LUCK. Of course, to cook your pasta-worthy sauce, you must synthesize ingredients. The quantity of ingredients [insert <em>your</em> <strong>correct</strong> list here] are analogous to the input space. Big family? Big eaters? More ingredients! More space!</p><p>Space complexity is considered to evaluate the use of memory, or data storage. Algorithms require the use of memory to do a few things:</p><ul><li>Store program instructions (compiler =&gt; runtime)</li><li>Execute (<em>e.g.</em> function calls, <a href="https://www.cs.auckland.ac.nz/references/unix/digital/AQTLTBTE/DOCU_075.HTM">jump statement</a>s)</li><li>Store data (<em>e.g.</em> constant and variable values)</li></ul><p>While these are all contributing factors, the stored variable data is often the primary consideration. As with time complexity, space complexity is typically represented with big O notation, and considers the worst-case scenario in its evaluation. Let’s use a few examples to demonstrate how the space complexity of an algorithm can be determined. The examples are in JavaScript.</p><h4>Example №1:</h4><pre><strong>function add(n1, n2) {<br>  const sum = n1 + n2<br>  return sum<br>}</strong></pre><pre>// In JavaScript, a number requires 64 bits of memory.<br>// For simplicity, we&#39;ll translate 64 bits to 8 bytes.</pre><pre>// The add function requires memory for 3 variables: <strong>n1</strong>, <strong>n2</strong>, &amp; <strong>sum</strong>.<br>// This memory is related to input space.</pre><pre>// The add function requires memory for the function call and <br>// return statement. This memory is related to auxiliary space.</pre><pre>// The required memory for the add function would be:<br>//  <strong>n1</strong> | 8 bytes<br>//       +<br>//  <strong>n2</strong> | 8 bytes<br>//       +<br>// <strong>sum</strong> | 8 bytes<br>//       +<br>// aux | 8 bytes (this is a wild guess!)<br>//       =<br>//       32 bytes</pre><pre>// The thing to note here is that the data space and auxiliary<br>// space are <strong>constant</strong>. No matter the value of the inputs, the<br>// memory needs are always the same:<br>// <strong>n1</strong> + <strong>n2</strong> + <strong>sum</strong> + aux, or 8 + 8 + 8 + 8 = 32 bytes.</pre><pre>// We can evaluate the space complexity of the add function as <br>// constant or <strong>O(1)</strong>. </pre><h4>Example №2:</h4><pre><strong>function sum(arr) {<br>  const sum = 0<br>  for (let i = 0; i &lt; arr.length; i++) {<br>    sum += arr[i]<br>  }<br>  return sum<br>}</strong></pre><pre>// The sum function requires memory for two variables: <strong>sum</strong> &amp; <strong>i</strong>.<br>// This memory is related to input space.</pre><pre>// The sum function requires memory for the function call, the for<br>// loop and the return statement. This memory is related to<br>// auxiliary space.</pre><pre>// The thing to note here is that the data space, or input space<br>// is <strong>not</strong> constant. It is <strong>linear</strong>. The required memory for the input<br>// space depends on the size of the data. In this case, the length<br>// of the Array. For example:</pre><pre><strong>const arr = [1, 2, 3, 4, 5]</strong><br>// N =&gt; arr.length =&gt; 5</pre><pre><strong>sum(arr)</strong></pre><pre>// The required memory for the sum function would be:<br>//  <strong>arr</strong> = k * 5 | 8 bytes * 5 = 40 bytes<br>//                          +<br>//          <strong>sum</strong> |                8 bytes<br>//                          +<br>//            <strong>i</strong> |                8 bytes<br>//                          +<br>//          aux |                8 bytes (another wild guess!)<br>//                          =<br>//                              64 bytes</pre><pre>// Suppose the length of the Array was 10 instead of 5:</pre><pre><strong>const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]</strong><br>// N =&gt; arr.length =&gt; 10</pre><pre><strong>sum(arr)</strong></pre><pre>// The required memory for the sum function would be:<br>//  <strong>arr</strong> = k * 10 | 8 bytes * 10 = 80 bytes<br>//                                 +<br>//           <strong>sum</strong> |                 8 bytes<br>//                                 +<br>//             <strong>i</strong> |                 8 bytes<br>//                                 +<br>//           aux |                 8 bytes (another wild guess!)<br>//                                 =<br>//                               104 bytes</pre><pre>// The needed memory for the sum function to execute <br>// proportionally increases with the size of the input: <br>// k * N + <strong>sum</strong> + <strong>i, </strong>for N = 10:<strong> </strong>8 * 10 + 8 + 8 + 8 = 104 bytes</pre><pre>// We can evaluate the space complexity of the sum function as <br>// linear or <strong>O(n)</strong>.</pre><p>Whether you’re asked to express the space complexity of an algorithm during a technical assessment, optimizing a program, or making a big ‘ol pot of sauce to adorn a hay bale’s worth of spaghetti with, you have some know how when it comes to why considering space is good practice. Buon appetito!</p><p><a href="https://github.com/dangrammer">github.com/dangrammer</a><br><a href="https://www.linkedin.com/in/danieljromans/">linked.com/in/danieljromans</a><br><a href="http://danromans.com/">danromans.com</a></p><h4><strong>A note from the Plain English team</strong></h4><p>Did you know that we have four publications and a YouTube channel? You can find all of this from our homepage at <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> — show some love by giving our publications a follow and <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>subscribing to our YouTube channel</strong></a><strong>!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa2ab0354b" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/what-is-space-complexity-and-how-is-it-determined-fa2ab0354b">What Is Space Complexity, and How Is It Determined?</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Counting Sort]]></title>
            <link>https://medium.com/@danromans/counting-sort-a10abdbbf45f?source=rss-c8fbe0846cb0------2</link>
            <guid isPermaLink="false">https://medium.com/p/a10abdbbf45f</guid>
            <category><![CDATA[time-complexity]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[counting-sort]]></category>
            <dc:creator><![CDATA[Dan Romans]]></dc:creator>
            <pubDate>Fri, 08 May 2020 23:07:37 GMT</pubDate>
            <atom:updated>2020-05-08T23:07:37.529Z</atom:updated>
            <content:encoded><![CDATA[<h3>Counting Sort: Why, When, &amp; How</h3><figure><img alt="Toby Flenderson from The Office." src="https://cdn-images-1.medium.com/max/1024/1*S2414hj3Ey3RoSLFCE1BMw.jpeg" /><figcaption>“Go back to the annex.”</figcaption></figure><p>Sorting is a near ubiquitous process in our daily lives. It makes sense to organize things to better use them. The same can be said for data. In computer programming—and mathematics, for that matter—sorting algorithms are frequently used to order data as needed to perform a calculation, feed an engine, render an interface, etc.</p><p>There are several well known sorting algorithms: <em>e.g.</em> bubble, quick, selection, insertion, merge, heap, bucket. There is also a lesser known sorting algorithm, relegated to the proverbial annex like poor Toby: <a href="https://en.wikipedia.org/wiki/Counting_sort">counting sort</a>. Have you ever heard of it? It is infrequently used because it comes with some caveats which make it impractical in most use cases. However, if the stars align and the conditions are just right, counting sort offers a unique advantage: it is the only sorting algorithm which performs in linear time (O(n)).</p><p>Most sorting algorithms perform in quadratic time (O(n²)), and the two exceptions—heap and merge—maximize efficiency at linearithmic time (O(n log n)). Counting sort provides a rarely useable, but more performant algorithm. If the conditions allow, and time efficiency is a priority, counting sort can shine.</p><p>*<em>Note: linear time sorting can also be achieved with the </em><strong><em>best</em></strong><em> case scenario bucket sort (which is not a proper evaluation—time complexity considers the </em><strong><em>worst</em></strong><em> case scenario) and </em><a href="https://en.wikipedia.org/wiki/Radix_sort"><em>radix sort</em></a><em>, which itself utilizes counting sort as a sub-routine.</em></p><h4>Caveat #1: Positive Integers Only</h4><p>Unlike most other sorting algorithms, counting sort is not a <a href="https://en.wikipedia.org/wiki/Comparison_sort">comparison sort</a>. It is an <a href="https://en.wikipedia.org/wiki/Integer_sorting">integer sort</a>. The sorting is performed by using values concurrently as keys and indices. This requires a condition wherein the objects—the elements, or values—being sorted are exclusively integers, and, since they must be able to represent an Array index, they must be 0 or greater.</p><h4>Caveat #2: Lesser Values</h4><p>As the name suggests, counting sort utilizes a counting procedure. It is in the form of an auxiliary Array which stores the frequency count, <em>i.e.</em> number of occurrences, of each value. It is done by initializing an Array of 0s to accommodate the maximum input value. For example, if the input was the sequence 5 1 3, the count Array would need to accommodate an index 5, plus an additional element to represent the index 0.</p><pre>input =&gt; 5 1 3</pre><pre>count Array =&gt; </pre><pre>idx  0  1  2  3  4  5<br>______________________<br>arr [0, 0, 0, 0, 0, 0]</pre><p>This condition requires that the maximum value of the integers being sorted is a relatively small number. The need to create an auxiliary Array comes at the cost of space, and if the maximum input value is great, then the space complexity of the algorithm would make it inefficient and, therefore, unusable.</p><p>I presume an acceptable maximum value is circumstantial, but once large numbers (1000+?) enter the mix, consider an alternative algorithm. Note that the specific time complexity of counting sort is O(n + k), wherein n is the length of the input, and k is the range of the input. It’s simpler to think of k, the range, as the maximum value of the input.</p><h4>Algorithm: In JavaScript</h4><p>There are numerous variations of the counting sort algorithm. I’m going to share one that I wrote. It’s possibly not <em>the</em> best one, but it works and is rudimentary, understandable. Two commonalities that I’ve noticed in other examples are <strong>1)</strong> the need to know the minimum and maximum values to include as input, and <strong>2)</strong> the use of a while loop nested within a for loop. My variation allows for inputting only an Array of integers, and does not have nested loops. Perhaps a trade off considering my example has slightly “worse” space complexity, but it’s fun to try different things.</p><p><strong>Mechanics:</strong></p><pre><strong>function countingSort(arr) {</strong></pre><pre>// initialize count Array: 0 * (arr max value + 1(for index 0))</pre><pre>  <strong>const countArr = new Array(Math.max(...arr) + 1).fill(0)</strong></pre><pre>// initialize accumulation Array with one element: 0<br>// this will be used to store key values as an index legend</pre><pre>  <strong>const accumulationArr = [0]</strong></pre><pre>// initialize accumulator to aid construction of accumulation Array</pre><pre>  <strong>let accumulator = 0</strong></pre><pre>// initialize sorted Array for result: 0 * arr.length</pre><pre>  <strong>const sortedArr = new Array(arr.length).fill(0)</strong></pre><pre>// load the count Array by tracking occurrences <br>// of each unique value in the input Array</pre><pre>  // loop over elements of the input Array<br>  <strong>for (const i of arr) {</strong><br>    // access matching index of count Array and <br>    // increment the corresponding value by 1<br> <strong>   countArr[i]++<br>  }</strong></pre><pre>// load the accumulation Array by accumulatively adding <br>// the values of the count Array, in sequence, to create <br>// an index legend for the pending sorting procedure<br>// note that the accumulation Array already contains the <br>// value 0 at index 0, and the loop stops before the last <br>// accumulation as it is not needed for calculations</pre><pre>  <strong>for (let i = 0; i &lt; countArr.length - 1; i++) {</strong><br>    // the accumulator is assigned the value of the first element<br>    // of the count Array on the first iteration, then on, the <br>    // accumulative value of previous elements + current element<br>    <strong>accumulator += countArr[i]<br>    </strong>// the current accumulator value is added to <br>    // the accumulation Array<br>    <strong>accumulationArr.push(accumulator)<br>  }</strong></pre><pre>// load the sorted result Array by looping over the input Array,<br>// using the current element to access an index from the<br>// accumulation Array, accessing that index in the sorted Array <br>// and assigning it the value of the current element</pre><pre><strong>for (let i = 0; i &lt; arr.length; i++) {<br>   </strong> // assign the index variable the value from the <br>    // accumulation Array at [index = current element]<br>    <strong>let index = accumulationArr[arr[i]]<br>    </strong>// use the index variable to assign value from input Array<br>    // to correct position in sorted Array<strong><br>    sortedArr[index] = arr[i]</strong><br>    // increment the value from the accumulation Array <br>    // at [index = current element] by 1 to shift target index<br>    // by 1 to accommodate pending repeated input values<br>    <strong>accumulationArr[arr[i]]++</strong><br>  <strong>}</strong></pre><pre>// output the sorted result Array</pre><pre><strong>  console.log(sortedArr)<br>  return sortedArr<br>}</strong></pre><p><strong>Example:</strong></p><pre>// input<strong><br>const arr = [5, 1, 4, 4, 3, 2]</strong></pre><pre>// function<strong><br>function countingSort(arr) {<br>  const countArr = new Array(Math.max(...arr) + 1).fill(0)<br> </strong>   // countArr =&gt; [0, 0, 0, 0, 0, 0]</pre><pre><strong>  const accumulationArr = [0]<br>    </strong>// accumulationArr =&gt; [0]</pre><pre><strong>  let accumulator = 0<br>    </strong>// accumulator =&gt; 0</pre><pre><strong>  const sortedArr = new Array(arr.length).fill(0)<br>    </strong>// sortedArr =&gt; [0, 0, 0 ,0, 0, 0]</pre><pre><strong>  for (const i of arr) {</strong><br> <strong>   countArr[i]++<br>  }<br>    </strong>// countArr =&gt; [0, 1, 1, 1, 2, 1]</pre><pre>////// explanation /////////////////////////////////////////////////<br>       ————————————————————————————————————————————<br>           input | 5 1 4 4 3 2 |<br>       ____________________________________________<br>        countArr | 0 1 2 3 4 5 | (indices)<br>       ____________________________________________<br>          loop 1 | 0 0 0 0 0 1 | 1 occurrence of 5<br>          loop 2 | 0 1 0 0 0 1 | 1 occurrence of 1<br>          loop 3 | 0 1 0 0 1 1 | 1 occurrence of 4<br>          loop 4 | 0 1 0 0 2 1 | <strong>2</strong> occurrence of 4<br>          loop 5 | 0 1 0 1 2 1 | 1 occurrence of 3<br>          loop 6 | 0 1 1 1 2 1 | 1 occurrence of 2</pre><pre><strong>  for (let i = 0; i &lt; countArr.length - 1; i++) {</strong><br>    <strong>accumulator += countArr[i]<br>    accumulationArr.push(accumulator)<br>  }<br>  </strong>// accumulationArr = [0, 0, 1, 2, 3, 5]</pre><pre>////// explanation /////////////////////////////////////////////////<br>       _______________________________________________<br>        loop 1 | countArr = [<strong>0,</strong> 1, 1, 1, 2, 1,]<br>               | accumulator = 0 + <strong>0</strong><br>               | accumulationArr = [0, <strong>0</strong>]<br>       ——————————————————————————————————————————————— <br>        loop 2 | countArr = [0<strong>,</strong> <strong>1</strong>, 1, 1, 2, 1,]         <br>               | accumulator = 0 + <strong>1</strong><br>               | accumulationArr = [0, 0, <strong>1</strong>]<br>       ———————————————————————————————————————————————<br>        loop 3 | countArr = [0<strong>,</strong> 1, <strong>1</strong>, 1, 2, 1,]<br>               | accumulator = 1 + <strong>1</strong><br>               | accumulationArr = [0, 0, 1, <strong>2</strong>]<br>       ———————————————————————————————————————————————<br>        loop 4 | countArr = [0<strong>,</strong> 1, 1, <strong>1</strong>, 2, 1,]<br>               | accumulator = 2 + <strong>1</strong><br>               | accumulationArr = [0, 0, 1, 2, <strong>3</strong>]<br>       ———————————————————————————————————————————————<br>        loop 5 | countArr = [0<strong>,</strong> 1, 1, 1, <strong>2</strong>, 1,]<br>               | accumulator = 3 + <strong>2</strong><br>               | accumulationArr = [0, 0, 1, 2, 3, <strong>5</strong>]</pre><pre><strong>  for (let i = 0; i &lt; arr.length; i++) {<br>    let index = accumulationArr[arr[i]]<br>    sortedArr[index] = arr[i]</strong><br>    <strong>accumulationArr[arr[i]]++</strong><br>  <strong>}</strong></pre><pre>////// explanation /////////////////////////////////////////////////<br>       ______________________________________________<br>        loop 1 | accumulationArr = [0, 0, 1, 2, 3, 5]<br>               | index = 5<br>               | sortedArr = [0, 0, 0, 0, 0, 5]<br>               | accumulationArr = [0, 0, 1, 2, 3, <strong>6</strong>]<br>       ————————————————————————————————————————————–– <br>        loop 2 | accumulationArr = [0, 0, 1, 2, 3, 6]<br>               | index = 0<br>               | sortedArr = [1, 0, 0, 0, 0, 5]<br>               | accumulationArr = [0, <strong>1</strong>, 1, 2, 3, 6]<br>       ————————————————————————————————————————————––<br>        loop 3 | accumulationArr = [0, 1, 1, 2, 3, 6]<br>               | index = 3<br>               | sortedArr = [1, 0, 0, 4, 0, 5]<br>               | accumulationArr = [0, 1, 1, 2, <strong>4</strong>, 6]<br>       ————————————————————————————————————————————––<br>        loop 4 | accumulationArr = [0, 1, 1, 2, 4, 6]<br>               | index = 4<br>               | sortedArr = [1, 0, 0, 4, 4, 5]<br>               | accumulationArr = [0, 1, 1, 2, <strong>5</strong>, 6]<br>       ————————————————————————————————————————————––<br>        loop 4 | accumulationArr = [0, 1, 1, 2, 5, 6]<br>               | index = 2<br>               | sortedArr = [1, 0, 3, 4, 4, 5]<br>               | accumulationArr = [0, 1, 1, <strong>3</strong>, 5, 6]<br>       ————————————————————————————————————————————––<br>        loop 4 | accumulationArr = [0, 1, 1, 3, 5, 6]<br>               | index = 1<br>               | sortedArr = [1, 2, 3, 4, 4, 5]<br>               | accumulationArr = [0, 1, <strong>2</strong>, 3, 5, 6]</pre><pre><strong>  console.log(sortedArr)<br>  return sortedArr<br>}</strong></pre><pre>// output<br>// sortedArr =&gt; [1, 2, 3, 4, 4, 5]</pre><p><strong>Solution:</strong></p><pre><strong>function countingSort(arr) {<br>  const countArr = new Array(Math.max(...arr) + 1).fill(0)<br> </strong> <strong>const accumulationArr = [0]<br>  let accumulator = 0<br>  const sortedArr = new Array(arr.length).fill(0)<br>  <br>  for (const i of arr) {</strong><br> <strong>   countArr[i]++<br>  }<br> <br>  for (let i = 0; i &lt; countArr.length - 1; i++) {</strong><br>    <strong>accumulator += countArr[i]<br>    accumulationArr.push(accumulator)<br>  }</strong></pre><pre><strong>  for (let i = 0; i &lt; arr.length; i++) {<br>    let index = accumulationArr[arr[i]]<br>    sortedArr[index] = arr[i]</strong><br>    <strong>accumulationArr[arr[i]]++</strong><br>  <strong>}</strong></pre><pre><strong>  console.log(sortedArr)<br>  return sortedArr<br>}</strong></pre><p>That’s a lot of text to take in, and there is still some ambiguity as to precisely why this works, but like a Stanley Kubrick or David Lynch film, this article is meant to present you with an introduction, a plot, and a finale—not the deeper meaning. While I’ve included ample demonstration, I encourage you to search around the internet and play around with counting sort to fully grasp the process to your own understanding. Everyone learns differently. At the very least, you have an overview, a foundation, and an example to study and use.</p><p><a href="https://github.com/dangrammer">github.com/dangrammer</a><br><a href="https://www.linkedin.com/in/danieljromans/">linked.com/in/danieljromans</a><br><a href="http://danromans.com/">danromans.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a10abdbbf45f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>