2013-08-26 63 views
1

如果沒有foreach循環,是否可以計算符合條件的數組中的整數(例如,小於n)?有沒有一種方法來計算小於給定點的數組中的整數沒有foreach循環?

$arr = range(0,100); // not always consistent 0,1,2,3...100. Could be 1,1,3,5,25,6,10,100. 
$n = 20; 
echo countLessThan($n,$arr); // can this work without a loop? 
echo countLessLoop($n,$arr); // works, with the help of a loop 

// can you make this work without a loop? 
function countLessThan($n,$arr) { 
    $count = ?; // number of items in $arr below $n 
    return $count; 
} 

// this works, but with a loop 
function countLessLoop($n,$arr) { 
    $count = 0; 
    foreach($arr as $v) { 
     if ($v < $n) $count++; 
    } 
    return $count; 
} 
+0

如果循環中沒有else語句,則無法執行此操作 –

+3

您可以對數組進行排序並查找數字的位置。 – cars10m

+0

數組是排序的嗎?或以任何方式受到限制? –

回答

7

一個通用的方法可以是使用array_filter函數創建滿足某些標準的元素數組(give N作爲函數名)

例如計數在數組元素的數目更大然後3一個可以運行

function test($x){ 
return $x>3; 
} 

$data = array(1,2,3,4,5); 
echo count(array_filter($data, 'test')); 

它打印

2 

但很明顯 - 而對標準的任何限制,並/或數組 - 任何解決方案將使用「引擎蓋下」的循環(並提供答案也循環,但只是使用語言預定義的函數)。

+1

+「底層」。 –

1

對不起不array_map(),但array_filter()這樣的:

$array = array('1', '2', '3', '4', '5', '5'); 
print_r(array_filter($array,"lessthen")); 
function lessthen($val) { 
    if ($val<4) { 
     return $val;  
    } 
    else return NULL; 
} 

會打印:

Array ([0] => 1 [1] => 2 [2] => 3) 

多看這裏:http://www.php.net/manual/en/function.array-filter.php

+0

我不關注。 http://codepad.org/VQK6Xj4B – Ryan

+0

現在它工作得很好,你可以改變<4爲<你想要的任何值' – Tiago

1

如果數組的排序被允許:

(本身排序當然並不總是便宜並在內部包括反正一些環路)

function countLessThan($n,$arr){ 
    sort($arr); 
    return array_search ($n,$arr); 
} 

否則:

function countLessThan($n,$arr){ 
    $a=array_slice($arr,0); 
    sort($a); 
    return array_search ($n,$a); 
} 

但是,然後再次:這隻適用於,如果$n其實是$arr的成員,否則你會得到一個錯誤的結果!

例如,$n不是數組的一部分,您可能需要通過在原始數組中選取一個點來嘗試樹方法,然後檢查該值是高於還是低於$n,然後遞歸地在剩餘的一半數組上重複該過程。當數組長度爲1時,遞歸結束。找到的位置基本上是您正在查找的數字。

+0

我很難做這個工作:http://codepad.org/t35b1R0h – Ryan

+0

試試這個小提琴:http://phpfiddle.org/main/code/4x9-xrp(我添加了一些更多的元素數組)。 – cars10m

相關問題