вложенные циклы — динамически помечать диагональные блоки с помощью ООП в переполнении стека

Я пытаюсь построить X в диагональных полях. Королева размещается случайным образом. Смотрите изображение ниже.

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

Как видите, только последний X на (5,5) нанесен правильно. В этом примере X должен быть нанесен в графу (1,1), (2,2), (3,3), (4,4) и (5,5). Поскольку королева размещается случайным образом, метод markRelatedDiagonalBoxes должен работать динамически. Ниже Board_model. У любого есть идея, как правильно написать markRelatedDiagonalBoxes, чтобы он отобразил X, как описано выше.

Board_model.php

<?php

/**
* This class will handle:
*  1) Constructing the boards boxes.
*  2) Returning the property $_row.
*  3) Returning the property $_col.
*  4) Returning the property $_box.
*  5) Setting random rows and columns.
*  6) Returning all the related boxes.
*  7) Returning the horizontal related boxes.
*  8) Returning the vertical related boxes.
*  9) Returning the diagonal related boxes.
*/
class Board_model extends CI_Model {

public $randomRow;
public $randomCol;

private $_box;
private $_length;
private $_row;
private $_col;

/**
* This method 1) will:
*  1) Set the $_length property.
*  2) Create an array of new objects, Boxes based on the length of the rows and columns.
* @param int $length
*/
public function __construct() {
parent::__construct();
$this->load->model('box');
$this->_length = 7;
for($row=0; $row < $this->_length; $row++){
for($col=0; $col< $this->_length; $col++){
$this->_row = $row;
$this->_col = $col;
$this->_box[$row+1][$col+1] = new Box($row+1, $col+1);
}
}
}


/**
* This method 2) will:
*  1) Return the $_row property.
* @return int
*/
public function getRow() {
return $this->_row;
}

/**
* This method 3) will:
*  1) Return the $_col property.
* @return int
*/
public function getCol() {
return $this->_col;
}

/**
* This method 4) will:
*  1) Return the $_box property based on the specified row and column.
* @param $row
* @param $col
* @return mixed
*/
public function getBox($row, $col) {
return $this->_box[$row][$col];
}

/**
* This method 5) will:
*  1) Randomly choose a number within the rang from 1 to the $_length property and place it in the property $randomRow.
*  2) Randomly choose a number within the rang from 1 to the $_length property and place it in the property $randomCol.
*  3) Execute the MarkRelatedHorizontalBoxes method.
*  4) Execute the MarkRelatedVerticalBoxes method.
*  5) TODO: Execute the MarkRelatedDiagonalBoxes method.
*/
public function setRandomColRow() {
// STATIC RANDOM TEST NUMBER
//mt_srand(1234534);
$this->randomRow = mt_rand(1, $this->_length);
$this->randomCol = mt_rand(1, $this->_length);

// Set piece
$this->getBox($this->randomRow,$this->randomCol)->setPiece("&#9813");

$this->relatedDiagonalBoxes();
return $this->_box;
}

function object_to_array($object) {
return (array) $object;
}

/**
* This method 7) will:
*  1) Create the related vertical array
*  2) Loop thew the array
*  3) Get the box position and place and X in the box as piece
*  4) TODO: Check if the box is empty
*/
public function markRelatedVerticalBoxes() {
for($row = 0; $row < $this->_length; $row++) {
$verticalBoxes[$row+1] = $row+1;
// Delete the random cel out of the array
unset($verticalBoxes[$this->randomRow]);
}
foreach ($verticalBoxes as $verticalBox) {
$this->getBox($verticalBox,$this->randomCol)->setPiece("X");
}
}

/**
* This method 8) will:
*  1) Create the related horizontal array
*  2) Loop thew the array
*  3) Get the box position and place and X in the box as piece
*/
public function markRelatedHorizontalBoxes() {
for($col = 0; $col < $this->_length; $col++) {
$horizontalBoxes[$col+1] = $col+1;
// Delete the random cel out of the array
unset($horizontalBoxes[$this->randomCol]);
}
foreach ($horizontalBoxes as $horizontalBox) {
$this->getBox($this->randomRow, $horizontalBox)->setPiece("X");
}
}

public function markRelatedDiagonalBoxes() {

$row = $this->randomRow - 1;
$col = $this->randomCol - 1;

while($row > 0 ) {
while($col > 0 ) {
$this->getBox($row, $col)->setPiece("X");
$col--;
}
$row--;
}
}

/**
* This method 9) will:
*  1) Create the diagonal array
*  2) Loop thew the array
*  3) Get the box position and place and X in the box as piece
* @return array
*/
public function relatedDiagonalBoxes() {

//$this->MarkRelatedHorizontalBoxes();

//$this->MarkRelatedVerticalBoxes();

$this->markRelatedDiagonalBoxes();
}
}

1

Решение

Ваша логика перебирает строки, затем перебирает столбцы внутри. Вы устанавливаете все части, полностью уменьшая столбцы, прежде чем переходить к следующему ряду.

Если вы хотите установить только один кусок на ряд, как вы бы хотели для уклона, вам нужно будет разбить его после размещения элемента в столбце.

while($row > 0) {
while($col > 0) {
$this->getBox($row, $col)->setPiece('X');
$col--;
break; // placing this break is the logic you are trying to achieve
// however defeats the purpose of the secondary while loop
}
$row--;
}

Что-то вроде следующего должно быть достаточно:

while($row > 0 && $col > 0) {
$this->getBox($row--, $col--)->setPiece('X');
}

Это так же, как если бы вы шли прямо по строке или столбцу, вам просто нужно уменьшить оба значения, чтобы получить наклон.

0

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector