计数特定细胞
我目前有一个二维数组,其中包含如下数据:
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 标记有数据的单元格,空白表示其为空。 在过去的一个小时里,我一直在揪着头发,试图弄清楚如何计算我所说的“洞”。 它基本上是两个有数据的单元格之间有空数据的单元格。 所以按照顺序你可以看到列从左到右分别有 2, 0, 2, 0, 0 个孔。 我的函数需要返回总孔数,因此对于这种情况 4。
目前我已经完成了非常接近的操作,但我的函数正在计算第 4 列上的前 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;
}
感谢您的帮助。
I currently have a 2 dimensional array that has data like this :
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 marks a cell that has data, blank means its empty.
I having been pulling my hair for the last hour trying to figure out how to count what I call "holes".
It's basically a cell with empty data between two cells having data.
So by order you can see the cols have respectively 2, 0, 2, 0, 0 holes from left to right.
My function needs to return the total holes, so for this case 4.
Currently I have done this really close but my function is counting the 2 first cells on the 4th col which is wrong and I can't figure out how to account for that.
Here is my actual code :
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;
}
Your help is appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我在 javascript 中有一个答案,试试这个:
'hole' 是带有孔数的 var
I have an answer in javascript, try this:
'hole' is the var with the number of holes
因此,如果我理解正确,您只想知道数组中有多少不在边缘的空单元格。
类似于计算句子中的空格数,但不计算开头或结尾的空格?
你是这个意思吗?
(您可能需要将
== null
和!= null
替换为您需要的任何其他“空”检查。此外,嵌套的 IF 显然可以压缩 - 我写道为了便于理解,它们进行了扩展。)So if I understand correctly, you just want to know how many empty cells you have in your array which isn't on an edge.
Similar to counting the number of spaces in a sentence, but not counting the whitespace at the beginning or end?
Is this what you mean?
(You may need to replace the
== null
and!= null
with whatever other 'emptyness' check you need. Also, the nested IFs can obviously be condensed - I wrote them expanded for ease of understanding.)