Free Code Camp Algorithmic Challenges Part 5

This is part 5 of a series in which I give solutions to the Free Code Camp Algorithmic challenges. Don't look at this post until you've solved these challenges yourself! You've been warned. :)

Here are the links for part 1, part 2, part 3, and part 4. You can also look at the github repo with all my solutions here.

Also, I'm using whatever libraries I feel like using (just ramda in this post) and any new JavaScript features I like for all of these challenges, something you can't do at freecodecamp.com.

Ok, with all that out of the way, Let's get on to the next challenges. :)

Chunky Monkey

This one asks us to split an array into some number of chunks of size n, and put that into an array. For example [1, 2, 3, 4, 5] split into chunks of size 2 is [[1, 2], [3, 4], [5]].

Here's the code:

const  
    R = require('ramda')

module.exports = (xs, n) =>  
    xs.reduce((xs, x) =>
        R.last(xs).length < n
            ? R.pipe(
                R.last,
                R.append(x),
                R.append(R.__, R.init(xs)))
                    (xs)
            : R.append([x], xs),
        [[]])

It's your basic reduce call. We use it to build an array of arrays. xs in the reducer is our accumulator (initialized as an array holding a single empty array), and x is an element from the original array.

The reducer first checks to see if the last element of xs is of size n. If not we add an element to the last array in xs. If so we add a new empty array to the end of xs.

Slasher Flick

This one just wants us to chop the front n elements from an array, which is what slice does:

module.exports = (xs, n) => xs.slice(n)  

'Nuff said. Next!

Mutations

Here we're asked to write a function that takes an array of two strings. The function should return true if all the characters in the second string are contained in the first string, ignoring case.

For example, given [[abcdefg], [CBa]] our function would return true, and for [[sdgid], [abc]] it would return false.

Code code code:

module.exports = arr =>  
    R.pipe(
        R.split(''),
        R.all(c => arr[0].match(new RegExp(c, 'i'))))
            (arr[1])

First we split up arr[1] into a character array.

R.all maps over each element of the array and then returns true if all elements in the resulting array are true. It's a shorthand for mapping a function on the array and then anding all the elements of the array returned by map.

Here we check to see if arr[0] matches the pattern new RegExp(c, 'i') which is just the character c ignoring case. Which is the same thing as saying that we check if c is in arr[0] (ignoring case).

More on regular expressions in another post.

Ok, that's enough for one post. Happy coding!

Looking for a software developer?