Skip to content

Instantly share code, notes, and snippets.

# a heavy int is one where the average of the digits is greater than 7
# eg: 8678 is heavy because (8 + 6 + 7 + 8) / 4 = 7.25
# 8677 is not heavy because ( 8 + 6 + 7 + 7) / 4 = 7
def num_heavy_ints(a, b):
"""
Return the number of heavy integers between a and b (inclusive).
Assume that a and b are positive integers.
>>> num_heavy_ints(8675, 8689)
@andyhd
andyhd / ipToInt.scala
Created May 20, 2011 08:33
IP dotted quad string to integer
// Scala is great
def ipToInt(ip: String) = ip.split('.').map(_.toInt).foldLeft(0)((sum, i) => sum * 256 + i)
@andyhd
andyhd / pattern-matching.js
Created January 12, 2012 16:07
Functional pattern matching (sort of) with Javascript
function when(x) {
return function () {
for (var i in arguments) {
var result = arguments[i](x);
if (result !== false) {
return result;
}
}
throw "No patterns matched when(" + x + ")";
};
@andyhd
andyhd / maybe-monad.js
Created January 16, 2012 01:02
Maybe monad in Javascript
function maybe(value) {
var obj = null;
function isEmpty() { return value === undefined || value === null }
function nonEmpty() { return !isEmpty() }
obj = {
map: function (f) { return isEmpty() ? obj : maybe(f(value)) },
getOrElse: function (n) { return isEmpty() ? n : value },
isEmpty: isEmpty,
nonEmpty: nonEmpty
}
@andyhd
andyhd / maybe-example.js
Created January 16, 2012 09:38
Maybe monad usage
var book = db.query("SELECT * FROM book WHERE id = 1");
function printTitle(book) { console.log(book.title) }
maybe(book).map(printTitle);
@andyhd
andyhd / tryo.js
Created January 23, 2012 11:25
Handling exceptions in mapped function
function tryo(fn) {
var res = null;
try {
res = fn();
} catch (e) {
res = null;
}
return maybe(res);
}
@andyhd
andyhd / map-reduce-filter.js
Created February 1, 2012 11:43
Javascript map, reduce and filter
function map(f, a) {
return a.length ? [].concat(f(a[0]), map(f, a.slice(1))) : []
}
function filter(f, a) {
return map(function (x) { return f(x) ? x : [] }, a)
}
var even = function (x) { return x % 2 == 0 };
@andyhd
andyhd / lens.js
Created February 11, 2012 01:48
Javascript Lenses
function lens(get, set) {
var f = function (a) { return get(a); };
f.set = set;
f.mod = function (f, a) { return set(a, f(get(a))); };
return f;
}
var first = lens(
function (a) { return a[0]; },
function (a, b) { return [b].concat(a.slice(1)); }
@andyhd
andyhd / world.js
Created April 18, 2012 08:57
render with one loop
function drawMap(map) {
var i, x, y, height, pos,
width = map[0].length,
total_nodes = map.length * width;
for (i = 0; i < total_nodes; i++) {
x = i % width;
y = Math.floor(i / width);
height = {
top: map[y][x],
right: map[y][x+1],
@andyhd
andyhd / world.js
Created April 18, 2012 09:12 — forked from nefarioustim/world.js
render with one loop
function drawMap(map) {
var x, y,
width = map[0].length,
current_node = map.length * width;
while (current_node--) {
x = current_node % width;
y = ~~(current_node / width);
drawTile({
x: x,
y: y