first thing first my question is very similar to this one. In fact, it's the same thing, except that I need to group every user like this below:
Everyone under 12 (exclusive)
Then, from 12 - 19
Then, from 20 - 29
...
More than 80 (inclusive)
Based on the answer from dasblinkenlight in the other question, I was able to do:
var ageStats = vModel
.GroupBy(l => 10 * (l.Age / 10))
.OrderBy(x => x.Key)
.Select(g => new
{
Name = g.Key,
Count = g.Select(l => l.Age).Count()
}).ToList();
For a result set of :
0-9
10-19
20-29
...
So what should I do to accomplish the pattern I have to ?
Thank you very much !!
var ages = new[] { 12, 19, 29, 80 };
var grouped = ages.Select(r => new {
Name = r,
Count = vModel.Count(x => x.Age >= r)
});
try this, but i don't know the performance
var ages = new int[12, 19, 29, 80];
var func = new Func<int, int>(a=>{
for(var i = 0; i<ages.Length; i++){
if(a<ages[i])
continue;
return i;
}
return 0;
});
vModel.GroupBy(m=>func(m.Age))....
You could use approach mentioned here and use this code:
var ages = new List<int> { 12, 19, 29, 39, 49, 59, 69, 80, int.MaxValue};
var categories = vModel.GroupBy(item => ages.FirstOrDefault(ceil => ceil >= item));
Related
I'm really confused on how I'm gonna find the index of item in array where there's a lot of duplicated words.
List<String> _words = "the quick brown fox jumps over the lazy dog".split(" ");
now I want to get the all the index in word "the" programmatically.
I expect a result of
List indexOfWords = _words.indexOfAll("the");
print(indexOfWords);
// [0, 6]
You can define indexOfAll as an extension method. I would implement it like this:
extension ListExtension<T> on List<T> {
List<int> indexOfAll(T item) => [
for (int i = 0; i < length; i++)
if (this[i] == item) i,
];
}
You can create an extension method. like this:
extension Occurrences on List {
List<int> indexOfAll(String pattern) {
List<int> indexes = [];
for (int i = 0; i < this.length; i++) {
if (this[i] == pattern) {
indexes.add(i);
}
}
return indexes;
}
}
then you can use it as function on your list
print(_words.indexOfAll("the")); // [0, 6]
I don't know if there is a direct solution for this job. To solve this problem I developed a function called GetIndexes() and it works successfully.
This example prints the following output to the console:
[the, quick, brown, fox, jumps, over, the, lazy, dog]
[3, 9, 15, 19, 25, 30, 34, 39]
The solution I developed is available below:
void main()
{
String text = "the quick brown fox jumps over the lazy dog";
var split = ' ';
List<int> indexes = [];
List<String> words;
words = text.split(split);
GetIndexes(text, split, indexes);
print(words);
print(indexes);
}
void GetIndexes(String text, var split, List<int> indexes)
{
int index = 0;
for(int i=0 ; i<text.length; ++i)
{
if(text[i] == split)
{
indexes.insert(index, i);
++index;
}
}
}
I have List list= [1,2,3,4,4,4,9,6,7,7,7,8,8,8,8,8,8,8];
how can i return 8 as max repeated value
Something like this?
void main() {
final list = [1, 2, 3, 4, 4, 4, 9, 6, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8];
print(findMaxDuplicatedElementInList(list)); // 8
}
T findMaxDuplicatedElementInList<T>(Iterable<T> list) => list
.fold<Map<T, int>>(
{},
(map, element) =>
map..update(element, (value) => value + 1, ifAbsent: () => 1))
.entries
.reduce((e1, e2) => e1.value > e2.value ? e1 : e2)
.key;
I'd just write it out, as straight-forward as possible:
Assuming the equal elements are always adjacent, and list cannot be empty, return arbitrary element with maximal count if there is more than one:
T maxDuplicated<T>(List<T> elements) {
var element = elements.count;
var count = 1;
var maxElement = element;
var maxCount = count;
for (var i = 1; i < elements.length; i++) {
var nextElement = elements[i];
if (element != nextElement) {
element = nextElement;
count = 1;
} else {
count += 1;
if (count > maxCount) {
maxElement = element;
maxCount = count;
}
}
}
return maxElement;
}
Assuming elements come in random order, so we need to remember every element we have seen,
still not allowing an empty list as input:
T maxDuplicated<T>(List<T> elements) {
var maxCount = 1;
var maxElement = elements.first
var seen = <T, int>{maxElement: maxCount};
for (var i = 1; i < elements.length; i++) {
var element = elements[i];
var count = seen[element] = (seen[element] ?? 0) + 1;
if (count > maxCount) {
maxCount = count;
maxElement = element;
}
}
return maxElement;
}
(Alternatively, I'd sort the list first, if allowed, to always be in the former situation. It's not faster than using a map, if we assume hash map lookup to be a constant time operation, but it will be more memory efficient.)
In a list of sequential integers, is there a simple way to locate where another integer would be placed (between two of the list members)?
main() {
var myList = new List();
myList.addAll([0, 4, 10, 20, 33, 45, 55, 64]);
int setStart;
int currentPosition;
currentPosition = 12;
// if currentPosition is greater than or equal to myList[fooPosition]
// but less than myList[barPosition]
// setStart = myList[foo]
}
So since the currentPosition is 12, the correct answer for setStart would be 10.
Try checking out package:collection's binarySearch.
Ok, figured it out myself. Pretty simple really. I just needed to add another variable (x) to indicate the list position of the upper number:
for (var i = 0; i < myList.length; i++) {
var x = i + 1;
if (currentPosition >= myList[i] && currentPosition < myList [x]) {
setStart = myList[i];
};
};
How do you get the min and max values of a List in Dart.
[1, 2, 3, 4, 5].min //returns 1
[1, 2, 3, 4, 5].max //returns 5
I'm sure I could a) write a short function or b) copy then sort the list and select the last value,
but I'm looking to see if there is a more native solution if there is any.
Assuming the list is not empty you can use Iterable.reduce :
import 'dart:math';
main(){
print([1,2,8,6].reduce(max)); // 8
print([1,2,8,6].reduce(min)); // 1
}
If you don't want to import dart: math and still wants to use reduce:
main() {
List list = [2,8,1,6]; // List should not be empty.
print(list.reduce((curr, next) => curr > next? curr: next)); // 8 --> Max
print(list.reduce((curr, next) => curr < next? curr: next)); // 1 --> Min
}
You can now achieve this with an extension as of Dart 2.6:
import 'dart:math';
void main() {
[1, 2, 3, 4, 5].min; // returns 1
[1, 2, 3, 4, 5].max; // returns 5
}
extension FancyIterable on Iterable<int> {
int get max => reduce(math.max);
int get min => reduce(math.min);
}
An example to get Min/Max value using reduce based on condition for a list of Map objects
Map studentA = {
'Name': 'John',
'Marks': 85
};
Map studentB = {
'Name': 'Peter',
'Marks': 70
};
List<Map> students = [studentA, studentB];
// Get student having maximum mark from the list
Map studentWithMaxMarks = students.reduce((a, b) {
if (a["Marks"] > b["Marks"])
return a;
else
return b;
});
// Get student having minimum mark from the list (one liner)
Map studentWithMinMarks = students.reduce((a, b) => a["Marks"] < b["Marks"] ? a : b);
Another example to get Min/Max value using reduce based on condition for a list of class objects
class Student {
final String Name;
final int Marks;
Student(this.Name, this.Marks);
}
final studentA = Student('John', 85);
final studentB = Student('Peter', 70);
List<Student> students = [studentA, studentB];
// Get student having minimum marks from the list
Student studentWithMinMarks = students.reduce((a, b) => a.Marks < b.Marks ? a : b);
If your list is empty, reduce will throw an error.
You can use fold instead of reduce.
// nan compare to any number will return false
final initialValue = number.nan;
// max
values.fold(initialValue, (previousValue, element) => element.value > previousValue ? element.value : previousValue);
// min
values.fold(initialValue, (previousValue, element) => element.value < previousValue ? element.value : previousValue);
It can also use to calculate sum.
final initialValue = 0;
values.fold(initialValue, (previousValue, element) => element.value + previousValue);
Although fold is not cleaner than reduce for getting min/max, it is still a powerful method to do more flexible actions.
For empty lists: This will return 0 if list is empty, the max value otherwise.
List<int> x = [ ];
print(x.isEmpty ? 0 : x.reduce(max)); //prints 0
List<int> x = [1,32,5];
print(x.isEmpty ? 0 : x.reduce(max)); //prints 32
int minF() {
final mass = [1, 2, 0, 3, 5];
mass.sort();
return mass[0];
}
void main() {
firstNonConsecutive([1,2,3,4,6,7,8]);
}
int? firstNonConsecutive(List<int> arr) {
var max = arr.reduce((curr, next) => curr > next? curr: next);
print(max); // 8 --> Max
var min = arr.reduce((curr, next) => curr < next? curr: next);
print(min); // 1 --> Min
return null;
}
If you need a more sophisticated min/max, such as finding an object with a min/max of a field, or use of a comparison predicate, use minBy() and maxBy() from the collection package:
import 'package:collection/collection.dart';
class Person {
final String name;
final int age;
Person(this.name, this.age);
#override
String toString() => '$name (age $age)';
}
main() {
final alice = Person('Alice', 30);
final bob = Person('Bob', 40);
final chris = Person('Chris', 25);
final dan = Person('Dan', 35);
final people = [alice, bob, chris, dan];
print('Youngest is ${minBy(people, (e) => e.age)}');
print('Oldest is ${maxBy(people, (e) => e.age)}');
print('First alphabetically is ${minBy(people, (e) => e.name)}');
print('Last alphabetically is ${maxBy(people, (e) => e.name)}');
print('Largest name length times age is ${maxBy(people, (e) => e, compare: (a, b) => (a.name.length * a.age).compareTo(b.name.length * b.age))}');
}
Output:
Youngest is Chris (age 25)
Oldest is Bob (age 40)
First alphabetically is Alice (age 30)
Last alphabetically is Dan (age 35)
Largest name length times age is Alice (age 30)```
I have the following query:
view.reduce.group_level(5).keys
which returns:
[["1f9c79a33f399a7937d880c5f31e8dbc", 2011, 12, 29, 13], ["1f9c79a33f399a7937d880c5f31e8dbc", 2011, 12, 29, 14], ["c38332ffc275b6c70bcf06ffc39ddbdd", 2011, 12, 29, 13], ["c38332ffc275b6c70bcf06ffc39ddbdd", 2011, 12, 29, 14]]
The first key is an id and the other keys are year, month, day, hour
I would like all the rows between 2010 and 2013. So I want to ignore the first key.
The problem is that i need to set the first parameter to get the results but i want to get all the results for all the keys.
for example: view.reduce.group_level(5).startkey(["every_possible_key", 2010]).endkey(['every_possible_key", 2013, {}])
If i leave the first key blank than i get nothing. If i give it "\u9999" than i get everything and it ignores the 2nd key.
Somebody knows what I am doing wrong?
Thanks a lot.
map:
function(d) {
if (d['type'] == 'State' && d['driver_id'] && d['name'] && d['created_at']) {
var dt = new Date(d.created_at);
emit([d.driver_id, dt.getFullYear(), dt.getMonth() + 1, dt.getDate(), dt.getHours()], d.name);
}
}
reduce:
function(k,v,r) {
var result = {
'hire': 0, 'hired': 0, 'arrived': 0, 'pick up': 0, 'drop off': 0,
'missed': 0, 'rider cancel': 0, 'driver cancel': 0, 'no show': 0,
'avail': 0, 'unavail': 0, 'other': 0
};
if (r) {
var row = null;
for (i in v) {
row = v[i];
for (j in row) {
result[j] += row[j];
}
}
} else {
for (i in v) {
if (result[v[i]] != null) {
result[v[i]] += 1;
} else {
result['other'] += 1;
}
}
}
return result;
}
What you're "doing wrong" is to use a key you don't need in your query as the first key of your view.
If you need it for another query, create another view.