I saw examples on how to do kind of similar stuff but never exactly what I want, I'm wondering how to do it properly so if you can give me an hint I would be really happy ! :)
["a","a","b","a","c","c","b","b","b","d","a"] =====> [2,1,1,2,3,1,1]
CodePudding user response:
The basic process will be
void main(List<String> args) {
final data = ["a", "a", "b", "a", "c", "c", "b", "b", "b", "d", "a"];
List<int> result = [];
int c = 1;
for (int i = 0; i < data.length - 1; i ) {
if (data[i] == data[i 1]) {
c ;
} else {
result.add(c);
c = 1;
}
}
// we are still missing the count for last element
/// if last two elements are same update the value
if (data[data.length - 1] == data[data.length - 2]) {
result[result.length - 1] = result[result.length - 1] 1;
}
//else add 1 for last char
else {
result.add(1);
}
print(result.toString());
}
CodePudding user response:
I tried to create a new flutter app to test the code, because it doesn't work in pure darts code without flutter. I have used the splitBetween
method.
import 'package:collection/collection.dart';
final data = ["a", "a", "b", "a", "c", "c", "b", "b", "b", "d", "a"];
void main() {
// I put this code here just for testing,
var foo = data.splitBetween((a, b) => a != b).map((a) => a.length);
print(foo);
runApp(const MyApp()); // Remember that you're inside flutter app.
}
Output in console :
(2, 1, 1, 2, 3, 1, 1)