<?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 A**** ****** on Medium]]></title>
        <description><![CDATA[Stories by A**** ****** on Medium]]></description>
        <link>https://medium.com/@cyberdoggo?source=rss-c99e9686d8e1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*nUQ4g7elLcHaVi7Z.</url>
            <title>Stories by A**** ****** on Medium</title>
            <link>https://medium.com/@cyberdoggo?source=rss-c99e9686d8e1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 22:56:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cyberdoggo/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[Over the Wire: Bandit]]></title>
            <link>https://medium.com/cyberdoggo/over-the-wire-bandit-534299149d29?source=rss-c99e9686d8e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/534299149d29</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[terminal]]></category>
            <category><![CDATA[information-security]]></category>
            <category><![CDATA[bash]]></category>
            <category><![CDATA[infosec]]></category>
            <dc:creator><![CDATA[A**** ******]]></dc:creator>
            <pubDate>Mon, 23 Apr 2018 03:27:45 GMT</pubDate>
            <atom:updated>2018-04-23T03:27:45.353Z</atom:updated>
            <content:encoded><![CDATA[<h3>Over the Wire: Bandit Level 0–5</h3><h4>A.K.A. Command Line 101</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O9NqLQfpzkgypL-elh9qGA.png" /><figcaption>He’ll get ya!</figcaption></figure><p>While I was going to write a walkthrough on another Over the Wire war-game, I figured I might as well start from the beginning. Bandit is a great way to learn your way around using the command line, especially if you’re a former OSX fanboy like me. I recommend you do not look through the answers here until you have pounded your head into your desk and screamed some expletives loud enough for your neighbors to hear.</p><p>The main thing I want people to get from this walkthrough aren’t the actual specific solutions as there are thousands of other walkthroughs online for this pretty simple war-game. Instead, I want people to gain an intuition on how you should approach infosec war-games, whether they be reverse engineering challenges, web security challenges, or full attack-defense CTFs. The hardest part of hacking isn’t necessarily the technical aspects of it, but the process of gaining a creative mindset in learning how things work and how to make things well… break.</p><p>As always, I have to state that the solutions I provide may not be the most efficient solutions or the “right” solutions. They are simply just my solutions.</p><p>Let’s get started.</p><h4>Level 0</h4><p>Here we simply need to connect to Over the Wire’s Bandit server using <strong>SSH</strong>. What the hell is SSH and how do we do that? I’ll explain.</p><p>SSH stands for <strong>Secure Shell</strong>, most likely because naming a network protocol SS would have offended some people.</p><p>Network protocol? Aaaahhh! I know. It is truly a rabbit hole, but I’ll try to explain this without confusing you even more.</p><p>SSH is part of the Internet protocol suite, commonly referred to as just TCP/IP, named after the original two network protocols. Oh, by the way, a protocol in the computer sense just means the rules and conventions for communication between two or more network devices.</p><p>SSH is one those network protocols within TCP/IP that basically through some crypto mumbo jumbo allows us to securely log into a <strong>remote host</strong>, in this case Over the Wire’s server, and execute commands there. It also has plenty of other uses but we won’t go into those right now. If you’re still curious go onto Wikipedia and get lost for a couple hours. That might help, or you might just end up more confused.</p><p>Oh, you also need a SSH client. For people running OSX or any Unix based operating system, you’re good as it should be already installed on your system. Anyone running Windows will have to download a client. I don’t use Windows as I don’t use Steam anymore so you will have to figure out that out. That being said, I’ve heard <a href="https://www.chiark.greenend.org.uk/~sgtatham/putty/latest.html">PuTTY</a> is pretty good.</p><blockquote>Level Goal</blockquote><blockquote>The goal of this level is for you to log into the game using SSH. The host to which you need to connect is <strong>bandit.labs.overthewire.org</strong>, on port 2220. The username is <strong>bandit0</strong> and the password is <strong>bandit0</strong>. Once logged in, go to the <a href="http://overthewire.org/wargames/bandit/bandit1.html">Level 1</a> page to find out how to beat Level 1.</blockquote><p>Here’s how to do this through the command line:</p><pre>$ ssh -l bandit0 -p 2220 bandit.labs.overthewire.org</pre><p>We first type in the base command SSH like all commands. Then we specify the username by typing the flag “l” and the username, in this case in <strong>bandit0</strong>. Then we specify what port to use through the flag “p” and the port <strong>2220</strong>. Finally we specify what host we are connecting to, in this case the server <strong>bandit.labs.overthewire.org</strong>.</p><p>After hitting return, we will see the requirement for a password. Remember here the password is simply <strong>bandit0</strong>. We will want to modify this command later on but for now we can use this for next several levels, simply changing the username and the password.</p><h4>Bandit Level 0 → Level 1</h4><blockquote>Level Goal</blockquote><blockquote>The password for the next level is stored in a file called <strong>readme</strong> located in the home directory. Use this password to log into bandit1 using SSH. Whenever you find a password for a level, use SSH (on port 2220) to log into that level and continue the game.</blockquote><p>The two commands we will being using in this level are <strong>cat</strong> and <strong>ls</strong>.</p><p><strong>ls</strong> stands for list and its function when not flagged is to list the files and folders within the current directory.</p><pre>$ ls</pre><p>After you hit enter, it should return with this:</p><pre>readme</pre><p>While we wouldn’t necessarily know if <em>readme</em> is a file or folder off the information that is provided here, they already specified that readme is in fact the file that contains the password to the next level.</p><p>Now we just need to read <em>readme</em>. We can do this by using <strong>cat</strong>.</p><p>While there are many ways to display the contents of a file in a bash shell, “cat” is the easiest command to use. All we need to do here is type:</p><pre>$ cat readme</pre><p>Which gives us…</p><pre>boJ9jbbUNNfktd78OOpsqOltutMc3MY1</pre><p>the first password of the game.</p><p>Make sure to save your passwords in a little passwords.txt file in case you have to take a break or go outside like people do (ONLY DO THIS FOR THESE PASSWORDS AND NONE OF YOUR ACTUAL PASSWORDS).</p><p>If you want to learn more about a specific command, you can use the command “man” followed by your command. This will give you a manual and the more complex ways to use a command. Simply press q to exit.</p><h4>Bandit Level 1 → Level 2</h4><blockquote>Level Goal</blockquote><blockquote>The password for the next level is stored in a file called - located in the home directory</blockquote><p>We already know the required commands for this level, but now we need to figure out how to open “-”. The problem here though is that <strong>cat</strong> is recognizing the dash as synonym for stdin. In order to fix this we need to specify the dash is a file using a dot and a forward slash:</p><pre>$ cat ./-</pre><p>Personally I precede all my files with the dot and slash even if I’m in the same directory as the file I’m try to use. Here though, this format is required. Pressing enter should give us this:</p><pre>CV1DtqXWVFXTvM2F0k09SHz0YwRINYA9</pre><p>Second password done. It only gets harder.</p><h4>Bandit Level 2 → Level 3</h4><blockquote>Level Goal</blockquote><blockquote>The password for the next level is stored in a file called <strong>spaces in this filename</strong> located in the home directory</blockquote><p>Here once again we are going to use the same commands but we will have to extra careful to make sure cat reads the entire filename. On a side note, this is why you shouldn’t put spaces in file names or directory names.</p><p>If we simply enter</p><pre>$ cat spaces in this filename</pre><p>Cat only tries to read and display a file for every word in the phrase.</p><pre>cat: spaces: No such file or directory</pre><pre>cat: in: No such file or directory</pre><pre>cat: this: No such file or directory</pre><pre>cat: filename: No such file or directory</pre><p>To fix this, all we need to do is put our filename in quotes so that cat recognizes the entire phrase as our filename.</p><pre>$ cat &quot;spaces in this filename&quot;</pre><p>Which gives us…</p><pre>UmHadQclWmgdLOKQ3YNgjWxGoRMb5luK</pre><p>the next password!</p><p>Onto the next level.</p><h4>Bandit Level 3 → Level 4</h4><blockquote>Level Goal</blockquote><blockquote>The password for the next level is stored in a hidden file in the <strong>inhere</strong> directory.</blockquote><p>Hidden files? Whaaaaaaat?</p><p>No they’re not government secrets. Usually hidden files or hidden directories are usually hidden to avoid a dumb user from accidentally deleting something important. <em>something something delete system32</em></p><p>First though we have to figure out how to get into the <strong>inhere</strong> directory. After running our standard <strong>ls</strong>, you should see this:</p><pre>inhere</pre><p>Cool, now how do we get into the directory? We use a command called <strong>cd</strong>.</p><p>cd stands for “change directory” and to use it we simply type:</p><pre>$ cd inhere</pre><p>Now that we’re inside <strong>inhere</strong>, let’s just type ls again to find that hidden file.</p><p>But wait, we didn’t get anything?</p><p>What we have to do here is specify that we want to list <em>all</em> files in the current directory, hidden files included. To do this, we have to use the flag -a after ls:</p><pre>$ ls -a</pre><p>Which gives us:</p><pre>.  ..  .hidden</pre><p>Ignore the first two dots for now. We’ll get back to those eventually. Now all we have to do is use cat and display the contents of <strong>.hidden </strong>to the command line.</p><pre>$ cat .hidden</pre><p>Which gives us the next password.</p><pre>pIwrPrtPN36QITSp3EQaw936yaFoFgAB</pre><h4>Bandit Level 4 → Level 5</h4><blockquote>Level Goal</blockquote><blockquote>The password for the next level is stored in the only human-readable file in the <strong>inhere</strong> directory. Tip: if your terminal is messed up, try the “reset” command.</blockquote><p>In this level we’re going to use a new command called <strong>file</strong>.</p><p>File as a command determines the file type of a file. So for instance, I wanted to check the file type of doggo.txt. It doesn’t matter what it is in doggo.txt as all <strong>file</strong> cares about is the file type.</p><p>So if we ran:</p><pre>$ file doggo.txt</pre><p>It would return:</p><pre>file.txt: ASCII text</pre><p>Okay. This is good and it definitely puts us on the right track. While “human readable” is a very vague phrase, we can assume it means the file we are looking is some sort of readable file, even if we don’t know the actual character encoding.</p><p>However, in the example above we are only checking the file type of one file. While we could go and check the file type of each file within <strong>inhere</strong>, that’s a lot of work and we hackers like being as lazy as possible.</p><p>Here’s how to retrieve the file types of every file within <strong>inhere</strong>:</p><pre>$ file inhere/*</pre><p>Okay before you just copy this command, bear with me here for a second. That little asterisk at the end there is called a wildcard. There are couple different types of wildcards. Some wildcards only represent a single character, some represent a range of characters. They allow to search the directory for a specific pattern and, in this case, display the file type. Here, because we simply put it directly after the slash, it searches through every file.</p><p>For instance, say we have a directory called <strong>fruit</strong> containing the files:</p><pre>apple<br>banana<br>pear<br>pineapple<br>peach</pre><p>If wanted to return the file type of every file starting the letter p, I would type this:</p><pre>$ file inhere/p*<br>pear<br>pineapple<br>peach</pre><p>Here, the pattern now searches for every file starting the letter p and any letters after p.</p><p>Anyway, if that made sense, cool. If not, it’s alright. Remember Wikipedia is your friend.</p><p>So if you entered “file inhere/*” into the shell, you should have gotten this returned:</p><pre>inhere/-file03: data</pre><pre>inhere/-file04: data</pre><pre>inhere/-file01: data</pre><pre>inhere/-file07: ASCII text</pre><pre>inhere/-file08: data</pre><pre>inhere/-file06: data</pre><pre>inhere/-file02: data</pre><pre>inhere/-file09: data</pre><pre>inhere/-file05: data</pre><p>Okay, so right off the bat, what grabs our attention? The outlier -file07 with file type of ASCII text of course. ASCII isn’t the only character encoding system, but every other file type just says “data” so we can probably be sure that -file07 contains our honey. Recognizing what is an <strong>outlier</strong>, whether it be a certain file, port, or directory that just seems <strong>out of place </strong>is essential to solving war-games and finding vulnerabilities. This is the part of infosec that requires a lot of creative thinking, which allows happens to be my favorite aspect of infosec.</p><pre>$ cat ./inhere/-file07<br>koReBOKuIDDepwhWk7jZC0RTdopnAYKh</pre><p>Huh. Would you look at that.</p><p>The first five levels are done and you are officially on the path to becoming an infosec god. Play around with the command line and try your hand at the next levels. If you run into trouble, I’ll walk you through and explain it in the next post.</p><p>مع السلامة</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=534299149d29" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cyberdoggo/over-the-wire-bandit-534299149d29">Over the Wire: Bandit</a> was originally published in <a href="https://medium.com/cyberdoggo">cyberdoggo</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Luhn Algorithm in JavaScript, Python, & Clojure: Part 1]]></title>
            <link>https://medium.com/cyberdoggo/luhn-algorithm-in-javascript-python-clojure-part-1-c4ea3079d0f7?source=rss-c99e9686d8e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4ea3079d0f7</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[A**** ******]]></dc:creator>
            <pubDate>Thu, 12 Apr 2018 02:41:40 GMT</pubDate>
            <atom:updated>2018-04-12T17:03:12.573Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XMp3Um_ScAvQkgiXsbzFDw.jpeg" /><figcaption>The Big Man Himself: <strong>Hans Peter Luhn</strong></figcaption></figure><p>Over the past few months many of my friends at university have asked me for programming advice ranging from small questions about CS101 problem sets to asking for help on technical interview questions. Due to the fact that I’m unemployed and have become incredibly efficient at acing my online community college courses over the past few months, I agreed to help. One question that appeared multiple times across a wide variety of CS101-type courses was the famous <strong>Luhn algorithm</strong> implementation.</p><p>The Luhn algorithm is a simple checksum formula used mainly at this point to check if people enter their credit card number in right as it’s not too cryptographically secure. In fact, checksum algorithms by themselves are actually just used to detect errors in the transmission of data rather than actually verify the authenticity of data. For those interested in how data actually gets secured today, check out <strong>Bruce Schneier’s</strong> books or my new favorite, <em>Serious Cryptography</em>, by Jean-Philippe Aumasson.</p><p>Alright, for those who just want to submit their PSet in time, here are the steps to this formula.</p><p><strong>Given a sequence of digits:</strong></p><ol><li>Double every second digit, starting from the right.</li><li>If doubling the digit results in a number greater than 9, subtract 9 from the product</li><li>Find the sum all of the digits</li><li>If the sum is evenly divisible by 10, then the sequence / card number is valid.</li></ol><p>I want to approach this problem in a few ways using a couple different languages as per the title of this article in order to really illustrate what each language offers in terms of benefits while at the same time showing you how to think computationally beyond the box of a specific programming language.</p><h3>The Imperative Approach in JavaScript</h3><p>First I want to approach this problem imperatively (mostly) using JavaScript. This won’t give us the most “elegant” solution, but it will give us a solid foothold in tackling this problem. Before that though, let’s establish our two baseline test-cases. I encourage you to add more test-cases, especially edge cases that can break your program. I’m just using these for the sake of simplicity and brevity.</p><pre>isValid(&quot;4539148803436467&quot;) // true<br>isValid(&quot;8273123273520569&quot;) // false</pre><p>Now let’s implement the first version of our <strong>isValid()</strong> function, which will accomplish the goals of the algorithm stated above. First let’s setup our function and initialize the array we will use to store our digits before finding the sum of them.</p><pre>const isValid = n =&gt; {<br>  const arr = []<br>}</pre><p>Next let’s setup a <strong>for-loop</strong> to iterate through each digit in our “number,” which by the way is actually a string due to the fact that this data would most likely be received through user input.</p><pre>const isValid = n =&gt; {<br>  const arr = [];<br>  for (let i = 0; i &lt; n.length; i++) {<br>    // do something to the digits and add them each to arr<br>  }<br>  // return sum of arr<br>}</pre><p>The first thing we need to do is determine whether the digit we are looking at is an odd or even digit, or in the context of the array, whether the index <strong>i</strong> is odd or even. We can test this using an <strong>if-else</strong> statement to separate the actions we need to take in the case of an odd or even digit by testing for evenness using the modulo operator.</p><pre>const isValid = n =&gt; {<br>  const arr = [];<br>  for (let i = 0; i &lt; n.length; i++) {<br>    if (i % 2 == 0) {<br>      // double digit according to formula and add to arr<br>    } else {<br>      // add digit to arr<br>    }<br>  }<br>  // return sum of arr<br>}</pre><p>Now we need to create another <strong>if-else</strong> statement within our current <strong>if</strong> block in order to tackle the case of a doubled digit being larger than 9. Then if it is, we can subtract 9 from the digit and add it to the array. If the doubled digit is less than 10, we can simply add it the array. To add the digit to the array, we will use the <strong>push </strong>method as the <strong>const </strong>declaration makes <strong>arr</strong> a read only reference to the actual array, essentially making:</p><pre>arr +=</pre><p>Invalid. Now let’s just implement the second <strong>if-else</strong> expression.</p><pre>const isValid = n =&gt; {<br>  const arr = [];<br>  for (let i = 0; i &lt; n.length; i++) {<br>    if (i % 2 == 0) {<br>      if (card[i]*2 &lt; 10) {<br>        arr.push(card[i]*2)<br>      } else {<br>        arr.push(card[i]*2-9)<br>      }<br>    } else {<br>      // add digit to arr<br>    }<br>  }<br>  // return sum of arr<br>}</pre><p>It’s important to note that the reason I don’t have to explicitly convert each digit, which once again is really a character within a string, to a number is that JavaScript’s data <strong>type coercion</strong> does this for us. That being said, trusting JavaScript’s type coercion to always give you the values you want is a bad programming practice and can lead to some very disastrous outcomes. I’m just doing this to show an unique aspect of the language.</p><p>Now we just need to push each odd digit to the array. However, in this case if simply type:</p><pre>else {<br>  arr.push(card[i])<br>}</pre><p>JavaScript’s type coercion will actually not save us and a character / string will be pushed to the array instead of a number. To fix this, we need to explicitly convert the char to a number using the built in function <strong>parseInt().</strong></p><p>This function takes two arguments, a string and a radix, or base. In this case, we are using the common base 10 system so we just need to type:</p><pre>else {<br>  arr.push(parseInt(card[i],10))<br>}</pre><p>At this point, your program should look pretty close to this:</p><pre>const isValid = card =&gt; {<br>  const arr = []<br>  for (let i = 0; i &lt; card.length; i++) {<br>    if (i % 2 == 0) {<br>      if (card[i]*2 &lt; 10) {<br>        arr.push(card[i]*2);<br>      } else {<br>        arr.push(card[i]*2-9);<br>      }<br>    } else {<br>      arr.push(parseInt(card[i],10))<br>    }<br>  }<br>  // return sum of arr<br>}</pre><p>Now we just need to find the sum of <strong>arr</strong> and return it. When many people first start learning JavaScript, they create a sum function that looks something like this:</p><pre>function sumOfArr(arr) {<br>  var sum = 0;<br>  for (var i = 0; i &lt; arr.length; i++) {<br>    sum += arr[i]<br>  }<br>  return sum<br>}</pre><p>We could do something like that here in our program but let’s use something more efficient and cleaner. Let’s use the wonderful built-in array method <strong>reduce()</strong>.</p><p>This function allows us to apply a callback function against an accumulator across each value of an array. The accumulator here represents our sum, with our callback function body adding the current value to the sum as it iterates through the array. What we wrote above can now be condensed down to:</p><pre>arr.reduce( (prv, cur) =&gt; prv + cur)</pre><p>If you’re still confused on <strong>reduce</strong>, take a look through <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce">this</a>.</p><p>Now that we can find our sum we just need to check if it is divisible by 10 as per Luhn’s formula. We can do so using a modulo operator like this:</p><pre>arr.reduce( (prv, cur) =&gt; prv + cur) % 10 === 0</pre><p>To put it all together:</p><pre>const isValid = card =&gt; {<br>  const arr = []<br>  for (let i = 0; i &lt; card.length; i++) {<br>    if (i % 2 == 0) {<br>      if (card[i]*2 &lt; 10) {<br>        arr.push(card[i]*2);<br>      } else {<br>        arr.push(card[i]*2-9);<br>      }<br>    } else {<br>      arr.push(parseInt(card[i],10))<br>    }<br>  }<br>  return arr.reduce( (prv, cur) =&gt; prv + cur) % 10 === 0;<br>}</pre><p>This program works but I want to show you a more elegant and efficient solution that makes use of some more built-in array methods, a helper function, and different way of writing <strong>if-else</strong> statements.</p><h3>The Functional(ish) Approach in JS</h3><p>This is going to be our final result:</p><pre>const calc = e =&gt; (e*2 &lt; 10) ? e*2 : e*2-9;</pre><pre>const isValid = card =&gt; {<br>  return card.split(&quot;&quot;)<br>  .map( (e,i) =&gt; (i % 2 == 0) ? calc(e): parseInt(e))<br>  .reduce( (prv, cur) =&gt; prv + cur) % 10 == 0<br>}</pre><p>This probably looks like gibberish for the most part and that’s okay right now. Before I go into the nitty gritty of explaining each block of code, I want to explain how I approached writing this solution over the first solution. The first thing I did here was notice the calculation required for even digits. It’s a somewhat complex calculation at least compared to the odd digit calculation, which simply just returns the digit to the array. While the helper function, <strong>calc()</strong>, wasn’t essential, especially given how small this problem is compared to the some more difficult programming problems and even code infrastructures you might work on later, building these habits of simplifying problems down to their essential required calculations is an excellent habit to start now.</p><p>Now as to the array methods used here, once again I used .<strong>reduce()</strong> to calculate the sum of the array but this time I created our array by actually splitting our string argument into an array of characters using <strong>.split()</strong>. I then applied the built-in array method <strong>.map() </strong>to iterate through our newly created array of characters, which is actually what <strong>.split() </strong>returns here, and perform the necessary calculations. The .<strong>map() </strong>function return a new array with the results of a callback function being applied across every element of the array. The callback function also takes more optional arguments beyond the required current value argument like the current index argument. The current index argument here is <strong>i </strong>while the current value argument is <strong>e</strong>. The functions <strong>.map()</strong> and <strong>.split()</strong> are essentially accomplishing the task of the <strong>for-loop</strong> in our first program in a more elegant solution by using the built-in array methods JavaScript gives us.</p><p>Finally, I used a ternary operator.</p><pre>(test case) ? returnValueIfTrue : returnValueIfFalse</pre><p>I used this in order to fill the role of our previous if-else statements. Left of the question marks represents our conditional test, while the left of the colon represents the <strong>if</strong> block and the right of the colon represents the <strong>else </strong>block. Despite these comparisons, the ternary operator is not the same thing as an <strong>if-else</strong> statement as is actually closer to the logical operators. In fact, the ternary operator is the only operator that takes three operands.</p><p>This code is okay, but in many ways it’s still inefficient. Before moving onto the final approach, take a second to try to implement a more efficient solution.</p><h3>The Final JavaScript Approach</h3><p>I want to take one more time to use JavaScript to solve this problem in order to illustrate how we can simplify our program even further. Once again I will show the final result as I did before and then explain my thought process:</p><pre>const calc = e =&gt; (e*2 &lt; 10) ? e*2 : e*2-9;</pre><pre>const bestValid = card =&gt; card.split(&quot;&quot;).reduce( (sum, cur, i) =&gt; {<br>  return i % 2 == 0 ? calc(cur): parseInt(cur) + sum<br>},0) % 10 == 0;</pre><p>So what did I do that was different compared to our to previous versions of this program?</p><p>I combined the process of calculating the digits and summing them at the same time, overall making it more efficient and in my opinion, simpler to understand. The array uses the same .<strong>calc()</strong> helper function as before but I removed the .<strong>map()</strong> and instead performed the digit calculation during the summation process in <strong>.reduce()</strong>. One thing to note is that I put a zero after the end of our callback function within .<strong>reduce()</strong>. The reason for this is that <strong>.reduce()</strong> with just a callback function will return an error if the array it is being applied to is empty as it will not have any value to return. To deal with this case, I put a starting value of zero to prevent this potential bug.</p><p>This program is still not perfect. For instance, it doesn’t take into account of potential whitespace between groups of digits nor does properly notify a user if the input is incorrectly entered. In fact, it doesn’t even have a user input function at the moment as we’ve simply given our test cases within the arguments of isValid. However, this does not necessarily mean we need to create a gigantic function, but rather we simply need to create a separate input function that checks for whitespace and notifies the user in case of bad input along with another main function that can tie the input function and <strong>isValid</strong> function together.</p><h4>Moving Forward</h4><p>By creating small and <strong>pure</strong> functions with clear and <strong>specific</strong> purposes, we can start to approach problems like a functional programmer.</p><p>In the next part of this article, I want to go over how can solve this problem using Clojure, a truly functional programming language and really explain what that means beyond “little pure functions” and “lots of array methods.” Then we’ll take one more shot at this problem using Python and some its respective benefits, which include a wonderful piece of magic called <strong>list comprehensions</strong>.</p><p>Leave a comment if you find something confusing or even want to correct me on something. See you soon.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4ea3079d0f7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cyberdoggo/luhn-algorithm-in-javascript-python-clojure-part-1-c4ea3079d0f7">Luhn Algorithm in JavaScript, Python, &amp; Clojure: Part 1</a> was originally published in <a href="https://medium.com/cyberdoggo">cyberdoggo</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MIT 6.00.1x: Problem Set 1]]></title>
            <link>https://medium.com/cyberdoggo/mit-6-00-1x-problem-set-1-c5ba79ae2aad?source=rss-c99e9686d8e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5ba79ae2aad</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[A**** ******]]></dc:creator>
            <pubDate>Sat, 07 Oct 2017 20:39:20 GMT</pubDate>
            <atom:updated>2018-04-12T02:44:06.081Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introduction to Computer Science and Programming Using Python</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*omz7F9SAvpuyX_MVZT-dxw.png" /></figure><p>Let’s get down to business. This first problem set is composed of three short programming challenges. The first two are fairly easy but the third one will probably require some thinking even for those with programming experience. I do not have any programming experience. Here’s how I did it:</p><p><strong>Warning</strong>: my solutions are not the best solutions or the “right” solutions. They are simply <strong>my</strong><em> </em>solutions.</p><h4>Problem 1</h4><blockquote><em>Assume </em><em>s is a string of lower case characters.</em></blockquote><blockquote><em>Write a program that counts up the number of vowels contained in the string </em><em>s. Valid vowels are: &#39;</em><em>a&#39;, &#39;</em><em>e&#39;, &#39;</em><em>i&#39;, &#39;</em><em>o&#39;, and &#39;</em><em>u&#39;. For example, if </em><em>s = &#39;azcbobobegghakl&#39;, your program should print:</em></blockquote><blockquote>Number of vowels: 5</blockquote><p>This problem is basically just to check you know the basic concepts of conditional statements. Python, like many programming languages, allows you to create <strong>if-else </strong>expressions that perform certain computations depending on whether a Boolean condition evaluates to <em>True</em> or <em>False</em>.</p><p>Lets say I want to create a program that prints out whether an ice cream store has ice cream in stock.</p><p>First we define a variable called iceCreamAvailable and set it to True.</p><pre>iceCreamAvailable = True</pre><p>One cool thing about Python is that you don’t have specify a data type preceding your variable declaration. Whether we set our variable to a Boolean value, an integer, a float, or a string, we would simply just need to change the value right of the equal sign. Some programming languages on the other hand like C don’t even have a built-in Boolean data type (<em>C is still awesome</em>).</p><p>The next part of our program is setting up our if-else expression to run depending on whether <strong>iceCreamAvailable</strong> is equal to true or false.</p><pre>if iceCreamAvailable == True:<br>    # print statement 1<br>else:<br>    # print statement 2</pre><p>If the value of iceCreamAvailable is equal to true here, we will then print statement 1. If iceCreamAvailable evaluates to any other value, it will print statement 2. If I wanted to be more specific for statement 2, I could have used an <strong>elif </strong>statement like this:</p><pre>elif iceCreamAvailable == False:<br>   # print statement 2</pre><p>Due to the fact that the Boolean data type can only evaluate to two values though, the elif is unnecessary. In fact, here I could even remove the double equals sign as <strong>if statements automatically evaluate any non-zero and non-null values as True.</strong></p><pre>if iceCreamAvailable: <br>   # print statement 1</pre><p>This just makes our a code a little bit more concise and easier to read. I like it.</p><p>Finally for our little example program, we want to print our statements. To do this we will use the built in function <strong>print</strong>. If you’re a complete beginner you probably don’t know what a function is yet. If you weren’t asleep in high school algebra though, you probably have a vague idea of what one is. Basically print just takes in an argument, and prints or outputs it to the shell. This is our first glimpse into the concept of input and output or as nerds call it: <strong>IO</strong>.</p><p>For instance:</p><pre>print(&quot;Hello doggo&quot;)</pre><p>Would print out to the shell:</p><pre>Hello doggo</pre><p>So now our entire iceCream program would look a little like this:</p><pre>iceCreamAvailable = True</pre><pre>if iceCreamAvailable:<br>    print(&quot;Come get some ice cream!&quot;<br>else:<br>    print(&quot;We&#39;re all out!&quot;)</pre><p>So let’s get back to our first problem. It’s really not that different from our example program we just made. The only difference is here we are going to use a for loop to repeat our conditional statements a certain number of times. Let’s first set up a variable called vowelCount and set it to zero in order to keep track of the number of vowels in a string.</p><pre>vowelCount = 0</pre><p>Next we need to set up our <strong>for</strong> loop. There’s a several ways of doing this. Here are two of them.</p><pre>for index in range(len(string)):</pre><p>This first iterates over a range from 0 to the length of <em>string</em>. That means <em>index</em> here will be equal to an integer every single iteration of the loop.</p><p>Let’s try to count just the vowel “a” first by.</p><pre>for index in range(len(string)):<br>   if string[index] == &#39;a&#39;:<br>      # increment vowelCount</pre><p>Here, we are accessing each character of the string through its index and then checking to see if it is matches ‘a’. If the character does match ‘a’, we then carryout whatever is inside our <strong>if</strong> block.</p><p>An easier and more readable way to write this code is to access the characters directly instead of going through the index of the string.</p><pre>for letter in string:</pre><p>I know. Pretty nice looking right? It reads like English and you don’t have to use the range or len functions.</p><p>Finally we want to increase our VowelCount variable count by one inside our conditional statements. We can do this once again in a couple ways.</p><pre>vowelCount = vowelCount + 1</pre><p>or</p><pre>vowelCount += 1</pre><p>I’ll will use the second one going forward.</p><p>Alright now that we have all our little bits to this problem figured out, let’s put it all together.</p><pre># variable s is predefined<br># define and set variable vowelCount to 0<br>vowelCount = 0</pre><pre># create a for loop to iterate through each character of s<br>for letter in s:<br>    # if letter in s equal to each vowel, increment vowelCount by 1<br>    if letter == &quot;a&quot;:<br>        vowelCount += 1<br>    elif letter == &quot;e&quot;:<br>        vowelCount += 1<br>    elif letter == &quot;i&quot;:<br>        vowelCount += 1<br>    elif letter == &quot;o&quot;:<br>        vowelCount += 1<br>    elif letter == &quot;u&quot;:<br>        vowelCount += 1</pre><pre># print the concatenated first string and vowelCount<br>print(&quot;Number of vowels: &quot; + str(vowelCount))</pre><p>Boom. First problem down. Not that bad at all right?</p><h4>Problem 2</h4><blockquote>Assume s is a string of lower case characters.</blockquote><blockquote>Write a program that prints the number of times the string &#39;bob&#39; occurs in s. For example, if s = &#39;azcbobobegghakl&#39;, then your program should print</blockquote><blockquote>Number of times bob occurs is: 2</blockquote><p>Okay this one is a little bit harder but it’s not that difficult once you get your head around the concept of accessing substrings through a string’s index. What the heck do I mean by that? Here’s a little example:</p><pre>name = &quot;cyberdoggo&quot;<br>lastName = name[5:]</pre><p>If we print lastName, we get:</p><pre>doggo</pre><p>Here what we have to do is iterate through the string accessing substrings s[i:i+3) until we find a substring that matches “bob”</p><p>I’ll show what you I mean by that if it still sounds like mumbo jumbo.</p><p>First lets define and set a variable <em>bobCount</em> to 0. This variable will have the same purpose the variable <em>vowelCount</em> had in the first program.</p><pre>bobCount = 0</pre><p>Here’s where it gets a little complicated. First let’s create our for loop:</p><pre>for i in range(len(s)):</pre><p>This once again just iterates a range from 0 to the length of s.</p><p>Next we need to create our conditional statement to match a substring to “bob”:</p><pre>if (s[i:i+3] == &#39;bob&#39;):<br>    # a statement</pre><p>This checks to see if the substring created from s[i:i+3] is equal to “bob” as the name bob has a length of three characters and therefor requires the substring to be a length of three. So if <em>s</em> <em>= ‘azcbobobegghakl’</em>, the first substring s[0:3] would be equal to ‘azc.’ Since ‘azc’ does equal ‘bob’, the statement within the <strong>if</strong> expression would not be executed.</p><p>Alright the hardest part here is done. Now we just need to increment bobCount by one within the <strong>if</strong> statement.</p><pre>bobCount += 1</pre><p>Now let’s put it all together:</p><pre># s is a predefined string<br># define and set bobCount to 0<br>bobCount = 0</pre><pre># iterate through the range from 0 to the length of s<br>for i in range(len(s)):<br>  # check to see if the substring accessed is equal to &#39;bob&#39;<br>  if (s[i:i+3] == &#39;bob&#39;):<br>      bobCount += 1</pre><pre>print(&quot;Number of times bob occurs is: &quot; + str(bobCount))</pre><p>Creating comments by the way is a great habit to pick up early. If you end up working with other people, comments are incredibly vital to making sure your coworkers can understand your code easily. Don’t be “that guy” or “that girl.”</p><p>Go eat a snack and then we can get on to the last problem.</p><h4>Problem 3</h4><blockquote>Assume s is a string of lower case characters.</blockquote><blockquote>Write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example, if s = &#39;azcbobobegghakl&#39;, then your program should print</blockquote><blockquote>Longest substring in alphabetical order is: beggh</blockquote><blockquote>In the case of ties, print the first substring. For example, if s = &#39;abcbcd&#39;, then your program should print</blockquote><blockquote>Longest substring in alphabetical order is: abc</blockquote><p>This problem sucks until you get it. Then it’s not so bad. What do I mean by “get it”? I’ll show you.</p><p>First let’s setup a little example:</p><pre>letters = &quot;abc&quot;<br>print(letters[1] &gt; letters[0])</pre><p>If we run this program we get:</p><pre>True</pre><p>I know what you’re thinking. “Why did that work?” Well let’s try something else. Enter this statement into your Python shell.</p><pre>print(ord(‘a’))</pre><p>You should get the number 97. What ord() is doing is converting the character ‘a’ to its corresponding ASCII numeric value. ASCII is basically just the standard for character encoding. I won’t go too much into this as I would have to write something the length of a Wikipedia article to fully explain it. Fortunately though, someone already wrote a great article <a href="https://en.wikipedia.org/wiki/ASCII">there</a>. It’s okay if you don’t get much. I only understand about a quarter of it.</p><p>So now that we know we can compare characters against each other, this problem should become a lot easier to grasp.</p><p>First let’s define two variables <em>called </em>and <em>longest</em>. You can just set them to empty strings. I explain these later don’t worry.</p><pre>current = &#39;&#39;<br>longest = &#39;&#39;</pre><p>Now let’s set up our for loop to iterate over our string as per usual:</p><pre>for i in range(len(s)):</pre><p>Here’s where it gets fun:</p><pre>if (s[i] &gt;= s[i-1]):<br>    current += s[i]<br>else:<br>    current = s[i]</pre><p>Our if statement checks to see if the current character, s[i], is greater than the previous character, s[i-1], in the string. So if s[i] is greater than or equal to s[i-1], it gets added to the string <em>current</em> as s[i] is ahead of s[i-1] in the alphabet. However, if s[i] is before s[i-1] in the alphabet, we need to reset the string <em>current</em> and set it to the value of s[i].</p><p>The problem though right now is that we are not finding the longest alphabetical substring in s, we are simply finding the last alphabetical substring in s. This is where the variable <em>longest </em>we defined earlier comes into play. Below our if-else block, we need to create another if statement that sets <em>longest</em> to the string of <em>current </em>if the length of <em>current</em> is greater than <em>longest</em>. Let’s use that len() function we’ve used before in our for loops.</p><pre>if len(current) &gt; len(longest):<br>    longest = current</pre><p>That’s pretty much it. Now for the last time, let’s put it all together:</p><pre># s is predefined variable set to a string value</pre><pre>current = &#39;&#39;<br>longest = &#39;&#39;</pre><pre>for i in range(len(s)):<br> if (s[i] &gt;= s[i-1]):<br>  current += s[i]<br> else:<br>  current = s[i]<br> if len(current) &gt; len(longest):<br>  longest = current</pre><pre>print(&quot;Longest substring in alphabetical order is: &quot; + longest)</pre><p>Overall, that wasn’t too bad. Now you can say you’ve completed an MIT problem set! One thing to note is that while my programs completed all of tests MIT put into their grading platform, they are not perfect. When writing code you should always try to make your programs as modular as possible. Always try to look for new ways your program could fail. If you can do that, you are officially more of a <strong>hacker </strong>than anyone on CSI: GreenTerminals.</p><p>See you next time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5ba79ae2aad" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cyberdoggo/mit-6-00-1x-problem-set-1-c5ba79ae2aad">MIT 6.00.1x: Problem Set 1</a> was originally published in <a href="https://medium.com/cyberdoggo">cyberdoggo</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>