Last active
May 10, 2023 13:08
-
-
Save PlugFox/8eed2788e7e6427d76db68800a1539af to your computer and use it in GitHub Desktop.
Remove from array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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