Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Random rnd = new Random();
- void Main()
- {
- const int cTests = 100;
- const int cRuns = 100;
- const int cVals = 10;
- var numFails = 0;
- for (int iRun = 0; iRun < cRuns; iRun++)
- {
- var a = new int[cVals];
- var b = new int[cVals];
- int max = -1;
- var reordering = new int[cVals];
- for (int i = 0; i < cVals; i++)
- {
- a[i] = rnd.Next(10000);
- b[i] = rnd.Next(10000);
- }
- Console.WriteLine($"Starting run {iRun}");
- for (int iTest = 0; iTest < cTests; iTest++)
- {
- Shuffle(b);
- if (max < 0)
- {
- (reordering, max) = FindEstimatedMax(a, b);
- }
- else
- {
- var (newReordering, newMax) = FindEstimatedMax(a, b);
- if (newMax > max)
- {
- Console.WriteLine($"Oops! Algorithm failed! oldMax = {max}, newMax = {newMax}");
- reordering = newReordering;
- max = newMax;
- numFails++;
- }
- }
- }
- }
- Console.WriteLine($"End of Tests. {numFails} failures.");
- }
- void Shuffle(IList<int> b)
- {
- for (int i = 0; i < b.Count - 1; i++)
- {
- var j = i + rnd.Next(b.Count - i);
- (b[i], b[j]) = (b[j], b[i]);
- }
- }
- int XorSum(IList<int>a, IList<int>b)
- {
- return a.Zip(b).Select(t => t.First ^ t.Second).Sum();
- }
- (int[] reordering, int max) FindEstimatedMax(IList<int> a, IList<int> b)
- {
- var bCopy = new int[a.Count];
- var bestReordering = new int[a.Count];
- var nSuccess = 0;
- var curMax = -1;
- Array.Copy(b.ToArray(), bCopy, b.Count);
- while (nSuccess < 100)
- {
- Shuffle(bCopy);
- while (FindIncreasingTranspose(a, bCopy));
- var newMax = XorSum(a, bCopy);
- if (newMax > curMax)
- {
- nSuccess = 0;
- curMax = newMax;
- Array.Copy(bCopy, bestReordering, b.Count);
- }
- else
- {
- nSuccess++;
- }
- }
- return (bestReordering, curMax);
- }
- bool FindIncreasingTranspose(IList<int> a, IList<int> b)
- {
- for (var i = 0; i < a.Count - 1; i++)
- {
- for (var j = i + 1; j < a.Count; j++)
- {
- if ((a[i] ^ b[j]) + (a[j] ^ b[i]) - (a[i] ^ b[i]) - (a[j] ^ b[j]) > 0)
- {
- (b[i], b[j]) = (b[j], b[i]);
- return true;
- }
- }
- }
- return false;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement