Class: Xi::Bjorklund

Inherits:
Object show all
Defined in:
lib/xi/bjorklund.rb

Overview

Implementation adapted from Nebs’ (MIT licensed) github.com/nebs/bjorklund-euclidean-rhythms

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(pulses, slots, value = nil) ⇒ Bjorklund



7
8
9
10
11
# File 'lib/xi/bjorklund.rb', line 7

def initialize(pulses, slots, value=nil)
  @pulses = pulses.to_i
  @slots = slots.to_i
  @value = value || 1
end

Instance Attribute Details

#pulsesObject (readonly)

Returns the value of attribute pulses.



5
6
7
# File 'lib/xi/bjorklund.rb', line 5

def pulses
  @pulses
end

#slotsObject (readonly)

Returns the value of attribute slots.



5
6
7
# File 'lib/xi/bjorklund.rb', line 5

def slots
  @slots
end

#valueObject (readonly)

Returns the value of attribute value.



5
6
7
# File 'lib/xi/bjorklund.rb', line 5

def value
  @value
end

Instance Method Details

#inspectObject



18
19
20
# File 'lib/xi/bjorklund.rb', line 18

def inspect
  "e(#{@pulses}, #{@slots}, #{@value.inspect})"
end

#p(*args, **metadata) ⇒ Object



13
14
15
16
# File 'lib/xi/bjorklund.rb', line 13

def p(*args, **)
  ary = to_a
  ary.map { |v| v ? @value : nil }.p(1 / ary.size, **)
end

#to_aObject



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/xi/bjorklund.rb', line 26

def to_a
  k = @pulses
  n = @slots

  return [] if n == 0 || k == 0

  bins = []
  remainders = []
  k.times { |i| bins[i] = [true] }
  (n-k).times { |i| remainders[i] = [false] }

  return bins.flatten if n == k

  loop do
    new_remainders = []
    bins.each_with_index do |bin, i|
      if remainders.empty?
        new_remainders.push bin
      else
        bin += remainders.shift
        bins[i] = bin
      end
    end

    if new_remainders.any?
      bins.pop new_remainders.count
      remainders = new_remainders
    end

    break unless remainders.size > 1
  end

  return (bins + remainders).flatten
end

#to_sObject



22
23
24
# File 'lib/xi/bjorklund.rb', line 22

def to_s
  to_a.map { |i| i ? 'x' : '.' }.join
end