我现在有一个二维数组,它的数据是这样的:
X X X X
X X X X
X X X
X X X X
X X X X
X X X X X
X标记有数据的单元格,blank表示为空。过去的一个小时里我一直在扯头发,试图弄清楚如何计算我所谓的"洞"。它基本上是两个有数据的单元格之间有空数据的单元格。按照顺序你可以看到颜色从左到右分别有2,0,2,0,0个孔。我的函数需要返回所有的洞,所以在这个例子中是4。
目前我已经做到了这一点,但我的功能是计算第4个col上的第2个单元格,这是错误的,我不知道如何解释。
下面是我的实际代码:public function countHoles(){
$total = 0;
for($i=0; $i<5; $i++){
$counting = false;
$passed = false;
for($j=0; $j<10; $j++){
if(count($this->table[$j][$i])>0){
$passed = true;
}
if($passed && !$counting && count($this->table[$j][$i])==0){
$counting = true;
}
else{
$counting = false;
}
if($passed && $counting){
$total++;
}
}
}
return $total;
}
感谢您的帮助
我有一个javascript的答案,试试这个:
var arr = [[1,2,3,null,5],[1,2,3,null,5],[null,2,null,null,5],[null,2,3,4,null],[1,null,null,4,5],[1,2,3,4,null]];
var hole = 0;
for(var i=0; i<arr.length; i++){
for(var j=1; j<arr[i].length-1; j++){
if(arr[i][j]==null){
for(var k=j;k<arr[i].length; k++){
if(arr[i][k] != null){
k = arr[i].length;
}else{
j++;
}
}
if(j < arr[i].length){
hole++;
}
}
}
}
alert(hole);
'hole'是带有孔数的变量
如果我理解正确的话,你只是想知道数组中有多少不在边上的空单元格。
类似于计算句子中的空格数,但不计算开头和结尾的空格数?
public function countHoles()
{
$total = 0;
// Start at 1 and go to Count() - 2
for($i = 0; $i < 5; $i++) // Horizontal
for($j = 1; $j < 9; $j++) // Vertical
{
if (j == 1) // 2nd row
{
if ($this->table[$i][$j] == null && $this->table[$i][0] != null)
$total++;
}
else if (j == 3) // 2nd last row
{
if ($this->table[$i][$j] == null && $this->table[$i][4] != null)
$total++;
}
else
{
if ($this->table[$i][$j] == null)
$total++;
}
}
return $total;
}
你是这个意思吗?
(您可能需要将== null
和!= null
替换为您需要的任何其他"空"检查。此外,嵌套的if显然可以被压缩——为了便于理解,我将它们展开。