lib/onedclusterer/ckmeans.rb
def clusters
      @clusters_result ||=begin
        if @unique <= 1 # A single cluster that contains all elements
          return [data]
        end

        rows = @data_size
        cols = kmax

        distance = *Matrix.zero(cols + 1, rows + 1) # 'D'
        backtrack = *Matrix.zero(cols + 1, rows + 1) # 'B'

        fill_dp_matrix(data.insert(0, nil), distance, backtrack)

        # Choose an optimal number of levels between Kmin and Kmax
        kopt = select_levels(data, backtrack, kmin, kmax)
        backtrack = backtrack[0..kopt]

        results = []
        backtrack(backtrack) do |k, left, right|
          results[k] = data[left..right]
        end
        results.drop(1)
      end
    end
def clusters
      @clusters_result ||=begin
        if @unique <= 1 # A single cluster that contains all elements
          return [data]
        end

        rows = @data_size
        cols = kmax

        distance = *Matrix.zero(cols + 1, rows + 1) # 'D'
        backtrack = *Matrix.zero(cols + 1, rows + 1) # 'B'

        fill_dp_matrix(data.insert(0, nil), distance, backtrack)

        # Choose an optimal number of levels between Kmin and Kmax
        kopt = select_levels(data, backtrack, kmin, kmax)
        backtrack = backtrack[0..kopt]

        results = []
        backtrack(backtrack) do |k, left, right|
          results[k] = data[left..right]
        end
        results.drop(1)
      end
    end
def clusters @clusters_result ||= begin if @unique <= 1 # A single cluster that contains all elements
 return [ data ] end rows = @data_size cols = kmax distance = Matrix . zero ( cols + 1 , rows + 1 ) # 'D'
 backtrack = Matrix . zero ( cols + 1 , rows + 1 ) # 'B'
 fill_dp_matrix ( data . insert ( 0 , nil ) , distance , backtrack ) # Choose an optimal number of levels between Kmin and Kmax
 kopt = select_levels ( data , backtrack , kmin , kmax ) backtrack = backtrack [ 0 .. kopt ] results = [ ] backtrack ( backtrack ) do | k , left , right | results [ k ] = data [ left .. right ] end results . drop ( 1 ) end end
Input:
  data -- a vector of numbers, not necessarily sorted
  kmin -- the minimum number of clusters expected
  kmax -- the maximum number of clusters expected
 If only kmin is given exactly kmin clusters will be returned
 else algorithm chooses an optimal number between Kmin and Kmax
 returns clustered data as array
Input : data -- a vector of numbers not necessarily sorted kmin -- the minimum number of clusters expected kmax -- the maximum number of clusters expected If only kmin is given exactly kmin clusters will be returned else algorithm chooses an optimal number between Kmin and Kmax returns clustered data as array