find the variance of all nodes in a linked list in ruby

To find the variance of all nodes in a linked list in Ruby, we first need to calculate the mean of the values stored in the nodes. Once we have calculated the mean, we can calculate the variance by iterating through the linked list and summing up the squares of the differences between each value and the mean.

Here is an example implementation of a LinkedList class with a method variance, which calculates the variance of all nodes in the linked list:

main.rb
class Node
  attr_accessor :value, :next

  def initialize(value, next_node = nil)
    @value = value
    @next = next_node
  end
end

class LinkedList
  attr_accessor :head
  
  def initialize
    @head = nil
  end
  
  def append(value)
    if @head.nil?
      @head = Node.new(value)
    else
      current = @head
      while current.next
        current = current.next
      end
      current.next = Node.new(value)
    end
  end
  
  def mean
    current = @head
    sum = 0
    count = 0
    while current
      sum += current.value
      count += 1
      current = current.next
    end
    sum.to_f / count
  end

  def variance
    m = mean
    current = @head
    sum_sq_diff = 0
    count = 0
    while current
      sum_sq_diff += (current.value - m) ** 2
      count += 1
      current = current.next
    end
    sum_sq_diff.to_f / count
  end
end
861 chars
54 lines

To use this class, you can create a new instance of a linked list, append some values, and call the variance method:

main.rb
list = LinkedList.new
list.append(1)
list.append(2)
list.append(3)
puts list.variance # Output: 0.6666666666666666
115 chars
6 lines

This will output the variance of the values stored in the linked list.

gistlibby LogSnag