Skip to content

Instantly share code, notes, and snippets.

@korobochka
Created April 4, 2013 20:20
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 korobochka/5314021 to your computer and use it in GitHub Desktop.
Save korobochka/5314021 to your computer and use it in GitHub Desktop.
import std.stdio;
/+
int bins(int[] arr, int what, int left = 0, int right = -1)
{
if(right == -1) right = cast(int)arr.length;
int l = left;
int r = right;
if(l >= r) return -1;
int m = (l + r) / 2;
if(arr[m] == what) return m;
return arr[m] > what ? bins(arr, what, l, m) : bins(arr, what, m + 1, r);
}
+/
// ^ lost this first time
int bins(int[] arr, int what, int skipped = 0)
{
if(arr.length == 0) return -1;
int m = cast(int)arr.length / 2;
if(arr[m] == what) return skipped + m;
return arr[m] > what ? bins(arr[0 .. m], what, skipped) : bins(arr[m + 1 .. $], what, skipped + m + 1);
}
// ^ lost this again, and this ^
void test(int[] arr)
{
writeln(arr);
foreach(i, a; arr)
{
write(a, ' ');
assert(bins(arr, a) == i);
}
writeln();
writeln("1");
assert(bins(arr, 5) == -1);
writeln("2");
assert(bins(arr, 0) == -1);
writeln("3");
assert(bins(arr, 10) == -1);
writeln("+");
}
unittest
{
test([]);
test([1]);
test([1, 2, 3]);
test([1, 2, 3, 4]);
test([1, 2, 3, 4, 6, 7, 8]);
test([1, 2, 3, 4, 6, 7, 8, 9]);
}
int main() { return 0; }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment