Free Code Camp Algorithmic Challenges

So, as I think I've mentioned before, I post links to these blog posts over at LinkedIn. I also ask for feedback there.

At one point I simply asked what topics I ought to blog about. One of the responses I got was to post solutions (with breakdowns) to algorithm challenges at sites like freecodecamp.com.

They specifically asked that I tackle the intermediate and advanced challenges, which I will do, but I'm too much of a completionist to start there. :)

So I've decided to create a repo with all the solutions to all the problems. Here's the link.

Each solution will have its own file as well as its own test file.

I strongly encourage you to do these challenges on your own before reading the rest of this post or any future solution posts I make.

I should also note that I'm going to be using ramda, any ES6 features I learn about, and any library that catches my fancy in the future. So you won't be able to use most of these exact solutions in any event.

Ok! let's get started!

The first challenge is to reverse a given string. I've written tests that exactly match the tests in the challenge:

describe('reverse', () => {  
  var reverse = require('../reverse.js')

  it('should return a string',
    () => expect(typeof reverse('Howdy'))
      .toEqual('string'))

  it('"hello" should become "olleh"',
    () => expect(reverse('hello')).toEqual('olleh'))

  it('"Howdy" should become "ydwoH"',
    () => expect(reverse('Howdy')).toEqual('ydwoH'))

  it('"Greetings from Earth" should become "htraE morf sgniteerG"',
    () => expect(reverse('Greetings from Earth'))
      .toEqual('htraE morf sgniteerG'))
})

Here's my code:

var R = require('ramda')

module.exports = R.reverse  

Heh heh >:)

Ok, let's do one more, getting the factorial of a number. Just as a refresher, in arithmetic factorial is represented as a bang, like so: n!.

Here's how we define a factorial:

0! = 1  
n! = (n)(n-1)(n-2)...(1)  

Some examples:

5! = 5 * 4 * 3 * 2 * 1 = 120  
2! = 2 * 1 = 2  
4! = 4 * 3 * 2 * 1 = 24  

Here are my tests:

describe('factorial', () => {  
  var factorial = require('../factorial.js')

  it('factorial(5) should return a number.',
    () => expect(typeof factorial(5)).toEqual('number'))

  it('factorial(5) should return 120.',
    () => expect(factorial(5)).toEqual(120))

  it('factorial(10) should return 3628800.',
    () => expect(factorial(10)).toEqual(3628800))

  it('factorial(20) should return 2432902008176640000.',
    () => expect(factorial(20))
      .toEqual(2432902008176640000))

  it('factorial(0) should return 1.',
    () => expect(factorial(0)).toEqual(1))
})

And here's my solution:

module.exports = function factorialize(num) {  
  if (num > 0) return num * factorialize(num - 1)
  return 1
}

Not much to break down here. We keep doing a recursive call until we get our result. We'll get more complicated after a bit. :)

Looking for a software developer?