<?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 Carlos Pineda on Medium]]></title>
        <description><![CDATA[Stories by Carlos Pineda on Medium]]></description>
        <link>https://medium.com/@carlospineda?source=rss-ab5cbb591b0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*Me2Qgnrgj2_2o9ey3LyRYQ.jpeg</url>
            <title>Stories by Carlos Pineda on Medium</title>
            <link>https://medium.com/@carlospineda?source=rss-ab5cbb591b0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 06:14:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@carlospineda/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[Exploring Binary Search Trees]]></title>
            <link>https://medium.com/@carlospineda/exploring-binary-search-trees-f9249a82e824?source=rss-ab5cbb591b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9249a82e824</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[binary-search-tree]]></category>
            <dc:creator><![CDATA[Carlos Pineda]]></dc:creator>
            <pubDate>Sat, 30 May 2020 03:56:00 GMT</pubDate>
            <atom:updated>2020-05-30T03:56:00.343Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6hc2E3l64P0doQTI.png" /></figure><p>This week I learned about Binary Search Trees (BST)and I came across a particular problem that helped me understand the difference between the Breadth-First Search (BFS) and Depth-First Search (DFS) and how their implementation can be modified according to need.</p><p>The practice problems I worked on is “Kth smallest element in a BST” (https://leetcode.com/problems/kth-smallest-element-in-a-bst). The task is simple; find the specified element and return its value.. sounds simple enough…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/1*RVjW4TWiTxArUaWER930wA.png" /></figure><p>My first approach was using BFS (Breadth-First Search), keyword “breadth” — as in going across. This involves using a queue (will cover in a future blog post) to save all the nodes in the level below you currently are now before you add a particular node to an array to return at the end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*TMfn6Q8fPEmzRizOy5GTUg.png" /></figure><p>The second approach is DFS (Depth-First Search), keyword “depth” — as in going down. This involves you going down the tree (typically left to right) and recording the node in an array as either before, in the middle or after you pass its child nodes (one level below). These three variations are knowns as “Pre Order”, “In Order” and “Post Order”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/0*vQ0bmc4EBYRwH1zS.png" /><figcaption>3 types of DFS</figcaption></figure><p>As you can see, each one will return nodes in a different order and each have its own uses. For example, if you want to print all nodes from top to bottom, you go with Pre Order, and if you want to print them bottom to top, you go Post Order, and from left to right, then you go with In Order.</p><pre>var kthSmallest = function(root, k) {<br>  let arr = []<br>  let queue = [root]<br>  let node</pre><pre>  while(queue.length){<br>    node = queue.shift()<br>    if(node.left) queue.push(node.left)<br>    if(node.right) queue.push(node.right)<br>    arr.push(node.val)<br>  }</pre><pre>  arr.sort((a,b) =&gt; a-b)</pre><pre>  return arr[k-1]</pre><pre>}</pre><p>For this particular question I started with BFS to record all nodes into an array, then sort them and return the k minus 1 element. This worked, but definitely not the optimal solution.</p><pre>var kthSmallest = function(root, k) {<br>  let arr = []</pre><pre>  function traverse(node){<br>    arr.push(node.val)<br>    if(node.left) traverse(node.left)<br>    if(node.right) traverse(node.right)<br>  }</pre><pre>  traverse(root)</pre><pre>  arr.sort((a,b) =&gt; a-b)</pre><pre>  return arr[k-1]<br>}</pre><p>Next I tried DFS pre-order and I sorted the array and returned the k minus 1st element. Although a bit more efficient without the need for a queue, I still found myself having to sort my array, which didn’t feel right. Then I realized one fundamental thing about BTS’s: if you travers DFS in order (prints node after left child and before right child), they print all nodes in ascending order (smallest to largest value) because in a BTS each left child of a node is a lower value than the parent node value, and the right value is always higher than the node value.</p><pre>var kthSmallest = function(root, k) {<br>  let arr = []</pre><pre>  function traverse(node){<br>    arr.push(node.val)<br>    if(node.left) traverse(node.left)<br>    if(node.right) traverse(node.right)<br>  }</pre><pre>  traverse(root)</pre><pre>  return arr[k-1]<br>}</pre><p>DFS in order allowed me to record each node value in ascending order and I could just return the k minus first element without having to sort it at the end. Then I realized something… maybe I can remove the need for an array altogether…🤔</p><pre>var kthSmallest = function(root, k) {<br>  let counter = 0<br>  let ans = root<br>  <br>  function traverse(node){<br>    if(node.left) traverse(node.left)<br>    counter++<br>    if(counter === k) ans = node<br>    if(counter&gt;=k) return<br>    if(node.right) traverse(node.right)<br>  }</pre><pre>  traverse(root)</pre><pre>  return ans.val</pre><pre>}</pre><p>By creating a counter I can keep track of which node I need to stop at, at soon as my counter reaches k, save the node I’m at and exit the recursive function and return the value of that node. I’d consider this the optimal solution for this problem.</p><p>My main takeaway is to think about your solution to determine how to traverse a BTS. Your output, along with the size of the tree (longer vs wider) should dictate how you should traverse it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9249a82e824" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A lesson in the importance built-in methods]]></title>
            <link>https://medium.com/@carlospineda/a-lesson-in-the-importance-built-in-methods-b994632de84a?source=rss-ab5cbb591b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/b994632de84a</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Carlos Pineda]]></dc:creator>
            <pubDate>Sun, 24 May 2020 04:54:09 GMT</pubDate>
            <atom:updated>2020-05-24T04:54:09.575Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*eq-HrqMkUKzd13DsrdLSHg.png" /></figure><p>I recently started practicing algorithms with some friends on a new site binarysearch.io (allows you to create a room and invite people to join and code in your own tab and look at each others code after you solve it or 10mins) and I came across the question Autocomplete (<a href="https://binarysearch.io/question/11">https://binarysearch.io/question/11</a>), where you get a set of words and a string as your inputs. Your task is to return the words that could be what the user is looking for given the input string s.</p><p>After a little thought, I decided my approach was to combine looping with logic to come up with an answer and I came up with this:</p><pre>solve(s, words) {<br>  let resp = []<br>  let good<br>  for (let i = 0; i &lt; words.length; i++) {<br>    good = true<br>    for (let j = 0; j &lt; s.length; j ++) {<br>      if (s[j] !== words[i][j]) {<br>        good = false<br>      }<br>    }<br>    if (good) {<br>      resp.push(words[i])<br>    }<br>  }<br>  return resp;<br>}</pre><p>I realized I needed to return an array of the words that matched, and I had to loop through all words and loop through each letter comparing the letters of the input string “s” to see if it matched. I created an indicator that would switch to false as soon as a letter in the word didn’t match the letter in the input string, and if that indicator never switched to false, the words meets the criteria and is added to the array, once I’ve looped through all the words, I return the array of the words that meet the criteria.</p><p>Although this answer got the job done, I realized it was far from optimal and it was time for some refactoring. I started with that second for loop… if i could take that string, and piece out the portion whose length is the same as the input string, I can just check if they’re equal and add to my response array if true, therefore I took each work and split it into a string, sliced off a piece equal to the length of the input string, joined it back together to make a new string, and if that was equal to the input string, then Iadd the appropriate word to my response array</p><pre>solve(s, words) {<br>  let resp = []<br>  for(let i=0;i&lt;words.length; i++){<br>    if (words[i].split(&quot;&quot;).slice(0,s.length).join(&quot;&quot;) == s){<br>    resp.push(words[i])<br>    }<br>  }<br>  return resp<br>}</pre><p>As you can see, it looks nice when you can daisy chain the methods to one line. However, I realized that I split each word to an array just to slice a piece and convert back to an array and felt like there should be a built-in method to do all this… alas I found it: substr()</p><pre>solve(s, words) {<br>  let resp = []<br>  for(let i=0;i&lt;words.length; i++){<br>    if (words[i].substr(0,s.length) == s){<br>    resp.push(words[i])<br>    }<br>  }<br>  return resp<br>}</pre><p>I felt pretty good about this answer and stuck by it, until… I found out there was a built-in method that allows you to not only do this in faster time, but also use less memory by not having to create a blank array and push items to it… behold… startsWith()… this allows me to determine if a word qualifies or not, I can filter through the list of words and return a list of only those which qualify.</p><pre>solve(s, words) {<br>  return words.filter(word =&gt; word.startsWith(s))<br>}</pre><p>There you have it folks, a very clean one liner that easily and quickly solves what I tried to do originally in 14 lines of code. Knowing that one built-in method would’ve saved me an amount of time which I’m too embarrassed to admit…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b994632de84a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python basics]]></title>
            <link>https://medium.com/@carlospineda/python-basics-c221bb0ca54f?source=rss-ab5cbb591b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/c221bb0ca54f</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Carlos Pineda]]></dc:creator>
            <pubDate>Sat, 16 May 2020 03:01:41 GMT</pubDate>
            <atom:updated>2020-05-16T03:01:41.151Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_FEt7-VmIu5RhJ9K.png" /></figure><p>I recently decided to learn Python to add to my stack (JS, Ruby) given the popularity of the languages across many industries. I’m writing this in hope that it can help others who are learning python with some coding background (I know JS/Ruby).</p><pre># Strings</pre><pre>sentence = &#39;Hi i am a string&#39;<br>  type(sentence) # return &lt;class &#39;str&#39;&gt;</pre><p>Strings are pretty straight forward, just like any other language, you define them with single quotes (‘ ’) or double quotes (“ ”), unlike JS back ticks (` `) won’t work in python.</p><pre># Boolean</pre><pre>  boolean = True # type boolean<br>  type(boolean) # return &lt;class &#39;bool&#39;&gt;</pre><pre>  bool(100) # returns True<br>  bool(0) # returns False</pre><p>Booleans are also straight forward: True/False. For numbers, 0 is considered ‘falsy’ while any other number is ‘truthy’.</p><pre># Numeric</pre><pre>num = 1 # type int<br>  type(num) # return &lt;class &#39;int&#39;&gt;</pre><pre>num = 2.1 # type float<br>  type(num) # return &lt;class &#39;float&#39;&gt;</pre><p>Numbers can either be save as integers (whole numbers) or floats (decimals).</p><pre># Complex</pre><pre>num = 1j # type complex<br>  type(num) # &lt;class &#39;complex&#39;&gt;</pre><p>There’s also a “complex” type which is a combination of numbers and letters.</p><pre># Empty Variables (None type)</pre><pre>  var = None<br>  type(var) # return &lt;class &#39;NoneType&#39;&gt;</pre><p>“none” type which allows you to declare empty variables without having to define them.</p><p>There are three collection type of data structures: lists, tuples, sets.</p><ul><li>Lists: defined with square brackets [] these are arrays and built as as such</li><li>Tuple: defines with braces () similar to lists but they are immutable in nature</li><li>Set: defined with curly braces {} similar to lists but they only keep unique values</li></ul><p>Note: you can combine set and list methods to obtain the unique values of a list.</p><pre># List <br> <br>  this_list = [1,2,3] <br>  type(this_list) # return &lt;class &#39;list&#39;&gt;</pre><pre># Tuple</pre><pre>  this_tuple = (1,2,3) <br>  type(this_tuple) # return &lt;class &#39;tuple&#39;&gt;</pre><pre># Set</pre><pre>  this_set = {1,2,3} <br>  type(this_set) # return &lt;class &#39;set&#39;&gt;</pre><pre># Creating one collection from another</pre><pre>  collection = [4,1,2,3,3]<br>  tuple(collection) # return (4,1,2,3,3)<br>  set(collection) # return {1,2,3,4}</pre><pre># Obtain sorted unique list </pre><pre>  list(set(collection)) # return [1,2,3,4] (uniques values</pre><pre># slice numbers of elements (NOT INDEX)<br> <br>  collection[:2] # return [1,2]</pre><p>Dictionaries are just like JS objects and Ruby hashes with key/value pairs. They can be created hard coded or with keys from a list.</p><pre># Dictionary</pre><pre>   dictionary = {&quot;name&quot;: &quot;John&quot;, &quot;age&quot;: 30}<br>  type(dictionary) # return &lt;class &#39;dict&#39;&gt;</pre><pre># setup dict from array with keys for dict</pre><pre>  this_list = [4, 1, 3, 3]</pre><pre>  dict.fromkeys(this_list) # returns {4: None, 1: None, 3: None}<br>  dict.fromkeys(this_list,0) # returns {4: 0, 1: 0, 3: 0}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c221bb0ca54f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JS vs Python: Minimum distance algo]]></title>
            <link>https://medium.com/@carlospineda/js-vs-python-minimum-distance-algo-59ff5ef17324?source=rss-ab5cbb591b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/59ff5ef17324</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Carlos Pineda]]></dc:creator>
            <pubDate>Sun, 10 May 2020 03:11:52 GMT</pubDate>
            <atom:updated>2020-05-24T03:52:33.110Z</atom:updated>
            <content:encoded><![CDATA[<h3>JS vs Python: Solving for minimum distance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*U4VJvYY8Q1yT87P4.png" /></figure><p>As I start learning Python, I find it useful to compare it to a current language that in know already, in this case it’ll be Javascript. Once I learned the basics of Python variables, functions and if/else statements (check out this <a href="https://medium.com/@carlospineda/python-basics-c221bb0ca54f">blog</a> post for more on Python basics), the next step was to put it to use in a simple problem by solving it in Javascript and then code the same answer in Python to experiment with the differences in the syntax.</p><p>The problem is an easy one: determine the minimum distance between two duplicate elements of an array. Link to the Hackerrank problem here: <a href="https://www.hackerrank.com/challenges/minimum-distances/problem">https://www.hackerrank.com/challenges/minimum-distances/problem</a></p><pre>// Javascript solution<br>function minimumDistances(a) {<br>  let map = {}<br>  let results = []<br>  for (let i = 0; i&lt;a.length; i++){<br>    let num = a[i]<br>    if(map[num] &gt;= 0){<br>      results.push(i-map[num])<br>    }else{<br>      map[num] = i<br>    }<br>  }<br>  return results.length === 0? -1 : Math.min(...results)<br>}<br></pre><pre># Python solution<br>def minimumDistances(a):<br>  map = {}<br>  results = []<br>  i = 0                     <br>  for num in a:<br>    if str(num) in map:                 <br>      results.append(i-map[str(num)])   <br>    else:<br>      map[str(num)] = i<br>    i += 1                              <br>  return -1 if len(results) == 0 else min(results)</pre><p>Here are some differences I realized:</p><ol><li>Blocks of code:<br>- Javascript uses curly brackets {} (akin to most languages)<br>- Python uses tabs alignment to organize blocks of code (forces you to be organized with you tabs)</li><li>Declaring variables:<br>- Javascript requires variable type (Var/Let/Cons, check out this <a href="https://medium.com/@carlospineda/javascript-var-let-const-1b9489bbd703">blog</a> for specifics)<br>- Python doesn’t require variable type</li><li>For Loop:<br>- Javascript has 3 types of for loops (for, for..in, for..of )<br>- Python only has a for…in loop (you need to specify a counter outside loop, similar to a while loop in JS)</li><li>Array methods:<br>- Javascript has “push” method to add at the end<br>- Python has “append” method to add at the end</li><li>Array length:<br>- Javascript treats length as an attribute of the array<br>- Python offers a method to calculate length of a list</li><li>If/else statement condition:<br>- Javascript requires you to specify that 0 is a possible value<br>- Python allows you to check existence</li><li>Object/Dictionary referencing:<br>- Javascript allows you to dynamically check the number as a key <br>- Python requires you to convert the number to string to check as a key</li><li>Ternary:<br>- Javascript structure is [condition]? [result if true]:[result if false]<br>- Python structure is [result if true] if [condition] else [result if false]</li></ol><p>So far, it seems that Javascript is better when it comes to referencing information and carries attributes with complex data types (arrays/objects), where Python seems to be more organized/structured/consistent with calculations and referencing (e.g.: length, converting number to string, etc). I’ll be sharing more findings as my exploration into Python continues.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59ff5ef17324" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The importance of input manipulation]]></title>
            <link>https://medium.com/@carlospineda/the-importance-of-input-manipulation-26fe2b8addf1?source=rss-ab5cbb591b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/26fe2b8addf1</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Carlos Pineda]]></dc:creator>
            <pubDate>Sat, 02 May 2020 04:59:10 GMT</pubDate>
            <atom:updated>2020-05-02T21:01:27.509Z</atom:updated>
            <content:encoded><![CDATA[<h3>String to number and the importance of input manipulation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*ke2OwCZ5WEbPcCcx9FSTQQ.png" /></figure><p>This week I was working on a LeetCode problem in which I had to extract an integer from a string. Here’s the link to the problem: <a href="https://leetcode.com/problems/string-to-integer-atoi/">https://leetcode.com/problems/string-to-integer-atoi/</a></p><p>Your input is a string composed of numbers, strings, and spaces and you have to take the sting, ignore the spaces and numbers and only take out the first number in the string, but if the first character is a letter, or if there aren’t any numbers (only spaces) then you return 0. Also, if the number is above above or below a predetermined max/min, replace that number with the max/min.</p><p>My approach was to put together logic to check each character in the string and check whether it’s a number, special character, number or space, and act accordingly. One improvement was to create an array of numbers and symbols so I can check whether the current character was included in that list or not. As my code was failing each test, I found myself adding more logic to cover that situation. I continued this trial and error cycle until I solved for all cases and this was my code:</p><pre>var myAtoi = function(str) {</pre><pre> let symbol = [&#39;+&#39;,&#39;-&#39;]<br> let number = [&#39;1&#39;,&#39;2&#39;,&#39;3&#39;,&#39;4&#39;,&#39;5&#39;,&#39;6&#39;,&#39;7&#39;,&#39;8&#39;,&#39;9&#39;,&#39;0&#39;]<br> let arr = []</pre><pre> if(!str.length){<br>  return 0<br> }</pre><pre> for (let i = 0; i&lt;str.length; i++){<br> let curr = str[i]<br> let next = str[i+1]</pre><pre> if (number.includes(curr)){<br>   arr.push(curr)<br> }else if(symbol.includes(curr) &amp;&amp; number.includes(next)){<br>   arr.push(curr)<br> }else if(curr === &#39;.&#39;){<br>   if (!arr.length){<br>    arr.push(&#39;0.&#39;)<br>   }else{<br>    arr.push(curr)<br>   }<br> }else if(curr === &#39; &#39;){<br>   if(arr.length){<br>    str = &#39;&#39;<br>   }else{<br>    null<br>   }<br> }else{<br>   if(!arr.length){<br>    return 0<br>   }else{<br>    str = &#39;&#39;<br>   }<br>  }<br> }</pre><pre> if(!arr.length){<br>  return 0<br> }</pre><pre> let min = Math.pow(-2,31)<br> let max = Math.pow(2,31)-1<br> let num = parseInt(arr.join(&#39;&#39;))</pre><pre> num = Math.min(num,max)<br> num = Math.max(num,min)<br> return num<br>}</pre><p>Even though my code sufficed all test cases, I realized it was very long and complex. After doing some research, I realized one important concept: manipulate that data before applying logic to it. In this particular case, the fact that spaces are not important and separate each section of characters and I only need to evaluate the first section. Therefore if you split up the string by spaces and just take the first segment and apply logic to that.</p><pre>var myAtoi = function(str) {<br> let firstSegment = str.trim().split(&#39; &#39;)[0]<br> let num = parseInt(firstSegment)</pre><pre> if(!num/1){<br>  return 0<br> }</pre><pre> num = Math.min(num,Math.pow(2,31)-1)<br> num = Math.max(num,Math.pow(-2,31))<br> return num<br>}</pre><p>Notice that after I separated the sting and take he first segment, I just had to check whether the segment is a number, if its not then return 0, otherwise return the number, and run it past the max/min accordingly. Manipulating the input before evaluating it with logic allowed me to considerably condense my code to be able to run more efficiently. Although the time complexity is still O(n), its much simpler and easier to read and debug (not to mention is makes me look smarter 😬 ).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26fe2b8addf1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Stacks in JavaScript]]></title>
            <link>https://medium.com/@carlospineda/implementing-stacks-in-javascript-703061f5ff60?source=rss-ab5cbb591b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/703061f5ff60</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[stack]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Carlos Pineda]]></dc:creator>
            <pubDate>Wed, 22 Apr 2020 03:36:27 GMT</pubDate>
            <atom:updated>2020-04-22T03:36:27.580Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*WWvnvVT-XCoaLKrB.jpg" /></figure><p>One type of data structure you can use when solving algorithms is a stack. A stack is a linear structure where adding or removing of an element follows a particular order: LIFO (Last In First Out) or FILO (First In Last Out).</p><p>I’ll be using a sample problem from LeetCode called <a href="https://leetcode.com/problems/valid-parentheses">Valid Parentheses</a></p><p>In this problem you receive a string of characters that can only be “()”,”[]”,”{}”, and you must create an algorithm to check if the string is valid (i.e. all openings are closed) and it gives you examples of what qualifies asa a a valid string as well as sample inputs with appropriate outputs.</p><p>My thought process to go about this was to check every character starting form the beginning and add it to a data structure if its an opening (<br>“(“ , ”[“ ,”{“) and if its a close closing ( “)”, “]”, “}”) check to see if the last item in my data structure is the corresponding opening, and if it is, remove that character from my data structure. If none of these conditions are met, return “false” as the closing does not match the latest opening, therefore not a valid string, and if at the end of the string, my data structure is empty, then return “true” because all the openings have been closed, otherwise false because there was an opening left unclosed.</p><p>I realized that a data structure that fits this well is a stack (since I’ll need LIFO method for adding/removing). The two ways I learned to implement them are by creating a Stack class (I call this for “formal” way) or using an array (I call this the “informal” way). Although simply using an array is much easier, I included the “formal” way in case you need to implement it in a tougher problem.</p><ol><li>Creating a Stack class</li></ol><pre>class Stack {<br>  constructor () {<br>    this.head = null;<br>    this.tail = null;<br>    this.length = 0;<br>    this.data = []<br>  }<br>  push(element){<br>    this.data.push(element)<br>  }<br>  pop(){<br>    if (this.data.length == 0){<br>        return false<br>    }else{<br>        this.data.pop()    <br>    }<br>  }<br>  peek(){<br>    return this.data[this.data.length-1]<br>  }<br>  isEmpty(){<br>    return this.data.length == 0<br>  }<br>}</pre><p>For this method you create a class and name is Stack, in the constructor you declare the initial values for the class and you declare the helper methods you’ll need, in this case it’ll be push (to add item),pop (to remove item),peek(to see last item), and isEmpty(to see if the stack is empty. With this you can implement the solution below</p><pre>var isValid = function(s) {<br>  <br>  let stack = new Stack</pre><pre>for (let i=0; i &lt; s.length; i++){ <br>    if (s[i] === &quot;(&quot; || s[i] === &quot;[&quot; || s[i] === &quot;{&quot;){<br>        stack.push(s[i])<br>      } else if (s[i] === &quot;)&quot; &amp;&amp; stack.peek() === &quot;(&quot;){<br>          stack.pop()<br>      } else if (s[i] === &quot;]&quot; &amp;&amp; stack.peek() === &quot;[&quot;){<br>          stack.pop()<br>      } else if (s[i] === &quot;}&quot; &amp;&amp; stack.peek() === &quot;{&quot;){<br>          stack.pop()<br>      } else{<br>          return false<br>      }<br>  }<br>  return stack.isEmpty()<br>}</pre><p>Notice how I create a new instance of the “Stack” class and assigning it to a variable “stack”. This will allow me to use the helper methods on the stack as needed (push to add any openings, peek to check the last item in my stack, pop to remove the last item, isEmpty to check if the stack is left empty after we iterate through the string).</p><p>Note to self — I just realized that instead of “peek”, I could’ve named the helper method “last” or something similar for clarity.</p><p>By now you probably noticed that I created an entire class for one instance, which creates an array, to use helper methods that would’ve worked directly on the array anyway (or have a simple work around). This is why I ended up using the second method: simply using an array.</p><p>2. Using an array</p><p>For this method I avoid the class all together and simply assign an array as my stack:</p><pre>var isValid = function(s) {<br>    <br>    let stack = []<br>    <br>    for (let i=0; i &lt; s.length; i++){ <br>        if (s[i] === &quot;(&quot; || s[i] === &quot;[&quot;|| s[i] === &quot;{&quot;){<br>            stack.push(s[i])<br>         } else if (s[i] === &quot;)&quot;  &amp;&amp; stack[stack.length-1] === &quot;(&quot;){<br>             stack.pop()<br>         } else if (s[i] === &quot;]&quot; &amp;&amp; stack[stack.length-1] === &quot;[&quot;){<br>             stack.pop()<br>         } else if (s[i] === &quot;}&quot; &amp;&amp; stack[stack.length-1] === &quot;{&quot;){<br>             stack.pop()<br>         } else{<br>             return false<br>         }<br>    }<br>    return !stack.length<br>};</pre><p>Notice how push and pop remain unchanged, and instead of peek I simply search directly for the last item in the array, and instead of isEmpty I check if the length is 0 (<a href="https://developer.mozilla.org/en-US/docs/Glossary/Falsy">falsy</a>) or not (<a href="https://developer.mozilla.org/en/docs/Glossary/Truthy">truthy</a>) and return the opposite since length of 0 means the string is valid(all openings are properly closed).</p><p>While this works just fine, it’s not very DRY (i.e. a lot of repeating) and not reusable (only fits that one specific situation), therefore I wanted to figure a way to dry it up a bit. I realized that all the openings have the same reaction (add to stack), therefore I created an array to group all the openings:</p><pre>var isValid = function(s) {<br>    <br>    let stack = []<br>    const openings = [&quot;(&quot;,&quot;[&quot;,&quot;{&quot;]<br>    <br>    for (let i=0; i &lt; s.length; i++){ <br>        if (openings.includes(s[i])){<br>            stack.push(s[i])<br>         } else if (s[i] == &quot;)&quot; &amp;&amp; stack[stack.length-1] === &quot;(&quot;){<br>             stack.pop()<br>         } else if (s[i] == &quot;]&quot; &amp;&amp; stack[stack.length-1] === &quot;[&quot;){<br>             stack.pop()<br>         } else if (s[i] == &quot;}&quot; &amp;&amp; stack[stack.length-1] === &quot;{&quot;){<br>             stack.pop()<br>         } else{<br>             return false<br>         }<br>    }<br>    return !stack.length<br>};</pre><p>Although this helps a bit, especially in the edge case that another opening is added, it doesn’t do anything to the closing. After some thinking I came up with this:</p><pre>var isValid = function(s) {<br>    <br>    const ref = {<br>      &#39;)&#39; : &#39;(&#39;,<br>      &#39;]&#39; : &#39;[&#39;,<br>      &#39;}&#39; : &#39;{&#39;,<br>    }<br>    <br>    const stack = []<br>    <br>    for (const char of s) {<br>        if (char in ref) {<br>            if (ref[char] === stack[stack.length - 1]) {<br>                stack.pop()<br>            } else {<br>                return false<br>            }<br>        } else {<br>            stack.push(char)<br>        }<br>    }<br>    return !stack.length<br>}</pre><p>Here is what I did:</p><ul><li>I created a reference object to save all the closings and their respective openings, this way if there are other pairs that need to be added, it can be done easily and the code will work</li><li>I used a “for of” loop since its optimized for arrays and strings</li><li>I switched the if statement around so I can search for the keys to check if the character is a closing and if the last item in the stack (array) is the appropriate opening, if not matched then returns false. If its not a key, it assumes it’s an opening and adds it to the stack (no need to check if its an opening).</li><li>I used “if(char in ref)” in order to search the key of the ref object. As opposed to creating an array of the keys and searching within that, this would increase time complexity to O(n²) (searching in an array within a string)</li></ul><p>I realized the above improvements sacrifices a bit of time, but the time complexity is still O(n) (linear time) and it needs more memory usage with the use of an object, but that’s negligible since space complexity is still O(n). However, the code is much cleaner and it allows for any number of opening and closing pairs.</p><p>Here’s an article that helped me understand this: <a href="https://www.geeksforgeeks.org/implementation-stack-javascript">https://www.geeksforgeeks.org/implementation-stack-javascript</a></p><p>If you need help visualizing how a stack works, check this site out: <a href="http://visualgo.net/en/list">http://visualgo.net/en/list</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=703061f5ff60" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[UNO gameplay logic in React.js with Redux]]></title>
            <link>https://medium.com/@carlospineda/uno-gameplay-logic-in-react-js-with-redux-1fdcb1c8ceac?source=rss-ab5cbb591b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fdcb1c8ceac</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[redux]]></category>
            <dc:creator><![CDATA[Carlos Pineda]]></dc:creator>
            <pubDate>Mon, 20 Apr 2020 03:55:23 GMT</pubDate>
            <atom:updated>2020-04-20T05:37:02.531Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BOiCMA1DUXmT6sft.png" /></figure><p>My most recent project called UNO-Y-MEDIO, it’s software version of UNO with a front end built with Javascript and React (Redux for state management). My first major challenge to tackle was to develop the gameplay logic, which I was really excited for.</p><p>Getting the game to accept a card of the same color or value was the easy part. The challenge was to manage the effect of the other cards: reverse, skip, plus 2, wild card, plus 4 wild. The way I went about this was to use the redux store to keep track of that status of the game and the main component (called table) to manage the actions based on changes in store. Before I could start, I created the store to track current turn, direction of play, color and value of the card played, a deck, a pile and 4 hands.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*HiofoSs5jCjRfwpTUtZ-Vw.png" /><figcaption>my default state in redux</figcaption></figure><p>Here’s how I went about each card effect:</p><p>The first two are underlying to the card effects, I created them to keep my code DRY</p><p>Next turn: reducer to determine who’s turn is next, while checking for to see if the value of the current card is skip or reverse, along with specifying that 1 is after 4 and vice-versa</p><p>Pick card: reducer to move the card at the top of the deck to your hand</p><p>Reverse: a reducer to switch the value for direction of play (clockwise true/false)</p><p>Skip: function calling two “next turn” reducers to jump the next player</p><p>Plus 2: function calling a “next turn” reducer, two “pick card”, and another “next turn” (since the next player also loses their turn)</p><p>Wild card: since this one involves the player choosing the next color, there’s logic to make render four buttons to choose the next color and click event attached to each button calls the function calling a reducer to change the color of the top card with a selected color, then “next turn”</p><p>Plus 4 wild: similar to “wild card”, only difference is that it includes four “pick card” reducers so the next player picks up the cards</p><p>One thing I still have to work on is daisy chaining Plus 2 and Plus 4 wild cards. More on that on a future blog post…</p><p>Link to the repo for the project: <a href="https://github.com/crpineda1/UNO-Y-MEDIO">https://github.com/crpineda1/UNO-Y-MEDIO</a></p><p>Take a look at the demo video of my project: <a href="https://youtu.be/ir_LneMIcbU">https://youtu.be/ir_LneMIcbU</a></p><p>Checkout the game at <a href="http://uno-y-medio.herokuapp.com/">http://uno-y-medio.herokuapp.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fdcb1c8ceac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Messing with animation in React.js]]></title>
            <link>https://medium.com/@carlospineda/messing-with-animation-in-react-js-ef156ebea275?source=rss-ab5cbb591b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef156ebea275</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-transition-group]]></category>
            <dc:creator><![CDATA[Carlos Pineda]]></dc:creator>
            <pubDate>Mon, 13 Apr 2020 03:42:44 GMT</pubDate>
            <atom:updated>2020-04-13T04:34:38.749Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*Y51XxW4JtmqRM_QtHr9sQw.png" /></figure><p>My most recent project called UNO-Y-MEDIO, it’s software version of UNO with a front end built with Javascript and React (Redux for state management). After developing the gameplay logic and the computer player to work with all 4 players (I talk about that in another <a href="https://medium.com/@carlospineda/figuring-out-computer-animation-in-javascript-87b03b91007">post</a>), my next challenge was to figure out the card animation.</p><p>From the beginning, one of my stretch goals was to develop animation for the cards where you can see the card go from the deck to the respective hand and from the hand to the pile when it’s played.</p><p>As you could imagine, I first tried regular CSS but that proved to only useful if you wanted what I call a “static” animation — animation that stays in place. Upon further research and help from my coaches at Flatiron, I came across a library called the React Transition Group. In a nutshell, the library allows you to specify certain CSS styling at any of the four transition states: entering, entered, exiting, exited.</p><p>Here’s a brief explanation of each transition state:</p><ul><li>entering: the stying you want applied before it mounts</li><li>entered: the styling you want applied after it mounts</li><li>exiting: the styling you want applied before it unmounts</li><li>exited: the styling you want applied after it unmounts</li></ul><p>For my project, I used the entered/exiting/exited states for the card to exit the deck and head to the particular hand, and to exit the hand to the pile. The actual movement of the cards was in the exiting state, the exited state was always opacity 0 to show that it had left, and entered state was opacity 1 to make the card appear in the new location after exiting the previous element.</p><p>Here’s the documentation for React Transition Group: <a href="http://reactcommunity.org/react-transition-group/transition">http://reactcommunity.org/react-transition-group/transition</a></p><p>The repo for my code is here: <a href="https://github.com/crpineda1/UNO-Y-MEDIO_frontend">https://github.com/crpineda1/UNO-Y-MEDIO_frontend</a></p><p>Here’s a demo video of my project: <a href="https://youtu.be/ir_LneMIcbU">https://youtu.be/ir_LneMIcbU</a></p><p>Checkout the game on Heroku: <a href="http://uno-y-medio.herokuapp.com/">http://uno-y-medio.herokuapp.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef156ebea275" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Figuring out computer animation in Javascript,]]></title>
            <link>https://medium.com/@carlospineda/figuring-out-computer-animation-in-javascript-87b03b91007?source=rss-ab5cbb591b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/87b03b91007</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Carlos Pineda]]></dc:creator>
            <pubDate>Mon, 06 Apr 2020 00:18:06 GMT</pubDate>
            <atom:updated>2020-04-13T03:01:21.548Z</atom:updated>
            <content:encoded><![CDATA[<h3>Figuring computer players in Javascript</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y51XxW4JtmqRM_QtHr9sQw.png" /></figure><p>My most recent project was to create a software version of UNO, with a front end built with Javascript and React (Redux for state management). I had developed the gameplay logic to work with human players and the next step was to create 4 computer players to play the game so the game could be played without humans. Upon creating the computer player logic, it would proceed to break the game every time.</p><p>I started by checking the computer player logic to make sure that it was looking for the right attributes, then proceeded to the game play logic. While troubleshooting the gameplay logic, I realized some logic (+2, +4, wildcard) was handled by functions in my main component, but others (skip, reverse, next turn) was handled in a reducer (Redux) and changing the turn automatically. Therefore I standardized it by having the reducers just handle updating store and the gameplay actions and switching turns to be handled by functions. However, I was still running into the problem of a player playing out of order.</p><p>After researching online, asking fellow students, consulting with my coaches, and multiple failed attempts. I realized that designing the game to have 4 computer players was fundamentally flawed and I redesigned my game to have only one computer player as a “ghost” (not appearing on the screen) to make a decision for the appropriate player only during their turn, allowing the game to be played autonomously.</p><p>Here’s a demo video of my project: <a href="https://youtu.be/ir_LneMIcbU">https://youtu.be/ir_LneMIcbU</a></p><p>Checkout the game at <a href="http://uno-y-medio.herokuapp.com/">http://uno-y-medio.herokuapp.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87b03b91007" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript: Var, Let, Const]]></title>
            <link>https://medium.com/@carlospineda/javascript-var-let-const-1b9489bbd703?source=rss-ab5cbb591b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b9489bbd703</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Carlos Pineda]]></dc:creator>
            <pubDate>Sun, 29 Mar 2020 23:07:09 GMT</pubDate>
            <atom:updated>2020-03-29T23:07:09.087Z</atom:updated>
            <content:encoded><![CDATA[<p>When I first started learning Javascript, I learned to use var to declare a variable and used it until I learned about let and const. Which led me to wonder the difference between the three. I learned that there are two aspects in which they differ: declaration/assignment and scope</p><p>Declaration/assignment:<br>When you declare a variable and assign it a value, the type you choose (or don’t choose) will depend on what you want to do with it later on.</p><ul><li>VAR — can be declared again and be assigned another value</li><li>LET —cannot be declared again, can be assigned another value</li><li>CONST — cannot be declared again, cannot be assigned another value</li></ul><p>Scope:<br>If you don’t quite understand scope yet, I suggest you read another blog post where I break it down quickly.</p><p><a href="https://medium.com/@carlospineda/computer-programming-scope-c116c7637c57">Computer Programming : Scope</a></p><ul><li>VAR — can be accessed anywhere in a functional , regardless if declared inside a block</li><li>LET — can only be accessed within the same block</li><li>CONST — can only be accessed within the same block</li></ul><p>Since their introduction with ES6, it’s generally a good idea to use Let and Const before Var. Although seeing Var is likely a sign pre-ES6 legacy code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b9489bbd703" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>