Neulich brauchte ich einen Algorithmus, um ein 2D-Gitter in einen Diamanten zu verwandeln (indem ich es effektiv um 45 Grad drehte), so dass ich diagonale Sequenzen als flache Aufzählungszeichen behandeln konnte, etwa so:
1 2 3 1
4 5 6 => 4 2
7 8 9 7 5 3
8 6
9
Mein Algorithmus sieht folgendermaßen aus:
public static IEnumerable<IEnumerable<T>> RotateGrid<T>(IEnumerable<IEnumerable<T>> grid)
{
int bound = grid.Count() - 1;
int upperLimit = 0;
int lowerLimit = 0;
Collection<Collection<T>> rotated = new Collection<Collection<T>>();
for (int i = 0; i <= (bound * 2); i++)
{
Collection<T> row = new Collection<T>();
for (int j = upperLimit, k = lowerLimit; j >= lowerLimit || k <= upperLimit; j--, k++)
{
row.Add(grid.ElementAt(j).ElementAt(k));
}
rotated.Add(row);
if (upperLimit == bound)
lowerLimit++;
if (upperLimit < bound)
upperLimit++;
}
return rotated;
}
Kann dies in einem prägnanteren Format mit LINQ erreicht werden?
oder auch nur ein prägnanteres Format? :)