Created
May 17, 2017 07:47
-
-
Save kacpak/c3988834f43154a9cdaf4064df8387df to your computer and use it in GitHub Desktop.
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; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace OperatoryKrzyzowania | |
{ | |
class Program | |
{ | |
static Random random = new Random(); | |
static int[] pmx(int[] os1, int[] os2) | |
{ | |
int[] p = new int[] { random.Next(os1.Length + 1), random.Next(os1.Length + 1) }; // przecięcie jest przed liczbą, dlatego +1 by móc przeciąć za liczbą | |
//int[] p = new int[] { 3, 7 }; | |
Array.Sort(p); | |
int[] keys = os1.Skip(p[0]).Take(p[1] - p[0]).ToArray(); | |
int[] values = os2.Skip(p[0]).Take(p[1] - p[0]).ToArray(); | |
Dictionary<int, int> map = keys.Zip(values, (k, v) => new { k, v }).ToDictionary(item => item.k, item => item.v); | |
int[] child = Enumerable.Repeat(-1, os1.Length).ToArray(); | |
// Remember first values | |
for (int i = p[0]; i < p[1]; i++) | |
child[i] = os1[i]; | |
// Save and substitute rest | |
for (int i = 0; i < os2.Length; i++) | |
{ | |
if (child[i] == -1) | |
{ | |
if (map.ContainsKey(os2[i])) { | |
child[i] = map[os2[i]]; | |
} else { | |
child[i] = os2[i]; | |
} | |
} | |
} | |
//printArray(os1, "os1: "); | |
//printArray(os2, "os2: "); | |
//printArray(keys, "keys: "); | |
//printArray(values, "value: "); | |
//printArray(child, "child: "); | |
//Console.WriteLine(); | |
return child; | |
} | |
static void Main(string[] args) | |
{ | |
//int[] os1 = new int[] { 1, 2, 3, 4, 5, 6 }; | |
//int[] os2 = new int[] { 5, 2, 4, 6, 1, 3 }; | |
int[] os1 = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; | |
int[] os2 = new int[] { 4, 5, 2, 1, 8, 7, 6, 9, 3 }; | |
pmx(os1, os2); | |
pmx(os1, os2); | |
pmx(os1, os2); | |
pmx(os1, os2); | |
pmx(os1, os2); | |
pmx(os1, os2); | |
Console.ReadLine(); | |
} | |
static void printArray(IEnumerable<int> enumerable, string before = "") | |
{ | |
Console.Write(before); | |
foreach (var i in enumerable) | |
Console.Write(i + " "); | |
Console.WriteLine(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment