Home > Blockchain >  Calculate the mean of a list with counts for each value
Calculate the mean of a list with counts for each value

Time:07-24

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

CodePudding user response:

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

CodePudding user response:

try this:

double averageChickenWeight(List<ChickenByWeight> chickenByWeight) {
  return chickenByWeight.map((m) => m.weight).reduce((a, b) => a   b) / chickenByWeight.length;
  
}

for this sample:

List<ChickenByWeight> sample = [ ChickenByWeight(weight:1,count:1), ChickenByWeight(weight:2,count:2)];
  print(averageChickenWeight(sample));

the output would be 1.5

CodePudding user response:

Another way:

import 'package:collection/collection.dart';

class User {
  int age;
  String name;
  
  User(this.age, this.name);
}
void main() {
  List<User> list = [];
  for (int i = 0; i < 10; i  ) {
    User user = User(i, "Name $i");
    list.add(user);
  }
  
  double avg = list.map((e) => e.age).average;
  print(avg); 
}
  • Related