Skip to content

Instantly share code, notes, and snippets.

@PlugFox
Last active May 10, 2023 13:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PlugFox/8eed2788e7e6427d76db68800a1539af to your computer and use it in GitHub Desktop.
Save PlugFox/8eed2788e7e6427d76db68800a1539af to your computer and use it in GitHub Desktop.
Remove from array
/*
* Remove from array
* https://gist.github.com/PlugFox/8eed2788e7e6427d76db68800a1539af
* https://dartpad.dev/8eed2788e7e6427d76db68800a1539af
* Matiunin Mikhail <plugfox@gmail.com>, 08 May 2023
*/
import 'dart:math' show Random;
import 'package:benchmark_harness/benchmark_harness.dart';
final $random = Random();
final $arr = List<int>.generate(10000, (_) => $random.nextInt(1000));
void main() {
$arr;
RemoveEvenBenchmark$Reverse().report();
RemoveEvenBenchmark$Swap().report();
}
class RemoveEvenBenchmark$Reverse extends BenchmarkBase {
RemoveEvenBenchmark$Reverse() : super(r'RemoveEvenBenchmark$Reverse');
@override
void run() {
final arr = $arr.toList();
for (var i = arr.length - 1; i >= 0; i--) {
if (arr[i] % 2 == 0) arr.removeAt(i);
}
assert(arr.every((e) => e % 2 != 0));
}
}
class RemoveEvenBenchmark$Swap extends BenchmarkBase {
RemoveEvenBenchmark$Swap() : super(r'RemoveEvenBenchmark$Swap');
@override
void run() {
final arr = $arr.toList();
var j = 0;
for (var i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0) continue;
if (i != j) arr[j] = arr[i];
j++;
}
arr.length = j;
assert(arr.every((e) => e % 2 != 0));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment