Problem in find Max And Min Number in Large Text File

hi
i have big file,in this link

im reading the numbers from each line,and each line have two number,

i wana find max and min value, i wrote a code that worked on little text file but in this file dont work, its seems be ok,but i dont know what i missed
its my code


<?php 
$time_start = microtime(true);
echo "Labour:";
ini_set('max_execution_time', 360);
echo "<br>" ;
ini_set('memory_limit', '2048M');
$sumpage = array();;
  $file = fopen( "web-graph.txt", "r" ) or exit ( "Unable to open file!" ) ;
  $str = fgets($file);
 $tmp = explode(" ", $str);
 if ($tmp[0]>$tmp[1]) {
      $max=$tmp[0];
      $min=$tmp[1];
  } else {
      $max=$tmp[1];
      $min=$tmp[0];
  }

  while ( !feof ( $file ) )
    {    
     $tmp = explode(" ", $str);
     if ($tmp[0]>$max) {
         $max=$tmp[0];
     }if ($tmp[0]<$min){
         $min=$tmp[0];
     } 
     if ($tmp[1]>$max) {
         $max=$tmp[1];
     }if ($tmp[1]<$min){
         $min=$tmp[1];
     }
     $str = fgets($file);
  }
     echo "Max =".$max."Min:".$min; // number of lines in file
  echo "<br>";
  fclose( $file ) ;
   echo "<br>";
    $time_end = microtime(true);
    $time = $time_end - $time_start;
    echo "Time of Execute: {$time}";
 ?>

Could you be more specific?
Do you get an error, a blank page, a wrong result? What does “dont work” mean?

1 Like

If I understood correctly then this may work.

$file = fopen('web-graph.txt', 'r' ) or exit ('Unable to open file!');
list($min, $max) = fscanf($file, '%s %s');
while (!feof($file)) {
  list($a, $b) = fscanf($file, '%s %s');
  $max = max($a, $b, $max);
  $min = min($a, $b, $min);
}
fclose($file);
echo "Min $min\nMax $max";
1 Like

hi sory for late,
no…its show the biggest number is 99999 but the real biggest number is something bigger

thanks
yes…its worked for muximum ,but minimum is null…Can you explain it?

If any line in the file contains only one number, and you don’t check for that, then it will present as a null string which will evaluate as lower than ‘1’.

1 Like

I’ve updated my example if you wish to try it.

$file = fopen('web-graph.txt', 'r') or exit('Unable to open file!');
list($a, $b) = fscanf($file, '%s %s');
$min = PHP_INT_MAX;
$max = ~PHP_INT_MAX;
while (!feof($file)) {
    $max = max($a, $b, $max);
    $min = min($a, $b, $min);
    list($a, $b) = fscanf($file, '%s %s');
}
fclose($file);
echo "Min $min\nMax $max";
1 Like

thanks in advance,its worked,

yes,thats right,

now code works fine,

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.