The other day I needed an algorithm to turn a 2D grid into a diamond (by effectively rotating 45 degrees), so I could deal with diagonal sequences as flat enumerables, like so:
1 2 3 1
4 5 6 => 4 2
7 8 9 7 5 3
8 6
9
My algorithm is as follows:
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;
}
Can this be achieved in a more concise format using LINQ?
.. or even just a more concise format? :)
Here's what I came up with:
void Main()
{
var lists = new string[] { "123", "456", "789" };
foreach (var seq in RotateGrid(lists))
Console.WriteLine(string.Join(", ", seq));
}
public IEnumerable<IEnumerable<T>> RotateGrid<T>(IEnumerable<IEnumerable<T>> grid)
{
int rows = grid.Count();
int cols = grid.First().Count();
return
from i in Enumerable.Range(0, rows + cols - 1)
select (
from j in Enumerable.Range(0, i + 1)
where i - j < rows && j < cols
select grid.ElementAt(i - j).ElementAt(j)
);
}
Output:
1
4, 2
7, 5, 3
8, 6
9
This gets a lot cleaner and more performant if you can assume IList<T>
s instead of just IEnumerable<T>
. I'm thinking of a more efficient approach (not using .ElementAt
) that would work with IEnumerable` also, which I will post if I manage to write it.
Update:
Here's my more practical version, that still manages to shoe-horn in a fair amount of linq. It's a reasonably efficient algorithm, in that it only creates an enumerator once for each IEnumerable
.
public IEnumerable<IEnumerable<T>> RotateGrid<T>(IEnumerable<IEnumerable<T>> grid)
{
var enumerators = new LinkedList<IEnumerator<T>>();
var diagonal =
from e in enumerators
where e.MoveNext()
select e.Current;
foreach (var row in grid)
{
enumerators.AddFirst(row.GetEnumerator());
yield return diagonal.ToArray();
}
T[] output;
while (true)
{
output = diagonal.ToArray();
if(output.Length == 0) yield break;
yield return output;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With