Skip to content

Instantly share code, notes, and snippets.

@zenon
Created April 6, 2017 20:50
Show Gist options
  • Save zenon/0da805a6ef96a31e6b4ba243337651c6 to your computer and use it in GitHub Desktop.
Save zenon/0da805a6ef96a31e6b4ba243337651c6 to your computer and use it in GitHub Desktop.
Test and fix for Sonic Pi's spread function, 2nd try
# helper for spread2
def redistribute(v1, v2)
vNew = []
while v1.length > 0 && v2.length > 0
a1 = v1.shift
a2 = v2.shift
vNew.unshift(a1 + a2)
end
if v1.length > 0 then
[vNew, v1]
else
[vNew, v2] # v2 might be empty, but that's fine
end
end
# no error checks, e.g. negative, num_accents > size
# no rotation
def spread2(num_accents, size)
v1 = [[true]] * num_accents
# If v2 empty -> end
if num_accents == size
v1
else
v2 = [[false]] * (size - num_accents)
# If v2 not empty, call at least once.
(v1, v2) = redistribute(v1,v2)
# End condition: v2 empty or has just one element.
while v2.length > 1
(v1, v2) = redistribute(v1,v2)
end
(v1 + v2).flatten
end
end
# "pretty" print a rythm
def ppeu(r)
result = ""
r.length.times do |i|
if r[i] then
result = result + "x"
else
result = result + "."
end
end
result
end
def test(a, b, r, rot = 0)
# result = ppeu(spread(a, b, rotate: rot))
result = ppeu(spread2(a, b)) # ignores rotation
if result == r then
# puts "ok: " + a.to_s + b.to_s
else
puts "nok: " + a.to_s + " " + b.to_s + " gives " + result + " but should " + r
end
end
# I don't yet understand why the computation
# res << ((i * num_accents % size) < num_accents)
# gives the same rhythm as the algorithm by Toussaint
# but all tested are in the same necklace at least
# chapter 2
test(5, 13,"x..x.x..x.x..", 1)
# chapter 4
test(1, 2, "x.")
test(1, 3, "x..")
test(1, 4, "x...")
test(4, 12, "x..x..x..x..")
test(2, 3, "x.x")
test(2, 5, "x.x..", 1)
test(3, 4, "x.xx")
test(3, 5, "x.x.x")
test(3, 7, "x.x.x..", 1)
test(3, 8, "x..x..x.")
test(4, 7, "x.x.x.x")
test(4, 9, "x.x.x.x..", 1)
test(4, 11, "x..x..x..x.")
test(5, 6, "x.xxxx")
test(5, 7, "x.xx.xx")
test(5, 8, "x.xx.xx.", 1)
test(5, 9, "x.x.x.x.x")
test(5, 11, "x.x.x.x.x..", 1)
test(5, 12, "x..x.x..x.x.")
test(5, 16, "x..x..x..x..x...", 1) # obvious misprint in the paper
test(7, 8, "x.xxxxxx")
test(7, 12, "x.xx.x.xx.x.", 2)
test(7, 16, "x..x.x.x..x.x.x.")
test(9, 16, "x.xx.x.x.xx.x.x.", 3)
test(11, 24, "x..x.x.x.x.x..x.x.x.x.x.")
test(13, 24, "x.xx.x.x.x.x.xx.x.x.x.x.", 5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment