Skip to content

Instantly share code, notes, and snippets.

@showell
showell / lib_cache_call.rb
Created December 2, 2010 19:41
using memcache to cache results of expensive functions with a URL scheme
class CacheCall
# Calls a function that accepts a hash as its only parameter UNLESS
# the result has been recently cached. Cache keys are essentially a
# URL of the hash keys and values.
#
# ====Parameters
#
# +method_obj+::
# A Ruby method object that supports call() and .name
#
@showell
showell / gist:906814
Created April 7, 2011 00:26
algorithm practice: combinations
require 'pp'
def succ(a, n)
# a is an array of integers <= n
# see tests
return nil if n == 0
a = Array.new(a)
x = a.pop
if x + 1 < n
return a + [x + 1]
@showell
showell / permutations.rb
Created April 7, 2011 03:15
algorithm practice: permutations (using lexical successor to generate)
require 'pp'
def succ(a)
# destructive to a
n = a.size
k = (n-2).downto(0) do |k|
break k if a[k] < a[k+1]
end
return nil if a[k] >= a[k+1]
l = (n-1).downto(0) do |l|
@showell
showell / bsearch.rb
Created April 7, 2011 04:25
algorithm practice: bsearch
require 'pp'
def chop(key, a)
low = 0
high = a.size - 1
while low < high do
mid = (low + high) / 2
val = a[mid]
return mid if val == key
if val > key
@showell
showell / weather_kata.rb
Created April 7, 2011 05:04
weather part of "data munging" kata
require 'pp'
def lines(fn)
File.open(fn) do |f|
return f.readlines
end
end
def data
lines('weather.dat').map do |line|
@showell
showell / game_of_life.rb
Created April 7, 2011 07:51
yet another Game of Life implementation (functional style)
require 'pp'
HEIGHT = 37
WIDTH = 17
def alive(game_board, x, y)
x %= WIDTH
y %= HEIGHT
coords = "#{x},#{y}"
game_board[coords]
@showell
showell / design.html
Created April 7, 2011 17:55
game of life w/functional JS style
<a href="game_of_life.html">Game of Life</a>
<h3>Computer Programs are...</h3>
Poetry for Robots? Maybe...but how about?
<ul>
<li>Algorithms</li>
<li>Configuration</li>
@showell
showell / max_run.coffee
Created April 11, 2011 19:38
Common Interview Question: longest run of integers (implemented in coffeescript w/tests)
assert = (cond) ->
throw("error") unless cond
max_run = (a) ->
m = 0
c = 0
for n in a
c += n
c = 0 if c < 0
m = c if m < c
@showell
showell / gist:1057894
Created July 1, 2011 04:57
jquery starter
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
</head>
<h1>SOME APP</h1>
@showell
showell / bizz.coffee
Created July 9, 2011 20:52
bizz_buzz on acid
# This extremely dubious code shows how to simulate
# a custom control structure in CS. bizz_buzz does
# a highly configurable loop through the integers.
bizz_buzz = (config) ->
i = 0
while true
i += 1
break if config.quit(i)
if config.bizz(i) && config.buzz(i)
console.log "bizzbuzz"