Skip to content

Instantly share code, notes, and snippets.

@oliverguhr
Last active August 1, 2018 14:28
Show Gist options
  • Save oliverguhr/99127765dbc71b3780e6b4aa624d0c86 to your computer and use it in GitHub Desktop.
Save oliverguhr/99127765dbc71b3780e6b4aa624d0c86 to your computer and use it in GitHub Desktop.
public List<List<String>> BalancedLatinSquares(int n)
{
var result = new List<List<String>>() { };
for (int i = 0; i < n; i++)
{
var row = new List<String>();
for (int j = 0; j < n; j++)
{
var cell = ((j % 2 == 1 ? j / 2 + 1 : n - j / 2) + i) % n;
cell++; // start counting from 1
row.Add(cell.ToString());
}
result.Add(row);
}
if (n % 2 == 1)
{
var reversedResult = result.Select(x => x.AsQueryable().Reverse().ToList()).ToList();
result.AddRange(reversedResult);
}
return result;
}
public List<List<String>> BalancedLatinSquares(int n)
{
var result = Enumerable.Range(0, n)
.Select(i =>
Enumerable.Range(0, n).Select(j => ((((j % 2 == 1 ? j / 2 + 1 : n - j / 2) + i) % n)+1).ToString()).ToList()
)
.ToList();
if (n % 2 == 1)
{
var reversedResult = result.Select(x => x.AsQueryable().Reverse().ToList()).ToList();
result.AddRange(reversedResult);
return result;
}
public static IEnumerable<IEnumerable<int>> GenerateBalancedLatinSquares(int n)
{
bool isEven (int i) => i % 2 == 0;
int calulateCell(int j, int i) => ((isEven(j) ? n - j / 2 : j / 2 + 1) + i) % n + 1;
var result = Enumerable
.Range(0, n)
.Select(i =>
Enumerable
.Range(0, n)
.Select(j =>calulateCell(j,i))
);
if (n % 2 == 1)
{
var reversedResult = result.Select(x => x.Reverse());
result = result.Concat(reversedResult);
} return result;
}
public static class BalancedLatinSquare
{
/**
* Orders the given sequence in from of a balanced latin square
*/
public static IEnumerable<IEnumerable<T>> Arrange<T>(IEnumerable<T> items)
{
var latinSquare = GenerateBalancedLatinSquares(items.Count());
return latinSquare.Select(row => row.Select(cellIndex => items.ElementAt(cellIndex-1)).ToList()).ToList();
}
/**
* Generates a balanced latin square for the numbers 1 to n
*/
public static IEnumerable<IEnumerable<int>> GenerateBalancedLatinSquares(int n)
{
bool isEven (int i) => i % 2 == 0;
int calculateCell(int j, int i) => ((isEven(j) ? n - j / 2 : j / 2 + 1) + i) % n + 1;
var result = Enumerable
.Range(0, n)
.Select(i =>
Enumerable
.Range(0, n)
.Select(j =>calulateCell(j,i))
);
if (n % 2 == 1)
{
var reversedResult = result.Select(x => x.Reverse());
result = result.Concat(reversedResult);
} return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment