find the standard deviation of all nodes in a linked list in ruby

To find the standard deviation of all nodes in a linked list, we need to:

  1. Calculate the mean of the linked list.
  2. Calculate the variance of the linked list.
  3. Calculate the standard deviation using the variance.

Here's the Ruby code to accomplish this:

main.rb
# Define the Node class
class Node
  attr_accessor :value, :next_node

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

# Define the LinkedList class
class LinkedList
  attr_accessor :head

  def initialize
    @head = nil
  end

  # Method to add a node to the linked list
  def add(number)
    node = Node.new(number)

    if !@head
      @head = node
    else
      current = @head
      while current.next_node != nil
        current = current.next_node
      end
      current.next_node = node
    end
  end

  # Method to calculate the mean of the linked list
  def mean
    sum = 0
    count = 0
    current = @head

    while current != nil
      sum += current.value
      count += 1
      current = current.next_node
    end

    sum.to_f / count
  end

  # Method to calculate the variance of the linked list
  def variance
    sum = 0
    count = 0
    current = @head

    while current != nil
      sum += (current.value - mean) ** 2
      count += 1
      current = current.next_node
    end

    sum.to_f / count
  end

  # Method to calculate the standard deviation of the linked list
  def standard_deviation
    Math.sqrt(variance)
  end
end

# Create a new linked list
list = LinkedList.new
list.add(1)
list.add(2)
list.add(3)
list.add(4)

# Output the standard deviation of the linked list
puts "Standard Deviation: #{list.standard_deviation}"
1414 chars
79 lines

In this code, we define a Node class to represent each node in the linked list, and a LinkedList class to represent the list itself. We then define methods to add nodes to the list, calculate the mean of the list, calculate the variance of the list, and calculate the standard deviation of the list. Finally, we create a new linked list, add some numbers to it, and output the standard deviation of the list.

gistlibby LogSnag