Created
June 6, 2014 22:25
-
-
Save st0le/cb39c5de6b5b31ff231f to your computer and use it in GitHub Desktop.
Finding Minimum with a Non-Transitive Comparator
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
using System; | |
namespace SharpFoo | |
{ | |
class Program | |
{ | |
private Random rnd = new Random(); | |
static void Main(string[] args) | |
{ | |
new Program().Go(); | |
Console.ReadKey(); | |
} | |
private void Go() | |
{ | |
const int N = 10; | |
int[] arr = RandomArray(N); | |
Console.WriteLine(string.Join(",", arr)); | |
try | |
{ | |
int minPos = Minimum(arr, N); | |
Console.WriteLine(arr[minPos]); | |
} | |
catch (Exception e) | |
{ | |
Console.WriteLine(e.Message); | |
} | |
} | |
//Pseudo Non-transitive comparator | |
//This comparator function works on a stupid rule | |
//Say we compare a and b, if eithor a or b is odd, we simply perform a less(a,b) | |
//If both are even, we perform less(b,a) | |
// So essentially, cmp(2,3) is True, cmp(3,10) is True....and then cmp(10,2) is also True! wtf! | |
// 2 < 3 | |
// 3 < 10 | |
// but 2 is not less than 10. | |
private bool cmp(int a, int b) | |
{ | |
if (a % 2 == 1 || b % 2 == 1) | |
return a < b; | |
else | |
return b < a; | |
} | |
private int Minimum(int[] arr, int N) | |
{ | |
int minIndex = 0; | |
for (int i = 1; i < N; i++) | |
if (!cmp(arr[minIndex], arr[i])) // cmp returns true if a comes before b | |
minIndex = i; | |
for (int i = minIndex - 1; i >= 0; i--) | |
if (cmp(arr[i], arr[minIndex])) | |
throw new Exception("No minimum according to comparator."); | |
return minIndex; | |
} | |
private int[] RandomArray(int N) | |
{ | |
int[] arr = new int[N]; | |
for (int i = 0; i < N; i++) | |
arr[i] = (rnd.Next(100) | 1) + 1; | |
return arr; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment