compare

compare

am 08.04.2006 17:16:49 von Piet

How can I stop a function in PHP?

When comparing data I want to stop the function on a hit.



Function compare($data) {

For ($n=1; $n<=10000; $n++) {

For ($m=1; $m<=10000; $m++) {

If $data[$n]==data[$m] {

.

Exit function, or exit for.. --- but how?

}

}

}

How can I avoid comparing 10000 * 10000 times?



Thanks



Piet

Re: compare

am 09.04.2006 22:53:50 von talthen.z-serwera.o2

"Piet"
> How can I stop a function in PHP?
>
> When comparing data I want to stop the function on a hit.
> Function compare($data) {
>
> For ($n=1; $n<=10000; $n++) {
> For ($m=1; $m<=10000; $m++) {
> If $data[$n]==data[$m] {
> .
> Exit function, or exit for.. --- but how?
> }
> }
> }

1. "Function", "If" and "For" should be lowercase
2. To break a loop- "break;"
3. To exit from function: "die('message explainging the reason');". You can
use "exit()" alias or just "return 0;".
4. For string comparison you can use substr_compare- should be much faster
then comparing byte by byte in a loop
5. NTG :)

Regards,
Talthen

Re: compare

am 09.04.2006 23:20:17 von Robert Stearns

talthen.z-serwera.o2@nospam.pl wrote:
> "Piet"
>
>>How can I stop a function in PHP?
>>
>>When comparing data I want to stop the function on a hit.
>>Function compare($data) {
>>
>>For ($n=1; $n<=10000; $n++) {
>> For ($m=1; $m<=10000; $m++) {
>> If $data[$n]==data[$m] {
>> .
>> Exit function, or exit for.. --- but how?
>> }
>> }
>>}
>
>
> 1. "Function", "If" and "For" should be lowercase
> 2. To break a loop- "break;"
> 3. To exit from function: "die('message explainging the reason');". You can
> use "exit()" alias or just "return 0;".
> 4. For string comparison you can use substr_compare- should be much faster
> then comparing byte by byte in a loop
> 5. NTG :)
>
> Regards,
> Talthen
>
>
This changes from an n squared algorithm to an n log n algorithm if you
sort $data and then scan sequentially for consecutive equals. Instead of
100,000,000 operations you will have about 80,000-100,000, depending on
your data and the sorting method. Even faster would be something like:

foreach($data as $v) {
if($test[$v]) {
$err = TRUE;
break;
}
$test[$v] = TRUE;
}
unset{$test}
return $err