.NET 3.x Итератор по двумерному массиву, выдающий окрестность 3х3 - C#
Формулировка задачи:
Прочитал несколько статей про итераторы, почти сделал, а дальше никак - второй день бьюсь. Помогите доделать!
using System; using System.Collections; namespace EnumeratorTest { public class Cell { public int z { get; private set; } public Cell(int x, int y) { z = x * y; } } public class Grid : IEnumerable { private Cell[,] cells; public int height { get; private set; } public int width { get; private set; } public Grid(int height, int width) { this.height = height; this.width = width; cells = new Cell[height, width]; for( int i = 0; i < height; ++i ) { for( int j = 0; j < width; ++j ) { cells[i, j] = new Cell(i, j); } } } public Cell GetCell(int x, int y) { if( x < 0 || x >= width || y < 0 || y >= height ) { return null; } return cells[x, y]; } public IEnumerator GetEnumerator() { return (IEnumerator) new Neighbourhood(this); } } public class Neighbourhood : IEnumerator { private Cell[,] cells; private Grid grid; private int x, y; public Neighbourhood(Grid grid) { this.grid = grid; cells = new Cell[3, 3]; } public bool MoveNext() { ++x; if( x == grid.width ) { x = 0; ++y; } return y != grid.height; } public void Reset() { x = -1; y = 0; } public object Current { get { for( int i = -1; i <= 1; ++i ) { for( int j = -1; j <= 1; ++j ) { this.cells[i + 1, j + 1] = grid.GetCell(x + i, y + j); } } return this; } } public void Display() { for( int i = 0; i < 3; ++i ) { for( int j = 0; j < 3; ++j ) { Console.Write(cells[i, j].z); Console.Write('\t'); } } Console.WriteLine(); } } static class Program { static void Main(string[] args) { Grid grid = new Grid(10, 10); int i = 0; foreach( var neighbourhood in grid ) { Console.WriteLine("Neighbourhood {0}", ++i); neighbourhood.Display(); } } } }
Решение задачи: «.NET 3.x Итератор по двумерному массиву, выдающий окрестность 3х3»
textual
Листинг программы
public object Current { get { //Пределы перебора индексов int Xmin = -1, Xmax = 1, Ymin = -1, Ymax = 1; if(x == 0) { this.cells[0, 0] = null; this.cells[0, 1] = null; this.cells[0, 2] = null; Xmin = 0; } else if(x == grid.width) { this.cells[2, 0] = null; this.cells[2, 1] = null; this.cells[2, 2] = null; Xmax = 0; } if(y == 0) { this.cells[0, 0] = null; this.cells[1, 0] = null; this.cells[2, 0] = null; Ymin = 0; } else if(y == grid.height) { this.cells[0, 2] = null; this.cells[1, 2] = null; this.cells[2, 2] = null; Ymax = 0; } for( int i = Xmin; i <= Xmax; ++i ) { for( int j = Ymin; j <= Ymax; ++j ) { this.cells[i + 1, j + 1] = grid.GetCell(x + i, y + j); } } return this; } }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д