'Is there a formula that swaps two elements in an array?

Is there a formula that swaps two elements in an array?

for example

nums=['a','b','c','d'];

Swapping d and b and making my new string

nums=['a','d','c','b'];

Since I will apply this process for all the elements in the array, it must be a general system.



Solution 1:[1]

The collection package seems to include a swap method:

import 'package:collection/collection.dart';

void main() {
    var nums=['a','b','c','d'];
    print(nums);
    nums.swap(1,3);
    print(nums);
}

Prints:

[a, b, c, d]
[a, d, c, b]

Install: https://pub.dev/packages/collection/install

dart pub add collection

flutter pub add collection


If you dont want the package import, the link actually includes the implementation, which you can reuse to define your own extension method:

extension Swappable on List {
  void swap(int a, int b) {
    var tmp = this[a];
    this[a] = this[b];
    this[b] = tmp;    
  }
}

Now you can run the same code without the package import.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1