2D Array - подсчет числовой последовательности - PullRequest
0 голосов
/ 02 октября 2018

Я как-то полностью на шланге.Это следует понимать по функциональному принципу и не звучит особенно сложно?Но я не могу придумать возможное решение.

У меня есть 2D-массив.Это 8х8.Каждое поле может содержать число от 1 до 7.Теперь я хочу «вернуть» в каждой строке по вертикали / горизонтали числа, которые по крайней мере в 3 раза подряд расположены друг за другом или друг с другом.Таким образом, теоретически pro / series существует вероятность того, что возможны две последовательности чисел.

Теперь реальный вопрос: КАК я могу просто вернуть числа, которые по крайней мере 3х подряд вширина высота!?Доволен индексом.Сейчас я много пробовал, ни с итерациями, ни с рекурсией.Но я пришел к желаемому результату - или я не вижу леса за деревьями ...?

Пример:

output

Ответы [ 2 ]

0 голосов
/ 03 октября 2018

Проблема решена, я найду решение.

private static List<List<Point>> Test(int[][] Matrix, Point Position, List<List<Point>> Pos) {
  if (Position.Y < Matrix.Length && Position.X < Matrix[Position.Y].Length) {
    if (Similar(Matrix, new Point(Position.X, Position.Y), new Point(Position.X + 1, Position.Y))) {
      List<Point> List = Pos.LastOrDefault();
      if (List == null) List = new List<Point>();

      List.Add(new Point(Position.X, Position.Y));
      List.Add(new Point(Position.X + 1, Position.Y));

      Pos.Remove(Pos.LastOrDefault());
      Pos.Add(List.Distinct().ToList());
    } else Pos.Add(new List<Point>());

    return Test(Matrix, new Point(Position.X + 1, Position.Y), Pos);
  } else {
    if (Position.Y < Matrix.Length && Position.X == Matrix[Position.Y].Length)
      return Test(Matrix, new Point(0, Position.Y + 1), Pos);
  }

  return Pos.Where(Entity => Entity.Count > 0).ToList();
}
0 голосов
/ 02 октября 2018

Давайте сначала сделаем это для 1d-массива.

У нас есть массив с 8 числами.

public List<int> Get3InRow(int[] array)
    {
        List<int> found = new List<int>(); // the list of found numbers we return
        int counter = 1;  //counts the amount of identical numbers found.
        int number = array[0];  //the number we are counting.

        //now comes the for loop
        for (int i = 1; i < 8; i++)
        {
            if (array[i] == number) counter++; // if we find a match counter goes up
            else
            {  //else reset the counter and search for new number.
                number = array[i];
                counter = 1;
            }
            if (counter == 3) found.Add(array[i]); // if we find 3 matching numbers ad it to the found list
        }
        return found;
    }

теперь, чтобы сделать это с 2d-массивом.Все, что нам нужно сделать, это добавить еще один цикл.

public List<int> Get3InRow(int[,] array)
    {
        List<int> found = new List<int>(); // the list of found numbers we return
        int counter = 1;  //counts the amount of identical numbers found.
        int number = 9;  //the number we are counting. (we chose 9 because none of the numbers in the array have this number.)

        //now comes the for loop
        for (int i = 0; i < 8; i++)
        {
            for (int j = 0; j < 8; j++)
            {                    
                if (array[i,j] == number) counter++; // if we find a match counter goes up
                else
                {  //else reset the counter and search for new number.
                    number = array[i,j];
                    counter = 1;
                }
                if (counter == 3) found.Add(array[i,j]); // if we find 3 matching numbers ad it to the found list
            }
        }

        //we repeat the for loops with i and j interchanged(in array[]) because now we want to check the other axis
        for (int i = 0; i < 8; i++)
        {
            for (int j = 0; j < 8; j++)
            {
                if (array[j,i] == number) counter++; // if we find a match counter goes up
                else
                {  //else reset the counter and search for new number.
                    number = array[j,i];
                    counter = 1;
                }
                if (counter == 3) found.Add(array[j,i]); // if we find 3 matching numbers ad it to the found list
            }
        }
        return found;
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...