Calculate the mean of a list with counts for each value

Advertisements

I have a List<ChickenByWeight> I’m struggling to find a way to calculate the average weight for all the chickens

class ChickenByWeight extends Equatable {
  final int count;
  final int weight;

  ChickenByWeight({
    required this.weight,
    required this.count,
  });

  ChickenByWeight copyWith({
    int? count,
    int? weight,
  }) {
    return ChickenByWeight(
      count: count ?? this.count,
      weight: weight ?? this.weight,
    );
  }

  @override
  List<Object?> get props => [
        count,
        weight,
      ];
}

I’d like to return the result with this method :

double averageChickenWeight(List<ChickenByWeight> chickenByWeight) {
  
  return ;
}

>Solution :

I’m not sure if I understand correctly, but I believe the code below is what you need. I omitted Equatable since it seems to not have any influence here.

class ChickenByWeight { 
  final int count;
  final int weight;

  ChickenByWeight({
    required this.weight,
    required this.count,
  });

  ChickenByWeight copyWith({
    int? count,
    int? weight,
  }) {
    return ChickenByWeight(
      count: count ?? this.count,
      weight: weight ?? this.weight,
    );
  }
}

double averageChickenWeight(List<ChickenByWeight> chickenByWeight) {
  var sum = 0.0;
  var count = 0.0;
  for(final chicken in chickenByWeight){
    sum += chicken.weight * chicken.count;
    count += chicken.count;
  }
  return sum / count;
}

void main() {
  var chickenList = <ChickenByWeight>[];
  final chicken1 = ChickenByWeight(weight:3,count: 1);
  final chicken2 = ChickenByWeight(weight:5,count: 2);
  chickenList.add(chicken1);
  chickenList.add(chicken2);
  
  print(averageChickenWeight(chickenList));
}

Leave a Reply Cancel reply