Jump to content

Help with do while statement.


fewkesy

Recommended Posts

Trying to code a first fit algorithm (explanation here). It doesn't output everything correctly at the end. There probably is an easier way to achieve this, but I need to do it using do and while statements.

 

From the output I only get the first array, none of the others display.

 

function first_fit(&$arr, &$max)
{
$bin = array(array(), array(), array(), array(), array(), array(), array(), array(), array() ,array() );
$i=0;
$j=0;	
do
{
do
{
	if (array_sum($bin[$j])+$arr[$i] <= $max) {$bin[$j][] = $arr[$i]; $k=1;	}
	$j++;
}
while($k = 0);
$i++;
$j=0;
}
while($i<=9);
outputarray($bin[0]);
outputarray($bin[1]);
outputarray($bin[2]);
outputarray($bin[3]);
outputarray($bin[4]);
outputarray($bin[5]);
outputarray($bin[6]);
outputarray($bin[7]);
outputarray($bin[8]);
outputarray($bin[9]);
}

 

 

The function outputarray() just prints the array in a nicely formatted way.

 

Any help would be much appreciated.

Link to comment
Share on other sites

Thanks for the response.

 

I'd forgot to reset $k, so I put it after the $j reset, however it still did not solve the problem.

 

I am aware of the ampersands and they have been put there on purpose due to other parts of the script.

 

Any more ideas?

 

If it helps $arr is an array of 10 numeric values, and $max is a single numeric value.

Link to comment
Share on other sites

I would add some debugging statements.  Each time you add to a bin, print out "Adding block of size {$arr[$i]} to bin $j\n".  And also print out each time you consider a bin and a block.  Printing out the values of $i, $j and $k at each step woudl be good too.

Link to comment
Share on other sites

I was also a bit confused as to why this wasn't working so I looked into it further.. it turns out the problem is in this line:

 

while ($k = 0);

 

I'll leave it to you to work out what is wrong with it and why it makes the script act that way :)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.