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

To find the variance of all nodes in a linked list, we can follow the following steps:

  1. Traverse the linked list and find the mean of all the nodes in it.
  2. Traverse the linked list again and find the difference between each node's value and the mean.
  3. Square the difference, and accumulate the result in a variable.
  4. Finally, divide the accumulated value by the total number of nodes in the linked list to get the variance.

Here's the Swift code to implement the algorithm:

main.swift
class Node {
    var value: Double
    var next: Node?

    init(_ value: Double, _ next: Node? = nil) {
        self.value = value
        self.next = next
    }
}

func variance(of list: Node?) -> Double {
    var mean = 0.0
    var count = 0
    
    // Traverse the linked list and find the mean
    var current = list
    while current != nil {
        mean += current!.value
        count += 1
        current = current!.next
    }
    mean /= Double(count)
    
    // Traverse the linked list again and accumulate the squared difference
    var variance = 0.0
    current = list
    while current != nil {
        let diff = current!.value - mean
        variance += diff * diff
        current = current!.next
    }
    
    // Divide accumulated value by the total number of nodes to get variance
    variance /= Double(count)
    return variance
}
859 chars
37 lines

We can use this function by creating a linked list, and passing its head to the variance function:

main.swift
let list = Node(2, Node(4, Node(6)))
let result = variance(of: list) // returns 2.6666666666666665
99 chars
3 lines

The result variable will contain the variance of all the nodes in the linked list.

gistlibby LogSnag