FCC ‘Find the Longest Word in a String’

The next freeCodeCamp algorithm that we’ll work on here at The Crooked Code will be ‘Find the Longest Word in a String’.  The challenge here is to write a function that accepts a string as a parameter and returns the length of the longest word in the string, which means we’ll be returning a number.

Before we start on the algorithm, there are a few JavaScript concepts that we’ll need to go over…

In JavaScript, methods are functions that are stored as object properties. Further, there are many methods that are built into JavaScript that are available to manipulate things like strings and arrays.  This algorithm will let us start exploring the methods associated with these various data types.  This concept might not seem immediately clear, however, this w3schools page explains the concept in a little more detail, or just keep reading this post and things should clear up.

As is the case with accessing other properties of objects, we can use dot notation to call these methods.

Let’s try to clear things up with an example:

String.split() is one of many methods that can be used on a string.  Split() will divide a string into an array of substrings.  It takes up to two arguments.  The first argument is the separator, or where the string will be divided.  The second argument is the limit and is optional.  The limit is a number specifying the max number of substrings (we won’t be using this second argument is this example).  In use, split() looks something like this:

A few things to note in this code…  We passed (‘ ‘) to str.split which means str will be divided into substrings at each whitespace.  (if you pass (”) str will be split at every letter, if you pass ‘,’ it’ll be split at every comma and so on..).    Also, console.log() is an excellent way of checking that your code is doing what you want.  In this case, we passed it the array of strings (arrOfStr) in which we stored all the substrings so we could check if the code was doing what we intended.  As you can see from the line below the console.log call, arrOfStr now contains 4 different strings, 1 for each word in the original string (str).

One more quick thing to cover before we get into solving the algorithm – arrays.  An array is a data structure that allows us to store a list of multiple values in a single variable.  Each value in the list is called an element and can be accessed individually using bracket notation, which is also explained in this MDN page.  An example using bracket notation with the above example would be:

As you can see, the index (the number inside the bracket notation that accesses an individual element in the array) of the first element of an array is 0.  Therefore, when we log index 0 of arrOfStr to the console we get ‘this’.  A good intro to arrays can be found here.

Ok, now moving onto the problem at hand…

FCC provides the following starting point:

We need to write the code inside the findLongestWord function that will return the length of the longest word.  FCC then starts to check your code by calling findLongestWord with the string ‘The quick brown fox jumped over the lazy dog’.

We can start by splitting the original string into an array of individual words as such:

We also need to create a variable to store the value representing the length of the longest word.

Now we need to write a loop to go through wordArray and look for the longest word.  Something to help with both these tasks is the method .length which can be used on both strings and arrays.  String.length will return the number of characters in a string.  Array.length will return the number of elements in an array.

A for loop is an easy way to iterate through an array.  The for loop is different from the while loop used in the last algorithm in that it is initiated using three statements.  A decent intro to a for loop can be found here but I’ll try to use an example to illustrate how it works:

The first statement (var i = 0;) executes before the loop begins.  In this case, we initialize a variable (i) to equal 0.  The second statement (i < 5) is the condition that must remain true for the loop to continue.  In this case, the loop will iterate 5 times (while i is equal to 0 through 4).  The third statement is executed at the end of each iteration, in this case, i is incremented by 1 each time.

Combining everything we’ve discussed thus far to solve the algorithm:

The comments in the code ( everything following //) should help you follow the logic.  The only thing in the code that we didn’t cover previously is the if statement.  The code is fairly self explanatory, but you can read up on if statements on this MDN page.   Basically, if the statement inside the () of an if statement is true, the code following (either a single line or a block inside {}) is executed.  In this function, the if statement is used to check if the current word is longer than the previous longest word.  If true, the length of the new longest word is stored in wordLength.

Hopefully this straightened out the code for you.  See you next time.

-Jeremy

FCC ‘Factorialize a Number’

freeCodeCamp’s Basic Algorithm Scripting section – ‘Factorialize a Number

We’ll start digging into the freeCodeCamp (FCC) curriculum with ‘Factorialize a number’ because it’s pretty straight forward and it’ll allow us to discuss the structure of functions and introduce loops (This problem can also be solved with recursion, but we’ll get into that with some of the more complex algorithms).

The challenge is to write a function that will return the factorial of the number provided.

To understand factorials better, feel free to check out wikipedia, but basically, a factorial is the product of all integers less than or equal to n and is expressed as n!  (i.e. 4! = 4 x 3 x 2 x 1 = 24).

FCC provides the following starting point:

As I mentioned in my first post, a function is a block of code that acts independently to perform a task.  It can be called from other parts of your program, and therefore, can be used over and over to perform the same ‘function’.  Functions have many uses in JavaScript, check out Eloquent JavaScript – chapter 3 to learn more.

As you can see above, the function we’ll be building is named factorialize and has one parameter (num).  The way it’s written above, it returns that parameter (the body of a function is contained in {}).  The function is then called on line 5 and passed the argument (5).

We need to add the code that will take the parameter (num) and calculate and return the factorial of ‘num’.

We’ll start by declaring a variable to store the value of the factorial and set it equal to 1.

We’ll add the code to calculate the factorial using a while loop.  Loops allow us to set a condition, then execute a block of code until that condition is met.  MDN gives a pretty good intro to while loops here.

We’ll use the argument (num) in our condition and say:

This while loop will now iterate until num>1 is false.  Therefore, we have to remember to somehow change num each time so that eventually the loop will end (otherwise, we have an infinite loop and the program will never complete).

Now we have to do something each time the loop iterates, this is where our variable total comes in.  Given that JavaScript will execute the right side of an equation before it stores it to the left side, we can set total = total * num, then depricate num by 1.  That would look something like this:

If we walk through this for num = 5, the first pass would be

Now total = 5 and num = 4.  Since 4 > 1, the while loop will execute again.

Now total = 20 and num = 3.  This will continue until the while (num>1) fails.  It would look like this.

total = 60, num = 2.

total = 120, num = 1.

At this point, the while loop condition would be false, and the loop would end with total = 120.  Given 5! = 120, we have the right total, we just need to return it.  We can just change the return statement from return num; to return total;.

Putting everything together:

This gives us the correct answer, but JavaScript makes statements that add, subtract, multiply or divide a number by itself much easier to write using the following operators: +=, -=, *= and /=.  You can also increment and deprecate by 1 using ++ and — respectively.  See the w3schools page on operators for more info.  Knowing that, the solution seen above can be written:

These two solutions do the exact same thing and solve the ‘Factorialize a Number’ algorithm challenge.

Hopefully this straightened out the code for you.  See you next time.

-Jeremy

Intro to JavaScript Terms

As a primer to more in depth JavaScript discussions, I figured an intro to some of the terminology that we’ll be using might be helpful.  As this will not be a complete “Intro to JavaScript” (far from it, in fact), I’ll provide links to resources that I’ve found helpful along the way.

Resources

There are several sites that I use frequently in learning to code.  Obviously, freeCodeCamp is the main one.  As I mentioned in my first post, I am currently working through the front end development certification at freeCodeCamp and highly recommend it.  While working through the freeCodeCamp curriculum I use w3schools, MDN and Stack Overflow extensively as references.  I also found that Tutorial Republic is an excellent resource for HTML, CSS and Bootstrap (which is a powerful front end framework that makes creating responsive web pages much easier).

There are also a couple books that I’ve used along the way.  The first is ‘Eloquent JavaScript‘, which is an excellent free resource (available in print also) for learning JavaScript.  It’s not exactly a book for beginners, but the online version provides examples and problems that you can work through right in the browser.  It’s the best JavaScript resource I’ve found yet…   I also picked up the Head First books ‘HTLM and CSS‘ and ‘HTML5 Programming‘.  They’re more on the beginner side, but are written well and I found them helpful in learning to interact with the DOM (which we will get into in future posts).

Intro to Terminology

Now, to cover some terms we’ll be using frequently.  In future posts, I will have to assume a basic understanding of these languages, otherwise each post will be the length of a book.  So I urge you, if you have any questions about the concepts listed below, please use the resources listed above to read more about them.

In JavaScript, groups of data are called values and these values have types.  There are 7 data types in JavaScript:

  • undefined
  • null
  • boolean
  • string
  • symbol
  • number
  • object

Any of these data types can be stored in a variable.  To declare a variable, use the keyword ‘var’, as such:

The above statement created a variable named ‘a’.  It also includes a comment…  Anything written on a line after // is a comment and will be ignored by the browser.  You can also assign values to the variable when you create it. The following statements create variables and assign values of the various data types.

JavaScript provides several data structures called objects and arrays.  I plan on covering objects and arrays in depth in decipheredCode so for now will only cover each at a very high level.

Objects allow us to group data of various types (including other objects) as name:value pairs called properties.  Objects are used extensively in JavaScript, in fact JSON (JavaScript Object Notation) files are the way most programs pass data among themselves over the web.

An array is a list of objects or values, called elements, stored inside brackets and separated by commas.  Array elements can be accessed using bracket notation and indexes (note: first element in an array is index [0]).  An example of accessing the first element of an array would be:

The arr declared above would now have the string ‘apple’ as it’s first element (index [0]).  Chapter 4  of ‘Eloquent JavaScript’ gives a great explanation in the use of objects and arrays.

Another term used extensively in JavaScript, and programming in general, is function.  A function is a self contained block of code that can act on it’s own to do something.  A function can take a set of parameters (optional) and contains a block of code to act on those parameters.  Here’s an example of a function.

This function, named addOne, has one parameter (num).  The code inside the function creates a new variable called newNum, then sets newNum equal to num + 1 and returns the value of newNum.  The way we would use this function (or invoke it) is

This example calls the addOne function and passes the number 5 as an argument.  This function call would return the value 6.

What is an argument?  An argument is the actual value that you pass into the function, as opposed to a parameter, which is the name listed in the function definition.  I’ll be using these terms interchangeably here at decipheredCode (whether right or wrong…), so you can think of both arguments and parameters as something that gets passed into a function.

Now…  This has been a long, rambling post that mentioned a bunch of things but didn’t really explain anything in detail. I feel, however, that it was necessary before I started digging any deeper..  Hopefully, this will be helpful to someone just starting out on their journey to learn to code.  The next posts here at decipheredCode will start to dig into real problems.  Meantime, I urge anyone that is interested to check out the links that I mentioned above and to start getting their hands dirty by writing some code!

-Jeremy

Learning to Program? We’ll help straighten out the code…

Learning to code, becoming a self-taught programmer, can be a daunting task when you are just beginning the process. The good news is there are tons of resources out there to help.

I started my learn to code journey earlier this year and have spent many hours sorting through all the resources out there to find the good ones. In some cases, however, even the good resources include jargon that might be confusing and difficult to understand for the beginner. I’ve created crookedCode in an attempt to break through that jargon and help others along their journey.

What makes me qualified to write about something I’m only in the process of learning? Great question… Rather than trying to justify what makes me qualified to cover these subjects, let me give the two reasons why I’ve created this blog:

The first reason, as I mentioned above, is that I’ve spent many hours trying to find good resources to help along the way. I hope that sharing what I’ve learned, and where to look for help, will enable others spend more time learning to code (and less time looking for how to learn).

The second reason, and this is a bit more selfish, is that going back and writing posts about challenges and projects that I’ve already completed will help solidify the concepts in my head. I find that the best way to truly understand a concept is to try to teach it to someone else. So that’s what I plan to do.

I’m currently working my way through freeCodeCamp. If you’re interested in learning to program, especially web development, I highly recommend checking them out. It’s a completely free program, with a very active and supportive community, and if you need another reason, they’re also doing some social good through their work with nonprofits.

We’ll start by working through examples of the freeCodeCamp curriculum (both algorithm challenges and development projects) and move on from there as we get more proficient. That said, we’ll be focusing on the logic behind the algorithms and we’ll be coding in Javascript, HTML and CSS.

I’ve learned quickly that there are usually multiple ways to solve coding problems. So, being new to this, I’m sure that I will not always provide the most efficient solution or most elegantly written code, so I welcome the feedback and suggestions. Please keep it positive though, there are plenty of other sites out there where you can berate others and get your aggressions out, please treat this as a positive learning environment.

-Jeremy