Is there a way to write this macro that expands array access in such a way that larger arrays can be written in a less verbose way?
/// Avoid manually expanding an expression, eg:
///
/// let array = unpack!([some.vec; 3]);
///
/// Expands into: [some.vec[0], some.vec[1], some.vec[2]]
///
/// Supports expanding into different bracket types based on the input args.
macro_rules! unpack {
([$v_:expr; 2]) => { { let v = $v_; [v[0], v[1]] } };
(($v_:expr; 2)) => { { let v = $v_; (v[0], v[1]) } };
({$v_:expr; 2}) => { { let v = $v_; {v[0], v[1]} } };
([$v_:expr; 3]) => { { let v = $v_; [v[0], v[1], v[2]] } };
(($v_:expr; 3)) => { { let v = $v_; (v[0], v[1], v[2]) } };
({$v_:expr; 3}) => { { let v = $v_; {v[0], v[1], v[2]} } };
([$v_:expr; 4]) => { { let v = $v_; [v[0], v[1], v[2], v[3]] } };
(($v_:expr; 4)) => { { let v = $v_; (v[0], v[1], v[2], v[3]) } };
({$v_:expr; 4}) => { { let v = $v_; {v[0], v[1], v[2], v[3]} } };
}
To reduce verbosity you can construct recursive macro.
macro_rules! unpack {
({$vec:expr; $count:expr}) => {
unpack!([$vec; $count])
};
(($vec:expr; $count:expr)) => {
unpack!([$vec; $count])
};
([$vec:expr; $count:expr]) => {
$vec[0..$count]
};
}
fn main() {
let vec = vec![1, 2, 3, 4, 5];
assert_eq!([1, 2], unpack!({vec; 2}));
assert_eq!([1, 2, 3], unpack!((vec; 3)));
assert_eq!([1, 2, 3, 4], unpack!([vec; 4]));
}
Every macro can be called with (), [] and {} brackets, so if you don't need additional pair of brackets your macro can be as simple as that:
macro_rules! unpack {
($vec:expr; $count:expr) => {
$vec[0..$count]
};
}
fn main() {
let vec = vec![1, 2, 3, 4, 5];
assert_eq!([1, 2], unpack!{vec; 2});
assert_eq!([1, 2, 3], unpack!(vec; 3));
assert_eq!([1, 2, 3, 4], unpack![vec; 4]);
}
Example from Rust Book.
Related
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 have a raw list like this:
var listRaw = [
{
"listName": "listA",
"listValue": [1, 2, 3]
},
{
"listName": "listB",
"listValue": [4, 5, 6]
},
{
"listName": "listC",
"listValue": [7, 8, 9]
}
];
and empty lists like this:
List<int> listA = [];
List<int> listB = [];
List<int> listD = [];
List<List<int>> listFilled = [listA, listB, listD];
How can I get the names of empty lists as a condition to add listVaule in listRaw to them if name of empty list == listName? => then listFilled will have the result [[1,2,3], [4,5,6], []]
So pls help me, this is my code so far
void main() {
var listRaw = [
{
"listName": "listA",
"listValue": [1, 2, 3]
},
{
"listName": "listB",
"listValue": [4, 5, 6]
},
{
"listName": "listC",
"listValue": [7, 8, 9]
}
];
List<int> listA = [];
List<int> listB = [];
List<int> listD = [];
List<List<int>> listFilled = [listA, listB, listD];
listRaw.forEach((r) {
listFilled.forEach((f) {
if (r['listName'] == ___ ) { // How to get name of (f)
f.addAll(r['listValue']);
}
});
});
print(listFilled); // want result: [[1,2,3], [4,5,6], []]
}
The variable names that you use are for you to understand what the variable is being used for. The compiler does not know what you named them. It only knows that this variable is pointing towards a specific point of memory.
That being said, what you can do is create your own subclass of the List class which will have a name attached to it. In that way, you can check the name of the List when you want to compare it. Your subclass should be something like this
This is not exact syntax. Just an overview of what needs to be done.
class MyNamedList extends List {
String name;
MyNamedList(String name) {
this.name = name;
}
}
//You can check for name like this
if (r['listName'] == myNamedListObj.name)
var listRaw = [
{
"listName": "listA",
"listValue": [1, 2, 3]
},
{
"listName": "listB",
"listValue": [4, 5, 6]
},
{
"listName": "listC",
"listValue": [7, 8, 9]
}
];
this is a List of Map<String, dynamic>
so what you need to do is create empty List<Map<String,dynamic>>
List<Map<String,dynamic>> list = List.empty(growable:true);//set false if size is fixed.
Then List<List<Map<String,dynamic>>> listFilled = [list1,list2,list3];
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);
}
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 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.