Created
February 22, 2013 09:01
-
-
Save rwoeber/5011907 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
radians = (n) -> | |
n * (Math.PI / 180) | |
# Operates similarly to Ruby's `Enumerable.invoke` | |
invoke = (a, f) -> | |
for n in a | |
memo = f memo, n | |
memo | |
# Returns the sum of an array of numeric items | |
sum = (a) -> | |
invoke a, (memo, n) -> | |
memo ?= 0 | |
memo += n | |
# Returns the difference of an array of numeric items | |
difference = (a) -> | |
start = a.slice(0, 1) | |
invoke a.slice(1), (memo, n) -> | |
memo ?= start | |
memo -= n | |
# Returns the product of an array of numeric items | |
product = (a) -> | |
invoke a, (memo, n) -> | |
memo ?= 0 | |
memo *= n | |
# Returns the quotient of an array of numeric items | |
quotient = (a) -> | |
start = a.slice(0, 1) | |
invoke a.slice(1), (memo, n) -> | |
memo ?= start | |
memo /= n | |
# Returns the dot product of two arrays of numeric items | |
dotProduct = (a, b) -> | |
if a.length isnt b.length | |
throw 'Argument `a` is not the same length as `b`.' | |
else | |
products = for v_a, i in a | |
v_b = b[i] | |
if v_a.length isnt v_b.length | |
throw 'Item `a`[#{i}] does not have the same dimmension as `b`[#{i}].' | |
else | |
v_a * v_b | |
sum products | |
matrix = (a, r, c) -> | |
{ | |
rows: r, | |
columns: c, | |
data: a | |
} | |
identity = (d) -> | |
a = [] | |
a.push (x is d - y) + 0 for x in [1..d] for y in [d-1..0] | |
matrix(a, d, d) | |
transform = (a, b) -> | |
n = [] | |
for r in [0...a.rows] | |
a_r = a.data.slice r * a.columns, r * a.columns + a.columns | |
for c in [0...b.columns] | |
b_c = (v for v, i in b.data when i % b.columns is c) | |
n.push dotProduct a_r, b_c | |
matrix n, r, c |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment