This Week in Dev

JavaScript Word-Search Puzzle

Revisiting JavaScript this week - I think my solution to the wordsearch puzzle grid problem is particularly elegant. Check out my Solution here

I also tweeted about an elegant recursive algorithm I devised to generate integer sequences in JavaScript (which is utilized in the word search challenge) Some languages (Ruby, Haskell) use syntax like [1..10] to represent an integer sequence, but JavaScript doesn’t have a built-in way to do this, so I created my own.

function intSequence(start, end, n = start, arr = []) {
    return n === end ? arr.concat(n)
        : intSequence(start, end, start < end ? n + 1 : n - 1, arr.concat(n));
}
[Read More]

This Week in Dev

Java, Unit Tests, CodeSignal

Up to level 40 this week on CodeSignal.com - that’s over 100 challenges solved in just a couple weeks

Evaluating Efficiency with Big-O Notation

Check out my recursive solution to this arcade problem, which made it possible for me solve a problem in *constant time* O(1), a whole world of improvement over my previous approach, which turned out to be a *factorial time* O(n!) solution. Big-O notation is a means of evaluating the computational efficiency of different algorithms.

My solution

boolean stringsRearrangement(String[] inputArray) {
    String[] sorted = Arrays.stream(inputArray).sorted().toArray(String[]::new);

    // test input that does not include duplicates
    if (inputArray.length == Arrays.stream(inputArray).distinct().count()
            && allStringsConform(sorted)) return true;

    // test starting with each individual input string
    for (String string : Arrays.stream(sorted).distinct().toArray(String[]::new)) {
        ArrayDeque<String> input = new ArrayDeque<>(Arrays.stream(sorted).collect(Collectors.toList()));
        input.remove(string);
        ArrayDeque<String> output = new ArrayDeque<>(Collections.singletonList(string));
        if (testPermutations(input, output)) return true;
    }

    return false;
}
[Read More]

This Week in Dev

Java, Streams and Loops - Affine Cipher

import java.math.BigInteger;

class AffineCipher {

    private static final int M = 26;        // size of alphabet
    private static final int A = (int) 'a'; // zero-index of 'a' (ASCII code point 97)

    String encode(String input, int a, int b) {
        if (greatestCommonDivisor(a, M) != 1) {
            throw new IllegalArgumentException("Error: keyA and alphabet size must be coprime.");
        }

        StringBuilder output = new StringBuilder();

        for (int codePoint :
            input.replaceAll("\\W", "") // nix punctuation and whitespace
                    .toLowerCase()
                    .toCharArray()
        ) {
            output.append( Character.isDigit(codePoint)
                    ? (char) codePoint
                    : (char) (((a * (codePoint - A) + b) % M) + A));
        }

        return String.join(" ", splitString(output.toString(), 5));
    }
[Read More]

This Week in Dev

Java, HackerRank and PowerMock

Venture Prize Pitch Night at Brown was really fun. The $25,000 first place prize was awarded to Formally - a tech company that aims to streamline visa and asylum applications, which might save law firms thousands of man hours per year!

Here I am with some of my classmates, posing for a photo with Virgin Pulse CMO Rajiv Kumar, who is an exceptional entrepreneur that founded “Shape Up RI” and managed to grow it into something extraordinary, and get acquired by Richard Branson’s Virgin Group.

/2019.03.06-BrownVenturePrize.jpg
It might be surprising to some that there is such a wealth of entrepreneural talent right here in little Rhode Island!

[Read More]

This Week in Dev

Java, HackerRank and PowerMock

I completed the 30 days challenges on HackerRank! HackerRank seems to employ an intentionally convoluted Input scheme, given that they use STATIC classes and instantiate Scanner class as FINAL, but i did manage to create JUnit tests for all the exercises that function equivalently to the online tests. I would be happy to share these (the tests) with others who appreciate the expediency and more robust debugging capabilities of haxoring in their local environment.

I used a tool called PowerMock to get around JUnit’s incapacity for testing static classes, so these unit tests are able to transparently run unmodified code from HR. Ask me for the repo (it just includes my tests and the intermediate code templates they provide for each exercise).

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import org.powermock.core.classloader.annotations.PrepareForTest;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

import static org.junit.Assert.assertEquals;

@RunWith(MockitoJUnitRunner.class)
@PrepareForTest({Solution.class})
public class SolutionTest {

    // a stream to record the output of our program
    private ByteArrayOutputStream testOutput;

    // run before each test (prepare for input / output)
    @Before
    public void setUpOutputStream() {
        testOutput = new ByteArrayOutputStream();
        System.setOut(new PrintStream(testOutput));
    }
[Read More]

This Week in Dev

Working with Node.js Express, mLab, and Concurrently

Brad Traversy’s DevConnector tutorial has kept me busy over the past couple weeks. see repo It was great to brush up after being away from developing React.js and Redux for a while. DevConnector is a much larger application than what I have built in the past using these tools, so and I was glad to practice my React/Redux programming patterns on such a larger scale.

I learned some new techniques in addition to brushing up on the familiar ones. mLab.com is a great tool for development. Not just a convenient alternative to working with MongoDB locally, mLab also offers intuitive interfaces for monitoring and managing database indexes.

/2019-02-19_mlab.png

Concurrently is another great trick I learned from this tutorial. I used to start the API and my frontend as separate processes, but with concurrently, I can combine them into one convenient command in my package.json

This Week in Dev

JavaScript - Classes, Functions, and Recursion

Great practice using classes in JavaScript, and working with recursion to solve an insertion problem.

Atbash Cipher

// extend the string object to filter out whitespace and shift to lower case
String.prototype.filterInput = function() {
    return this.replace(/\W/g, '').toLowerCase();
};

// extend the array object to return a string grouped into segments of five
Array.prototype.groupIntoFives = function() {
    return this.reduce((remit, char, index) =>
        index % 5 === 0
            ? remit += ' ' + char
            : remit += char
    , '').trim();
};

function atbashEncodeChar(c) {
    // return number as-is
    if (!isNaN(c))
        return c;

    // get zero-index index of the input letter (ie. a = 0, z = 25)
    const zeroIndex = c.charCodeAt(0) - 'a'.charCodeAt(0);

    // get the transposed letter (bounded by size of alphabet)
    const newLetter = (26 - zeroIndex + 25) % 26;

    // transpose back into ASCII range (ie. a = 97, z = 122)
    return String.fromCharCode(newLetter + 'a'.charCodeAt(0));
}

export const encode = input =>
    input.filterInput()
        .split('')
        .map(c => atbashEncodeChar(c))
        .groupIntoFives();
[Read More]

This Week in Dev

Steemit.com account finally approved

/logos/steemit-logo.svg
After almost 4 weeks, I had begun to lose hope of my Steemit account ever coming through, but the confirmation email has finally arrived, nearly a month after my signup. This makes it by far the longest interim between applying and receiving any online account for me personally. Steemit is a fount of great resources for blockchain, but it’s also an ethereum-based social networking blog that pays content producers based on user reviews.

[Read More]

This Week in Dev

More web3.js Tutorials

It seems now that innovation comes fast and furious, making the high state of flux one of the most challenging aspects of working with this technology currently. HardlyDifficult’s great Ethereum Dapp Tutorial on Steemit sometimes required a bit of finesse to maintain coherence with the video, as some of the tools have already evolved with breaking changes.

One tool I was very excited to learn about was Remix

[Read More]

Bash Hacking on Exercism.io

During Christmas break I treated myself to the idle diversion of honing my bash skills.

/logos/gnu_bash-official.svg

I must have blasted through about 6000 cookies as I solved a dozen or so bash programming challenges this week (at a frightful clip). Learning new languages by solving Exercism.io challenges has been my casual vice for a while now. Since I already use the bourne again shell incessantly in my work, I have always wanted to dig a bit deeper and really learn the nuts and bolts.

Bash is really weird. Maybe that’s because the shell is somewhat akin to a Ship of Theseus, representing the culmination of decades worth of design innovations stretching all the way back to the storied UNIX days of Bell Labs in the 1970s, where such giants as Ken Thompson and Dennis Ritchie created the seminal C Programming Language and the iconic UNIX operating system. There is a beautiful MC-Esheresque quality to the closely intertwined development of C and UNIX; two amazing tools that were created in mutual benefit of each other. The first implements the second, which facilitates development of the first.

/DrawingHands.jpg

The harsh upshot is that all those years of evolution has had the unfortunate side-effect of creating many situations where arbitrary design decisions become more significant than they ought to be, on account of the implications to program portability. I often also felt unduly challenged to understand the minute differences between variant uses of syntax, and experienced great pining for Python because of some spectacularly bizarre and counter-intuitive behaviors in Bash, like the character-set collation issue

Watch out! - 10 is sometimes less than 2

$ #!/usr/bin/env bash
$ function print() { (( $1 )) && printf X || printf .; }
$ for n in 1 2 9 10 20 'a'; do
$ (( $n < 2 )); print $?
$ [[ $n < 2 ]]; print $?
$ (( $n > 2 )); print $?
$ [[ $n > 2 ]]; print $?
$ printf "\t$n\n"
$ done
..XX    1
XXXX    2
XX..    9
X..X    10
XX..    20
.XX.    a
[Read More]