Reputation: 567
Using Dart, what is a good way of iterating through a list of strings in search for a specific one, when string is found move it to the front of the list?
For example, if looking for the letter 'b'. Find it, move it up front.
['a', 'b', 'c']
=> ['b', 'a', 'c']
Not knowing Dart very well, I solved it with simple for-loop
List<String> example = ['a', 'b', 'c'];
for (int i = 0; i< example.length; i++) {
if (example[i] == 'b') {
final temp = example[0];
example[0] = example[i];
example[i] = temp;
}
}
Is there a way in dart to call some array method on a list to find a specific item, remove it from the original list and return the removed item? Like .splice()
in JS.
Upvotes: 3
Views: 9556
Reputation: 512226
When approaching this problem it is helpful to know some properties of the list data structure:
Thus, although @FloW's answer is very concise and easy to read, it's slow because it requires both removing from the middle of a list and adding to the beginning of a list:
final example = ["a", "b", "c"];
if (example.remove("b")) {
example.insert(0, "b");
}
For short lists it probably doesn't matter but for long lists this could have noticeable performance impacts.
Since the requirements in the original problem allow for swapping rather than removing and inserting, the for loop solution given in the question itself is better in my opinion:
List<String> example = ['a', 'b', 'c'];
for (int i = 0; i < example.length; i++) {
if (example[i] == 'b') {
final temp = example[0];
example[0] = example[i];
example[i] = temp;
}
}
Although this search still requires visiting every item in the list, it doesn't require moving everything if a match is found. Only the two affected indices are changed.
You could improve the efficiency even more by adding a break
statement to the end of the if
block, which would make it equivalent to using indexOf
:
final example = ['a', 'b', 'c'];
final value = 'b';
final index = example.indexOf(value);
example[index] = example[0];
example[0] = value;
Upvotes: 3
Reputation: 1266
for List delete and then insert to move it up to front
if(example.remove("b"))
example.insert(0, "b");
Upvotes: 4