Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Calculate the mean of a list with counts for each value

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 ;
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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));
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading