most of the examples converted to symbology.

This commit is contained in:
Jeremy Ashkenas
2010-07-29 00:03:42 -04:00
parent 58a5d93214
commit da6ea27454
13 changed files with 216 additions and 229 deletions

View File

@@ -2,15 +2,15 @@
# The implementation of binary search that is tested.
# Return the index of an element in a sorted list. (or -1, if not present)
index: (list, target) ->
[low, high]: [0, list.length]
index = (list, target) ->
[low, high] = [0, list.length]
while low < high
mid: (low + high) >> 1
val: list[mid]
mid = (low + high) >> 1
val = list[mid]
return mid if val is target
if val < target then low: mid + 1 else high: mid
if val < target then low = mid + 1 else high = mid
return -1
puts 2 is index([10, 20, 30, 40, 50], 30)
puts 4 is index([-97, 35, 67, 88, 1200], 1200)
puts 0 is index([0, 45, 70], 0)
puts 2 is index [10, 20, 30, 40, 50], 30
puts 4 is index [-97, 35, 67, 88, 1200], 1200
puts 0 is index [0, 45, 70], 0

View File

@@ -1,11 +1,11 @@
# Beautiful Code, Chapter 3.
# Produces the expected runtime of Quicksort, for every integer from 1 to N.
runtime: (N) ->
[sum, t]: [0, 0]
runtime = (N) ->
[sum, t] = [0, 0]
for n in [1..N]
sum += 2 * t
t: n - 1 + sum / n
t = n - 1 + sum / n
t
puts runtime(3) is 2.6666666666666665

View File

@@ -3,16 +3,16 @@
# '.', '^', '$', and '*'.
# Search for the regexp anywhere in the text.
match: (regexp, text) ->
match = (regexp, text) ->
return match_here(regexp.slice(1), text) if regexp[0] is '^'
while text
return true if match_here(regexp, text)
text: text.slice(1)
text = text.slice(1)
false
# Search for the regexp at the beginning of the text.
match_here: (regexp, text) ->
[cur, next]: [regexp[0], regexp[1]]
match_here = (regexp, text) ->
[cur, next] = [regexp[0], regexp[1]]
if regexp.length is 0 then return true
if next is '*' then return match_star(cur, regexp.slice(2), text)
if cur is '$' and not next then return text.length is 0
@@ -20,11 +20,11 @@ match_here: (regexp, text) ->
false
# Search for a kleene star match at the beginning of the text.
match_star: (c, regexp, text) ->
match_star = (c, regexp, text) ->
loop
return true if match_here(regexp, text)
return false unless text and (text[0] is c or c is '.')
text: text.slice(1)
text = text.slice(1)
puts match("ex", "some text")
puts match("s..t", "spit")