Skip to content

Instantly share code, notes, and snippets.

@FeepingCreature
Created May 29, 2012 16:26
Show Gist options
  • Save FeepingCreature/2829381 to your computer and use it in GitHub Desktop.
Save FeepingCreature/2829381 to your computer and use it in GitHub Desktop.
bintest with success
module bintest;
// assume array is sorted from small to big
int findIndexOfOne(int[] array, int value) {
if (!array.length) raise new Error "$value not found during binsearch";
auto test-idx = array.length / 2;
if (array[test-idx] == value) return test-idx;
if (array[test-idx] < value) // everything before test-idx is also smaller
return findIndexOfOne(array[test-idx+1 .. $], value) + test-idx+1;
else // everything after test-idx is also larger
return findIndexOfOne(array[0..test-idx], value);
}
void main() {
auto array = [-15, 2, 3, 7, 7, 9, 15348, 99999];
auto pos = [for val <- array: findIndexOfOne(array, val)].eval[];
writeln "$pos"; // [0, 1, 2, 4, 4, 5, 6, 7]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment