Skip to content

Instantly share code, notes, and snippets.

@tinybike
Last active August 29, 2015 14:05
Show Gist options
  • Save tinybike/f5b195c96679f840241f to your computer and use it in GitHub Desktop.
Save tinybike/f5b195c96679f840241f to your computer and use it in GitHub Desktop.
# Fun with sequential differences
# @author jack@tinybike.net
# Recursion (hideous...or maybe I'm just bad at it)
function seqdiff!(x; top=NaN, differences=[])
if isempty(x)
return [0, differences], sum(differences)
end
if isnan(top)
top = pop!(x)
else
prev = top
top = pop!(x)
differences = [prev - top, differences]
end
seqdiff!(x; top=top, differences=differences)
end
recursive_answer = seqdiff!([1, 2, 4, 6, 10, 15])
# Iteration
x = [1, 2, 4, 6, 10, 15]
differences = x[1:end] - [x[1], x[1:end-1]]
iterative_answer = (differences, sum(differences))
# Verify both answers are the same
@assert recursive_answer == iterative_answer
println("Recursion: ", recursive_answer)
println("Iteration: ", iterative_answer)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment