I'm just starting to learn CoffeeScript and am trying to work through simple examples, this one being Prim's algorithm. I'd like feedback on everything but especially on making this script take advantage of the features of CoffeeScript most effectively.
nodes_dir = {
0 : [1],
1 : [0, 2, 3, 5],
2 : [1, 4],
3 : [1, 4, 5],
4 : [2, 3],
5: [1, 3]
}
edges_dir = {
0: {1:6}
1: {2:1, 3: 2, 5:0, 0:6},
2: {1:1, 4:4},
3: {1:2, 4:5, 5:3},
4:{2:4, 3:5},
5:{3:3, 1:0},
}
MAX_WEIGHT = 10000
NUM_NODES = 6
EDGE_WEIGHTS = [99, 2, 2, 1, 1, 5, 10]
get_min_key_value = (obj) ->
if Object.keys(obj).length < 1
return [-1, -1]
min_k = MAX_WEIGHT
min_v = MAX_WEIGHT
for k, v of obj
if v < min_v
min_v = v
min_k = k
delete obj[min_k]
[min_k, min_v]
# Prims algorithm as implemented in Skiena p 195
prim = (nodes_dir, edges_dir) ->
# record-keeping arrays
intree = []
distance = []
link = []
parent = []
# set default values for record-keeping arrays
for i in [1..NUM_NODES]
intree.push -1
distance.push MAX_WEIGHT
link.push -1
parent.push -1
links = []
link_add = -1
current_node = 0
while intree[current_node] < 0
# add new node and new edge to record of edges/nodes
intree[current_node] = 1
links.push link[current_node] if link[current_node] > 0
# update any distances to tree that have become shorter with addition of new node
p = edges_dir[current_node]
for k,v of p
weight = EDGE_WEIGHTS[v]
if distance[k] > weight and intree[k] < 0
distance[k] = weight
link[k] = v
parent[k] = current_node
# determine which node is now closest to tree and add it
dist = MAX_WEIGHT
for i in [0..NUM_NODES-1]
if intree[i] < 0 and dist > distance[i]
dist = distance[i]
current_node = i
link_add = link[i]
links
f = prim(nodes_dir, edges_dir)
alert f