Home > Blockchain >  I want to calculate the occurrences of each number in aray in Dart
I want to calculate the occurrences of each number in aray in Dart

Time:10-09

i have that needs me to make a function that counts the occurrences of each number in an array [2,5,6,6,8,4,2,5,2] and print it like this 2 -> 3 times 6 -> 2 times and so on I did it before but it was to count the occurrences of one number not all of them so can anyone help ... Thanks in advance

to update this is the code I used to count the occurrences of one number

int countTwo(List<int> arr, int value) {
  int counter = 0;
  for (int i = 0; i < arr.length; i  ) {
    if (arr[i] == value) {
      counter  ;
    }
  }
  return counter;
}

void main() {
  List<int> arr = [5, 6, 15, 2, 8, 2, 38, 2];
  int x = countTwo(arr, 2);
  print(x);
}

CodePudding user response:

You can create a set from list to get unique int.

final data = [2, 5, 6, 6, 8, 4, 2, 5, 2];
final dataSet = data.toSet();

int counter(int number) {
  final int counter = data.where((element) => element == number).length; //you can use for loop here too
  return counter;
}

for (int i = 0; i < dataSet.length; i  ) {
  print(
      "number ${dataSet.elementAt(i)} -> ${counter(dataSet.elementAt(i))} times");
}

And with your method just do

final data = [2, 5, 6, 6, 8, 4, 2, 5, 2];
final dataSet = data.toSet();

for (int i = 0; i < dataSet.length; i  ) {
  final checkNUmber = dataSet.elementAt(i);
  print("number $checkNUmber->  ${countTwo(data, checkNUmber)} times");
}

Result

number 2 -> 3 times
number 5 -> 2 times
number 6 -> 2 times
number 8 -> 1 times
number 4 -> 1 times

CodePudding user response:

I'd use a map to collect the count:

var count = <int, int>{};
for (var n in data) {
  count[n] = (count[n] ?? 0)   1;
}

After that, you have all the individual elements, and the number of times it occurred:

for (var n in count.keys) {
  print("$n: ${count[n]} times");
}
  • Related