1

Как найти соседей элемента (8 соседей - по вертикали, по горизонтали, по диагонали ) в двумерном массиве, при условии, что соседей можно искать и через границу массива?

Имеется двумерный массив, например, такой

введите сюда описание изображения

Для поиска соседей элемента внутри массива все просто. Комбинируем координаты текущего элемента с единицей и между собой data[x +/- 1][y +/- 1] и получаем такую картину

введите сюда описание изображения

Для элемента на границе массива соседи следующиевведите сюда описание изображения

Для элемента в углу

введите сюда описание изображения

Итого мы имеем 1 общий случай, когда элемент лежит внутри массива и 8 частных (4 на границах, 4 на углах)

Конечно, можно использовать case-оператор, перебрать эти случаи поиска соседей и решить эту задачу в лоб, но есть более изящные способы решения?

2 ответа 2

2

Как насчет так, где в getElementsArr(i, j) i и j - позиция центрального объекта:

var arr = [
  ["0:0","0:1","0:2","0:3"],
  ["1:0","1:1","1:2","1:3"],
  ["2:0","2:1","2:2","2:3"],
  ["3:0","3:1","3:2","3:3"]
];

function getElementsArr(i, j) {
  var yIndexes = getIndexes(arr, i);
  var xIndexes = getIndexes(arr[i], j);
  var thisArr = {
    topLeft: arr[yIndexes.prev][xIndexes.prev],
    top: arr[yIndexes.prev][xIndexes.curr],
    topRight: arr[yIndexes.prev][xIndexes.next],
    centerLeft: arr[yIndexes.curr][xIndexes.prev],
    center: arr[yIndexes.curr][xIndexes.curr],
    centerRight: arr[yIndexes.curr][xIndexes.next],
    bottomLeft: arr[yIndexes.next][xIndexes.prev],
    bottom: arr[yIndexes.next][xIndexes.curr],
    bottomRight: arr[yIndexes.next][xIndexes.next],
  }
  
  return thisArr;
}

function getIndexes(arr, i) {
  let prev = i - 1;
  let next = i + 1;
  if (i == 0) {
    prev = arr.length - 1;
  } else if (i == arr.length - 1) {
    next = 0;
  }
  
  return {
    prev: prev,
    curr: i,
    next: next };
}

console.log(getElementsArr(0,0));

PS. Может только дайте более звучные названия функциям и переменным...

1
  • спасибо! интересное решение
    – while1pass
    4 мая 2017 в 11:02
2

Есть всего два граничных случая:

  1. когда значение больше максимального индекса
  2. когда значение меньше 0

Для того, чтобы обработать их можно воспользоваться простой формулой:

var index = (currIndex+count)%count;

Пример:

var size = 5;

function* getRelative(rowIndex, colIndex) {
  for (var i = -1; i <= 1; i++) {
    for (var j = -1; j <= 1; j++) {
      if (i == 0 && j == 0) continue;
      yield {
        rowIndex: (rowIndex + i + size) % size,
        colIndex: (colIndex + j + size) % size
      }
    }
  }
}

$('td').click(function() {
  $('.relative,.active').removeClass('relative active');
  var $this = $(this).addClass('active');
  var colIndex = $this.index();
  var rowIndex = $this.parent().index();
  [...getRelative(rowIndex, colIndex)].forEach(coord => {
    $(`tr:nth-child(${coord.rowIndex+1}) td:nth-child(${coord.colIndex+1})`).addClass('relative');
  });
});
table {
  border-collapse: collapse;
}

td {
  border: 1px solid black;
  width: 50px;
  height: 50px;
  text-align: center;
}

.active {
  background-color: #add;
}

.active::after {
  content: '2';
}

.relative {
  background-color: rgba(75, 255, 0, 0.59)
}

.relative::after {
  content: '1';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
  </tr>
</table>

И еще

function* getRelative(rowIndex, colIndex, rowCount, colCount) {
  for (var i = -1; i <= 1; i++) {
    for (var j = -1; j <= 1; j++) {
      if (i == 0 && j == 0) continue;
      yield {
        rowIndex: (rowIndex + i + rowCount) % rowCount,
        colIndex: (colIndex + j + colCount) % colCount
      }
    }
  }
}

function clearCells() {
  var cells = document.querySelectorAll('.active, .relative');
  for (var i = 0, len = cells.length; i < len; i++) {
    cells[i].classList.remove('active', 'relative')
  }
}

function createTable(rowCount, colCount) {
  return Array.from({
    length: rowCount
  }, () => Array.from({
    length: colCount
  })).reduce((table, cells, rowIndex) => {
    table.appendChild(cells.reduce((row, _, colIndex) => {
      var cell = document.createElement('td');
      cell.addEventListener('click', function() {
        clearCells();
        this.classList.add('active');
        [...getRelative(rowIndex, colIndex, rowCount, colCount)].forEach(coord => {
          document.querySelector(`tr:nth-child(${coord.rowIndex+1}) td:nth-child(${coord.colIndex+1})`).classList.add('relative');
        });
      })
      row.appendChild(cell);
      return row;
    }, document.createElement('tr')))
    return table;
  }, document.createElement('table'))
}

document.body.appendChild(createTable(5, 10));
table {
  border-collapse: collapse;
}

td {
  border: 1px solid black;
  width: 20px;
  height: 20px;
  text-align: center;
}

.active {
  background-color: #add;
}

.active::after {
  content: '2';
}

.relative {
  background-color: rgba(75, 255, 0, 0.59)
}

.relative::after {
  content: '1';
}

2
  • Очень изящное решение через генераторы, мог бы поставить два ответа, оба отметил
    – while1pass
    4 мая 2017 в 11:01
  • @while1pass, что за два ответа? У меня вроде один: вычисление корректного индекса для каждого из восьми соседей. Ааааааааааа :-D это я тебя не так понял :-)
    – Grundy
    4 мая 2017 в 11:17

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.