Dart Set remove by index - dart

I try to figure out how can i remove from a set by using index. When i remove from the set, the set gets smaller. I get this error: Uncaught Error: RangeError (index): Index out of range: index should be less than 3: 3
Somehow i need to figure out, if i want to remove dog i need to figure out the newIndex which is 2 due to first remove.
I know it's possible to do animals.remove("objectName") but in this case i want remove by index.
final Set<String> animals = {"lion", "tiger", "cat", "dog"};
void main() {
int index = 1;
animals.remove(animals.elementAt(index));
int newIndex = 3;
animals.remove(animals.elementAt(newIndex));
}

Error: RangeError (index): Index out of range means that index 3 is more than the list length. Example:
final Set<String> animals = {"lion", "tiger", "cat", "dog"};
void main() {
// Before removing the item your list has 4 items. All index: 0, 1, 2, 3
int index = 1;
animals.remove(animals.elementAt(index));
// After removing an item from the list, the list has 3 items left. All index: 0, 1, 2
int newIndex = 3; // <- As you can see above the 3 index does not exist in the list.
animals.remove(animals.elementAt(newIndex)); // Uncaught Error: RangeError (index): Index out of range.
}
More safe method:
animals.removeWhere((animal) => animal.contains("tiger"));

Related

Get every n number of elements in list Flutter Dart

I have a list of elements and I need to get a list containing the first element followed by every nth element afterwards. For example: given n = 3 and the list [banana, cherry, apple, pear, kiwi], I need to get the list [banana, pear]. I need this regardless of specific content, since the list depends on user input.
How do I do this using Dart?
You may access list in dart by providing an index like for example:
List<String> fruits = ["banana","cherry","apple","pear","kiwi"];
print(fruits[0]); // Will print to the console "banana";
On your case, you are trying to access index 0 and index 3 which is "banana" and "pear".
You may create a function that accepts an index like:
String getFruit(int index, List<String> fruits) => fruits[index];
print(getFruit[0]); // Will print "banana";
or if you need to actually get the specific ranges you may use:
List<String> fruits =["banana","cherry","apple","pear","kiwi"].getRange(0,4);
// Will give you "banana","cherry","apple","pear
You may check : https://api.dart.dev/be/180791/dart-core/List-class.html for more information.
Edited answer based off the comment:
List<String> getElements(List userInput, nIndex){
List elements = [];
for(int x = 0; x<userInput.length;x++){
if(x % nIndex == 0){
elements.add(userInput[x]);
}
}
return elements;
}
List fruits = ["banana","cherry","apple","pear","kiwi"];
print(getElements(fruits,2));
or you may try to look and use List.retainWhere() depending on your use case.
Dart has a great set of collection operators that make this type of problem pretty straightforward to solve. For example, we could do something like:
extension X<T> on List<T> {
List<T> everyNth(int n) => [for (var i = 0; i < this.length; i += n) this[i]];
}
main() {
final fruit = ["banana", "cherry", "apple", "pear", "kiwi"];
print(fruit.everyNth(3));
}
Output:
[banana, pear]
You can use this extension method, which will work on lists of any type:
extension GetEveryN<T> on List<T> {
List<T> elementsEveryN(int n) {
List<T> result = [];
for(int index = 0; index < length; index +=1) {
if(index % n == 0) {
result.add(this[index]);
}
}
return result;
}
}
Trying it in an example:
List<String> list = ["banana", "cherry","apple", "pear","kiwi"];
print(list.elementsEveryN(2)); // [banana, pear]

How to get the indexes from duplicate values in a list

I have the following code.
R_sigma22 = [matrix([[489.13845994]]), matrix([[1.87773385]]), matrix([[1.8822108]]), matrix([[1.70095661]]), matrix([[1.70095661]]), matrix([[1.8822108]]), matrix([[1.87773385]]), matrix([[489.13845994]])]
R_min = [[1.70095661]]
##find the element indices for duplicate minimum R values##
index = []
bam = len(R_min_MST_list)
for n in range(bam):
index.append(R_sigma22.index(R_min_MST))
Index of minimum R's
[3, 3] <--- 2nd index should be a 4
The second index found should be a 4, not a 3. Any ideas on how I can skip the first duplicate value to the second duplicate?

Create nXn matrix with values incrementing Swift

Im trying to find an easy way to create matrix with self incrementing values i.e., if 3x3 array then it should look like
[[0,1,2],[3,4,5],[6,7,8]]
when I do something like below, I could get all zero's
var arr = Array(repeating: Array(repeating: 0, count: 3), count: 3)
Inorder to acheive, I need to loop through elements and reassign incremented values. Instead of that is there any fast approach I could follow without using for-loop?
A possible approach is to use map() on the range of rows and columns:
let nrows = 3 // Number of rows
let ncols = 3 // Number of columns
let matrix = (0..<nrows).map { row in (0..<ncols).map { col in ncols * row + col } }
print(matrix) // [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
The outer (0..<nrows).map maps each row number to an array (the “row”), and the inner (0..<ncols).map maps each column number to a matrix entry.
With a little bit “tuple magic” you could assign auto-incrementing values:
var entry = 0
let matrix = (0..<nrows).map { _ in (0..<ncols).map { _ in (entry, entry += 1).0 } }
but that's not what I would really recommend.
There is the a Subscripts tutorial on Swift.org showing a Matrix struct example, which I really like

search in maps dart2 , same as list.indexOf?

I Use this sample for search in Map but not work :|:
var xmenList = ['4','xmen','4xmen','test'];
var xmenObj = {
'first': '4',
'second': 'xmen',
'fifth': '4xmen',
'author': 'test'
};
print(xmenList.indexOf('4xmen')); // 2
print(xmenObj.indexOf('4xmen')); // ?
but I have error TypeError: xmenObj.indexOf$1 is not a function on last code line.
Pelease help me to search in map object simple way same as indexOf.
I found the answer:
print(xmenObj.values.toList().indexOf('4xmen')); // 2
or this:
var ind = xmenObj.values.toList().indexOf('4xmen') ;
print(xmenObj.keys.toList()[ind]); // fifth
Maps are not indexable by integers, so there is no operation corresponding to indexOf. If you see lists as specialized maps where the keys are always consecutive integers, then the corresponding operation should find the key for a given value.
Maps are not built for that, so iterating through all the keys and values is the only way to get that result.
I'd do that as:
K keyForValue<K, V>(Map<K, V> map, V value) {
for (var entry in map.entries) {
if (entry.value == value) return key;
}
return null;
}
The entries getter is introduced in Dart 2. If you don't have that, then using the map.values.toList().indexOf(value) to get the iteration position, and then map.keys.elementAt(thatIndex) to get the corresponding key.
If you really only want the numerical index, then you can skip that last step.
It's not amazingly efficient (you allocate a new list and copy all the values). Another approach is:
int indexOfValue<V>(Map<Object, V> map, V value) {
int i = 0;
for (var mapValue in map.values) {
if (mapValue == value) return i;
i++;
}
return -1;
}
You can search using .where(...) if you want to find all that match or firstWhere if you assume there can only be one or you only want the first
var found = xmenObj.keys.firstWhere(
(k) => xmenObj[k] == '4xmen', orElse: () => null);
print(xmenObj[found]);

Select from Tarantool by secondary index with sort by another field and limit/offset

I have some space top with fields:
-id,
-status,
-rating
I have two indexes for space top:
--primary
box.space.top:create_index('primary', { type = 'TREE', unique = true, parts = { 1, 'NUM' } })
--status
box.space.top:create_index('status', { type = 'TREE', unique = false, parts = { 2, 'NUM' } })
I can select by id or status
--select by id
space.top.index.primary:select(someId)
--select by status with limit/offset
space.top.index.status:select({someStatus}, {iterator = box.index.EQ, offset = 0, limit = 20})
Sometimes i need select by status with ordering by rating.
What is the best way? Create another index with parts status, rating and make some tricky query if it`s possible? Or continue select by status and make sort by rating in Lua procedure?
Thanks!
UPD:
Thanks, Kostya!
I modified index status like this:
box.space.top:create_index('status_rating', { type = 'TREE', unique = false, parts = { 2, 'NUM', 3 'NUM' } })
And now i can query:
local active_status = 1
local limit = 20
local offset = 0
box.space.top.index.status_rating:select({active_status}, {iterator = box.index.LE, offset=offset, limit=limit})
Great!
Doesn't make sense to create the third index, if you need to order by rating, just include it into the second index as the second part, and use GE/GT iterator, the data will come out ordered. This is an in-memory database, adding more parts to an index doesn't use up more memory, only slows down insertion a bit.
Call with GE/LE iterator and partial index may work not as expected than there is no matching tuples or limit is too high.
Suppose, we have following tuples (status, rating):
{ 1, 1 }
{ 3, 1 }
{ 3, 2 }
Than call
box.space.top.index.status_rating:select({2}, {iterator = box.index.GE, limit=1})
will return tuple {3, 1} as it greater than {2}
And call
box.space.top.index.status_rating:select({1}, {iterator = box.index.GE, limit=2})
will return two tuples {1, 1}, {3, 1}
In both case tuple {3, 1} may be not expected

Resources