Алгоритм упаковки для списка ячеек в 2D -массиве [закрыто]C#

Место общения программистов C#
Ответить
Anonymous
 Алгоритм упаковки для списка ячеек в 2D -массиве [закрыто]

Сообщение Anonymous »

Я работаю над проектом, где я пытаюсь имитировать землю и океаны. Я использую значение выше определенного числа, чтобы представлять землю и ниже, чтобы представлять воду. У меня есть программа, предназначенная для создания реалистичных островов, но у меня были проблемы с упаковкой их в массив.public struct Coords {
public int x { get; set; } // Equivalent to ROW
public int y { get; set; } // Equivalent to COL
public Coords(int x, int y) {
this.x = x;
this.y = y; }
public override string ToString() => $"({x}, {y})";
}
< /code>
для представления местоположения ячеек в массиве, где находится земля. Список координат эквивалентен острова. У меня также есть программа, которая получает список координат при переводе на новую позицию. < /P>
public static List TranslateCoords(int rows, int cols, List coords, Coords newStart)
{
// Test that it works
if (coords == null || coords.Count == 0)
{
return new List();
}

// Get starting point (minimum x over minimum y)
Coords start = coords.OrderBy(c => c.x).ThenBy(c => c.y).First();

// Get the offset
int dx = newStart.x - start.x;
int dy = newStart.y - start.y;

// Translate
List translated = new List();
foreach (var coordy in coords)
{
int newX = coordy.x + dx;
int newY = coordy.y + dy;

// Check if out of bounds
if (newX < 0 || newX >= rows || newY < 0 || newY >= cols)
{
return new List();
}
translated.Add(new Coords(newX, newY));
}
return translated;
}
< /code>
Проблема, которую я пытаюсь решить, заключается в том, что я хочу собрать группу списков координат в массив и получить большой список всех возможных начальных координат, которые я могу использовать, чтобы затем перевести их в 2D -массив. Это работало в небольшом масштабе, но это занимает много времени, и это было не полезно для списков координат. < /P>
public static List FindValidIslandPlacementsInArray(int[,] inputArray, List sectionList, int rangeMin, int rangeMax, int distance, bool horizontalWrapping, bool verticalWrapping)
{
int rows = inputArray.GetLength(0);
int cols = inputArray.GetLength(1);
var validStarts = new List();
if (sectionList == null || sectionList.Count == 0)
{
return validStarts;
}

// Create a list of cells not to be checked
List cellsExcluded = new List();
List cellsWithinRangeLoL = Utility.Matrices.Selection.SelectSections(inputArray, rangeMin, rangeMax, horizontalWrapping, verticalWrapping);
List cellsWithinRangeDistLoL = Utility.Matrices.Selection.SelectionSectionEdges(inputArray, rangeMin, rangeMax, horizontalWrapping, verticalWrapping, distance);
cellsExcluded.AddRange(Utility.Lists.CollapseLists(cellsWithinRangeLoL));
cellsExcluded.AddRange(Utility.Lists.CollapseLists(cellsWithinRangeDistLoL));

// Iterate through the list, and test each translateList to see if any overlap
for (int i = 0; i < inputArray.GetLength(0); i++)
{
for (int j = 0; j < inputArray.GetLength(1); j++)
{
Coords newStart = new Coords(i, j);
// Iterates through all tiles not directly within a forbidden tile
if (!cellsExcluded.Contains(newStart))
{
List translateList = Utility.Matrices.Transformation.TranslatePosition(sectionList, rows, cols, newStart, horizontalWrapping, verticalWrapping);
bool overlaps = false;
// Tests all cells with a translated list for overlapping
foreach (Coords cellcoord in translateList)
{
if (inputArray[cellcoord.x, cellcoord.y] >= rangeMin && inputArray[cellcoord.x, cellcoord.y]
(игнорируйте оберток и расстояние). Затем я начал с другой версии, которая может быть просто предоставлена ​​списка координат и спуститься вниз по строке, сравнить каждый с массивом, а затем вернуть список массивов координат, где индекс каждого массива соответствует действительному начальному местоположению для списка координат с одним и тем же индексом в данном списке. Я включил настройку опции, где, если Minval был установлен выше 0, после того, как программа достигла этого объема начальных местоположений, которые она бросила (чтобы сэкономить время), в противном случае она обнаружила каждое место.// This algorithm takes a LoL of Coords, representing a section, and returns all possible starting locations
public static List FindValidPlacements(int rows, int cols, List sections, int minimumReturns = -1)
{
List returnableLists = new List();

#region Verify the lists
// Verify the lists are not null
if (sections == null || sections.Count == 0)
{
return returnableLists;
}
// Check to make sure that the total size is not larger than the list capacity
int limit = rows * cols;
int coordcount_verify = 0;
foreach (List list in sections)
{
foreach (Coords coords in list)
{
coordcount_verify++;
}
}
if (coordcount_verify >= limit)
{
return returnableLists;
}
#endregion

// For each section, iterate through every possible permutation (unless we already have a minimum number of returns
int currentSectionIndex = 0;
bool maxReturnsReached = false;

while (currentSectionIndex < sections.Count)
{
// Get the current comparison list
List primaryList = sections[currentSectionIndex];

// Create an int array for testing
int[,] testForPacking = new int[rows, cols];

for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
// Check each cell
}
}
// Iterate current section index
currentSectionIndex ++;
}
return returnableLists;
}
< /code>
Проблема в том, что я не могу понять, как проверить на наличие списков. Доступны ли какие -нибудь алгоритмы упаковки, которые могут сделать это?

Подробнее здесь: https://stackoverflow.com/questions/797 ... a-2d-array
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»