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

To find the variance of all nodes in a linked list in TypeScript, we first need to calculate the mean value of the nodes. We can do this by iterating over the linked list and adding the values of each node to a sum variable and keeping count of the number of nodes. Once we have the sum and the count, we can calculate the mean by dividing the sum by the count.

index.ts
class Node {
  value: number;
  next: Node | null;
  constructor(value: number) {
    this.value = value;
    this.next = null;
  }
}

class LinkedList {
  head: Node | null = null;
  // add method for adding new nodes to the linked list
  
  variance() {
    let count = 0;
    let sum = 0;
    let currNode = this.head;
    while (currNode) {
      sum += currNode.value;
      count++;
      currNode = currNode.next;
    }
    const mean = sum / count; // calculate mean
    let varianceSum = 0;
    currNode = this.head;
    while (currNode) {
      varianceSum += Math.pow((currNode.value - mean), 2);
      currNode = currNode.next;
    }
    const variance = varianceSum / count;
    return variance;
  }
}
715 chars
34 lines

In this implementation, we first iterate through the linked list to calculate the mean value of the nodes. Then, we iterate through the linked list again to calculate the variance of the nodes. The variance of the list is the final output. The variance formula we have used is the sample variance formula that divides the sum of squares of differences between each value and mean by (number of values -1).

gistlibby LogSnag