comparisons

Back to General Chat

Page: 1  
From User Message Body
Juice
Post #121
Member
Date: 10:01 pm, Feb 25 2006
Posts: 40


I have a dilema.

I have an array ($players) that can have anywhere from 5 - 30 rows in it. Each row has 6 columns.

The 6th column ($players[$row][5]) has a number in it. The number can be anything from 0 - 30.

Without changing the order of the rows or columns, I need to find the row that has the largest number in this 6th column.

Can you help me with the coding for that?

Have a Great Day!

Juice
Administrator
http://ww4.GameSoda.net
Manick
Post #122 - Reply to (#121) by Juice
user avatar
Admin
Date: 11:45 pm, Feb 25 2006
Posts: 223


Code
$maxRow = -1;
$maxNum = -1;
foreach ($players AS $row => $data)
{
  if ($maxRow == -1)
  {
    $maxRow = $row;
    $maxNum = $data[5];
  }

  if ($data[5] > $maxNum)
  {
    $maxRow = $row;
    $maxNum = $data[5];
  }
}

Then $maxRow contains the $row, and $maxNum contains the max num.

--Manick
PHP-IRC Developer
Juice
Post #125
Member
Date: 3:15 am, Feb 27 2006
Posts: 40


ok, this works great and I thought I had it down in case there were two that had the same number, but I had forgotten that there could be up to 30 that all have the exact same number (in that case each would have 1).

How could I get it to randomly choose one of all those.

In the current code, it takes the very first one and any after that with the same number doesn't get a chance to be chosen.

Have a Great Day!

Juice
Administrator
http://ww4.GameSoda.net
Manick
Post #126 - Reply to (#125) by Juice
user avatar
Admin
Date: 6:59 am, Feb 27 2006
Posts: 223


Code
$maxRow = -1;
$maxNum = -1;
$maxRowArray = array();
foreach ($players AS $row => $data)
{
  if ($maxRow == -1)
  {
    $maxRow = $row;
    $maxNum = $data[5];
    $maxRowArray[] = $row;
    continue;
  }

  if ($data[5] > $maxNum)
  {
    $maxRow = $row;
    $maxNum = $data[5];
    $maxRowArray = array();
  }
  else if ($data[5] == $maxNum)
  {
    $maxRowArray[] = $row;
  }
}
if (count($maxRowArray) > 1)
{
  $num = rand(0,count($maxRowArray)-1);
  $maxRow = $maxRowArray[$num];
}

$maxRow contains the row, $maxNum the data from 5th column.

--Manick
PHP-IRC Developer
   

Back to General Chat