JSFiddle - React, Tailwind, and code Playground

by Andrew Poes

HTML

<!--Euler Problem 152
 Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner.

How many such routes are there through a 20×20 grid? -->

CSS

.print {
    position: relative;
    display: inline-block;
    background-color: black;
    color: white;
    font-family: Helvetica, Helvetica-Neue, sans-serif;
    font-weight: bold;
    font-size: 24px;
    letter-spacing: -1.5px;
    padding: 4px 8px;
}

body {
    background-color: #eeeeee;
}
}

JavaScript

$(document).ready(function() {
	var start = new Date().getTime();

    var grid = 10
    var tree = []
    for (var i = 0; i < grid; ++i) {
        for (var j = 0; j < grid; ++j) {
            tree.push(new Leaf("[" + i.toString() + ", " + j.toString() + "]"))
        }
    }
    for (var i = 0; i < tree.length; ++i) {
        var node = tree[i]
        var r = i + 1
        var l = i + grid
        if (r < tree.length && row(i, grid) == row(r, grid)) {
            node.right = tree[r]
        }
        if (l < tree.length && col(i, grid) == col(l, grid)) {
            node.left = tree[l]
        }
    }
    
    var c = { count: 0 }
    traverseTree(tree[0], c)
    print(c.count)

    var end = new Date().getTime();
    var time = end - start;
	print('Execution time: ' + time + 'ms');
})

function row(index, cols) {
    return Math.floor(index / cols)
}

function col(index, cols) {
    return index%cols
}

function Leaf (id) {
    this.id = id
    this.left = null
    this.right = null
}

function traverseTree(node, c) {
    if (node == null) {
        return
    }
    if (node.left == null && node.right == null) {
		c.count += 1
    }
    if (node.left) {
    	traverseTree(node.left, c)
    }
    if (node.right) {
	    traverseTree(node.right, c)
    }
}

function print() {
    var args = Array.prototype.slice.apply(arguments)
    var str = ""
    for (arg of args) {
        str += arg + ", "
    }
    str = str.substring(0, str.length - 2)
    var el = newel(str)
    $("body").append(el)
    $("body").append("</br>")
}

function newel(str) {
    var el = document.createElement("div")
    $(el).html(str)
    $(el).addClass("print")
    return el
}