I have two Maps, bookingMap & reserveMap. Both maps have the same keys but different values. bookingMap is for the guest to book the seats whereas reserveMap is for the backend team. I want to compare the values of both maps with the help of their respective keys, if the values are equal I want to increment the totalSeats by +1 or +2. If the values don't match I want to subtract totalSeats by -1 or -2 respectively. Both maps have the same keys but map 1 can contain 10 out of 5 keys and Map 2 contains exactly 10 keys and values. If use if-else statements the code will be long. Is there a method or a way I'm missing?
The code below checks all the values, not the individuals.
import 'package:collection/collection.dart';
void main() {
compareValues();
}
void compareValues() {
int totalSeats = 0;
// Booking Map
Map<String, int> bookingMap = {
'c1': 1,
'c2': 2,
'c3': 3,
'c4': 5,
};
//Seat Map
Map<String, int> reserveMap = {
'c1': 1,
'c2': 2,
'c3': 3,
'c4': 4,
'c5': 6,
};
if (DeepCollectionEquality().equals(bookingMap.values, reserveMap.values)) {
totalSeats = totalSeats + 1;
} else {
totalSeats = totalSeats - 1;
}
print(totalSeats);
}
I think you need iterate through all keys and compare values. Something like that:
void compareValues() {
int totalSeats = 0;
Map<String, int> bookingMap = {
'c1': 1,
'c2': 2,
'c3': 3,
'c4': 5,
};
Map<String, int> reserveMap = {
'c1': 1,
'c2': 2,
'c3': 3,
'c4': 4,
'c5': 6,
};
var equals = true;
for (final kv in bookingMap.entries) {
if (reserveMap[kv.key] != kv.value) {
equals = false;
break;
}
}
if (equals) {
totalSeats = totalSeats + 1;
} else {
totalSeats = totalSeats - 1;
}
print(totalSeats);
}
With the help of and altering #chessmax answer I solved the issue with the following code.
void compareValues() {
int totalSeats = 0;
Map<String, int> bookingMap = {
'c1': 1,
'c2': 2,
'c3': 3,
'c4': 4,
'c5': 6,
};
Map<String, int> reserveMap = {
'c1': 1,
'c2': 2,
'c3': 3,
'c4': 4,
'c5': 66,
};
for (final kv in bookingMap.entries) {
if (reserveMap[kv.key] == kv.value) {
totalSeats = totalSeats + 1;
} else {
totalSeats = totalSeats - 1;
}
}
print(totalSeats);
}
Related
I have this list [null, 3, 5, null] and I want to join the values in-between nulls and put it into the same list
For example:
[null, 3, 5, null] into [null, 35, null]
I made this one extension that groups all the values between two nulls
extension GroupByNull<T> on List<T> {
List<List<T>> groupByNull() {
final groupedList = <List<T>>[];
var list = this;
for (var i = 0; i < list.length; i++) {
if (list[i] == null) {
if (i > 0) {
groupedList.add(list.sublist(0, i));
}
list = list.sublist(i + 1);
i = 0;
}
}
if (list.isNotEmpty) {
groupedList.add(list);
}
return groupedList;
}
}
Which returns [[3, 5]] for [null, 3, 5, null]... But I want it to be joined together and added to the original list in the same index
How can I solve this...
thank you.
Note that you can't operate on an arbitrary List<T> because there's no general way to combine two elements of some arbitrary type T. What you want could make sense for List<int?> or maybe List<String?>. (Or maybe it could work on an arbitrary List<T> input if you want a List<String?> output.)
Assuming that you want to operate on List<int?>, then basically as you iterate over your input list, keep track of your current accumulated value. If you encounter null, add the current value (if any) to your output List along with the null. Don't forget to add the current accumulated value (if any) when you're done iterating in case there isn't a final null element.
extension GroupByNull on List<int?> {
List<int?> groupByNull() {
var result = <int?>[];
int? currentValue;
for (var element in this) {
if (element != null) {
currentValue = (currentValue ?? 0) * 10 + element;
} else {
if (currentValue != null) {
result.add(currentValue);
currentValue = null;
}
result.add(currentValue);
}
}
if (currentValue != null) {
result.add(currentValue);
}
return result;
}
}
void main() {
print([null, 3, 5, null].groupByNull()); // Prints: [null, 35, null]
print([3, 5, null].groupByNull()); // Prints: [35, null]
print([3, 5, null, null].groupByNull()); // Prints: [35, null, null]
print([null, 3, 5].groupByNull()); // Prints: [null, 35]
print([null, null, 3, 5].groupByNull()); // Prints: [null, null, 35]
print([null, 0, 0, 0, null].groupByNull()); // Prints: [null, 0, null]
print([null, 1, 2, null, 3, 4, null]
.groupByNull()); // Prints: [null, 12, null, 34, null]
print([null].groupByNull()); // Prints: [null]
print([null, null].groupByNull()); // Prints: [null, null]}
}
You can use this solution.
extension GroupByNull<T> on List<T> {
List groupByNull() {
final groupedList = [];
var list = this;
list.removeWhere( (value) => value == null); // remove all null values
groupedList.add(int.parse(list.join(""))); // combine number left in list
groupedList.insert(0,null); // add null
groupedList.add(null);
return groupedList;
}
}
i have input like this [1, 1, 3, 3, 5, 5, 5, 5]
the condition is : 1 is blue/biru, 3, is green/hijau, 5 is black/hitam;
for each double number, count as pair, i.e 1, 1 = 1 pair of blue
i experiment with this code :
function charCount(word) {
let freq = [];
for (let i = 0; i < word.length; i++) {
if (word[i] == [1]) {
freq.push("biru");
} else if (word[i] == [3]) {
freq.push("hijau");
} else {
freq.push("hitam");
}
// freq[char] ? freq[char]++ : freq[char] = 1;
}
let count = {}
for (let i = 0; i < freq.length; i++) {
let char = freq[i];
// count[char] ? (Math.floor(count[char]++)/2) : (Math.floor(count[char] = 1)/2);
count[char] ? count[char]++/2 : (count[char] = 1)/2;
}
return pasang
}
console.log(charCount([ 1, 1, 3, 3, 5, 5, 5, 5]));
ouput from this code is { biru: 1.5, hijau: 1.5, hitam: 3.5 }
but i got problem, when want to be divided by 2
please help me
I want to delete a certain number of duplicates from an ordered list in Dart. It could also be taken as the deletion of duplicates after a certain number of occurrences.
To illustrate my question, I will give an example, which could explain the problem much better than my words:
I want to keep 3 duplicates max. of each number or category.
This is what I am given:
[1,1,1,1,2,2,2,2,3,4,4,5,5,5,5,5]
Notice the occurrences per number. 3 and 4 are only present in the array one and two times correspondingly.
This is what I want that list to become:
[1,1,1,2,2,2,3,4,4,5,5,5]
void main(List<String> args) {
var numbers = [1,1,1,1,2,2,2,2,3,4,4,5,5,5,5,5];
const max_duplicates = 3;
var base = numbers.toSet();
var result = <int>[];
base.forEach((number) {
var counter = numbers.where((e) => e == number).length;
result.addAll(List.filled(counter > max_duplicates ? max_duplicates : counter, number));
});
print(result);
}
Result:
[1, 1, 1, 2, 2, 2, 3, 4, 4, 5, 5, 5]
var toRemove = [];
var localScore = 10;
var cuentaLocal = 0;
filteredCareTakers.forEach((item) {
if (localScore > item['score']) {
localScore = item['score'];
cuentaLocal = 0;
} else if (localScore == item['score']) {
if (cuentaLocal == 2) {
toRemove.add(item);
} else {
cuentaLocal++;
}
}
});
filteredCareTakers.removeWhere((element) => toRemove.contains(element));
void main() {
final input = [1, 1, 1, 1, 2, 2, 2, 2, 3, 4, 4, 5, 5, 5, 5, 5];
final seen = <Object, int>{};
var output = <Object>[];
for (var e in input) {
seen[e] = (seen[e] ?? 0) + 1;
if (seen[e]! <= 3) output.add(e);
}
print(output);
}
or for the functional programmers:
void main() {
final input = [1, 1, 1, 1, 2, 2, 2, 2, 3, 4, 4, 5, 5, 5, 5, 5];
final count = <Object, num>{};
final output = input.where((e) {
count[e] = (count[e] ?? 0) + 1;
return count[e]! <= 3;
}).toList();
print(output);
}
I imagine you could do something with .fold and and a tuple, but that just seems like too much work. :)
How could I split a string into chunks of all available combinations? For example:
"12345"
Would output:
[1,
12,
123,
1234,
12345,
2,
23,
234,
2345,
3,
34,
345,
4,
45]
This is as far as I've gotten:
String title = "12345";
List<String> keywordsList = List();
String temp = "";
String temp2 = "";
for (int i = 0; i < title.length; i++) {
temp = temp + title[i];
if (temp.length > 1) temp2 = temp2 + title[i];
keywordsList.add(temp);
if (temp2.length != 0) keywordsList.add(temp2);
}
print(keywordsList);
return keywordsList;
},
Which results in:
[1, 12, 2, 123, 23, 1234, 234, 12345, 2345]
Super stuck now, will appreciate any help.
Thanks in advance!
You can achieve in following way.
String number = '12345';
List<String> listnumber = number.split("");
List<int> output = [];
for (int i = 0; i < listnumber.length; i++) {
if (i != listnumber.length - 1) {
output.add(int.parse(listnumber[i]));
}
List<String> temp = [listnumber[i]];
for (int j = i + 1; j < listnumber.length; j++) {
temp.add(listnumber[j]);
output.add(int.parse(temp.join()));
}
}
print(output.toString());
How I can get the most popular number from a list in dart without using any third party libraries?
var list = [0, 1, 1, 2, 2, 2, 3, 3, 4]; // most popular number is 2
If there are two or more popular numbers then the output should be a List with both values. Example:
One popular number:
var list = [0, 1, 1, 2, 2, 2, 3, 3, 4];
// Output should be [2]
Two or more popular numbers:
var list = [0, 1, 1, 2, 2, 2, 3, 3, 3];
// Output should be [2, 3]
Thank you in advance for your help!
This works...you can optimize it
var list = [1, 1, 2, 2, 3, 4, 5];
list.sort();
var popularNumbers = [];
List<Map<dynamic, dynamic>> data = [];
var maxOccurrence = 0;
var i = 0;
while (i < list.length) {
var number = list[i];
var occurrence = 1;
for (int j = 0; j < list.length; j++) {
if (j == i) {
continue;
}
else if (number == list[j]) {
occurrence++;
}
}
list.removeWhere((it) => it == number);
data.add({number: occurrence});
if (maxOccurrence < occurrence) {
maxOccurrence = occurrence;
}
}
data.forEach((map) {
if (map[map.keys.toList()[0]] == maxOccurrence) {
popularNumbers.add(map.keys.toList()[0]);
}
});
print(popularNumbers);
try this to count each element in list:
var list = [0, 1, 1, 2, 2, 2, 3, 3, 4];
var popular = Map();
list.forEach((l) {
if(!popular.containsKey(l)) {
popular[l] = 1;
} else {
popular[l] +=1;
}
});
I guess I found the solution.
Let me explain it to you:
I had queried through your list and checked whether the keys of the map contains the element or not. If the map does not contain the element as the key then, it will create a key from the element and pass 1 as the value. If the map does contain the element as a key then it will simply increment the value.
Once the map is ready, I had sorted the map values and stored them in a List. From the sorted map values I had taken the last element from the list of sorted values because we had sorted it in ascending order so the most popular value will be at last.
At last, I had queried through the map and check whether the value of the particular key is equal to the popularValue or not. If it is then we are adding the current key and value to the mostPopularValues list.
If I got something wrong please let me know.
void main() {
List list = [0, 1, 1, 1, 2, 2, 2, 3, 3, 4];
List mostPopularValues = [];
var map = Map();
list.forEach((element) {
if (!map.containsKey(element)) {
map[element] = 1;
} else {
map[element] += 1;
}
});
print(map);
// o/p : {0: 1, 1: 3, 2: 3, 3: 2, 4: 1}
List sortedValues = map.values.toList()..sort();
print(sortedValues);
// o/p : [1, 1, 2, 3, 3]
int popularValue = sortedValues.last;
print(popularValue);
// o/p : 3
map.forEach((k, v) {
if (v == popularValue) {
mostPopularValues.add("$k occurs $v time in the list");
}
});
print(mostPopularValues);
// o/p : [1 occurs 3 time in the list, 2 occurs 3 time in the list]
}
Not sure if that's the best solution, but it works pretty well. Let me know if there are any doubts.
final list = [0, 1, 1, 2, 2, 2, 3, 3, 4];
// Count occurrences of each item
final folded = list.fold({}, (acc, curr) {
acc[curr] = (acc[curr] ?? 0) + 1;
return acc;
}) as Map<dynamic, dynamic>;
// Sort the keys (your values) by its occurrences
final sortedKeys = folded.keys
.toList()
..sort((a, b) => folded[b].compareTo(folded[a]));
print('Most popular value: ${sortedKeys.first}'); // 1
print('Second most popular value: ${sortedKeys[1]}'); // 2
I have solved this problem by defining an extension on Iterable:
extension MostPopularItemsExtension<E> on Iterable<E> {
/// Returns the most popular items, where all items in the returned
/// list have the same number of occurances. If [this] is empty, returns an
/// empty list
///
/// Examples:
/// `[1,2,3,2].mostPopularItems() == [2]`
/// `[1,1,2,2].mostPopularItems() == [1,2]`
Iterable<E> mostPopularItems() {
if (isEmpty) return [];
final itemsCounted = <E, int>{};
for (final e in this) {
if (itemsCounted.containsKey(e)) {
itemsCounted[e] = itemsCounted[e]! + 1;
} else {
itemsCounted[e] = 1;
}
}
final highestCount = (itemsCounted.values.toList()..sort()).last;
return itemsCounted.entries
.where((e) => e.value == highestCount)
.map((e) => e.key);
}
}
The basic idea is to count all occurrences of each item in a Map object, get the highest count from this map and then return all items that have that specific number of occurrences.