SOLVING:
Steps To Go: 0 Energy Left: 0 Seconds: 0
PAGE SOURCE:
<html>
<body>
<?php
$steps = 0;
$energy = 0;
if( isset( $_POST['steps'] ) && is_numeric( $_POST['steps'] ) )
$steps = $_POST['steps'];
if( isset( $_POST['energy'] ) && is_numeric( $_POST['energy'] ) )
$energy = $_POST['energy'];
?>
<form action="" method="post">
Steps: <input type="text" name="steps" value="<?php echo $steps; ?>" /><br />
Energy: <input type="text" name="energy" value="<?php echo $energy; ?>" /><br />
<input type="submit" /><br />
</form>
<pre>
<?php
echo "SOLVING:\n";
solve( $steps, $energy );
echo "\nPAGE SOURCE:";
highlight_file( "index.php" );
function solve( $steps, $energy )
{
//define the speeds
$speed = array(
array( "steps" => 3, "energy" => 5, "seconds" => 2, "name" => "fast" ),
array( "steps" => 2, "energy" => 3, "seconds" => 1.5, "name" => "medium" ),
array( "steps" => 1, "energy" => 1, "seconds" => 1, "name" => "slow" )
);
//input validation
if( $steps > $energy )
{
echo "** Not enough energy **\n";
return;
}
//init
$seconds = 0;
//output progress
echo "Steps To Go: {$steps}\tEnergy Left: {$energy}\tSeconds: {$seconds}\n\n";
//try for all 3 speeds, fastest first
for( $x=0; $x<3; $x++ )
{
//slowest speed is base case, or if energy and steps is the same
if( $x == 2 || $energy == $steps )
{
//if taking steps in base case, do it
if( $steps > 0 )
{
$moves = $steps;
//consume steps to go and energy
$steps -= $moves;
$energy -= $moves;
$seconds += $moves;
//output progress
echo "==> Take {$moves} slow step(s)\n\n";
echo "Steps To Go: {$steps}\tEnergy Left: {$energy}\tSeconds: {$seconds}\n\n";
}
return;
}
else
{
//determine max moves by steps
$moves_max_step = floor( $steps / $speed[$x]['steps'] );
//determine max moves by energy consumption
$moves_max_eng = floor( $energy / $speed[$x]['energy'] );
//calculate max (ideal) moves that can be taken while maintaining steps >= energy
//solving algebraicly for moves in: steps - moves * steps at this speed = energy - moves * energy at this speed
$moves_ideal = floor( ( $energy - $steps ) / ( $speed[$x]['energy'] - $speed[$x]['steps'] ) );
//determine moves based on ideal and maximums
$moves = min( $moves_ideal, $moves_max_step, $moves_max_eng );
//if we are taking any moves at this speed, do it
if( $moves > 0 )
{
//consume steps to go and energy
$steps -= $moves * $speed[$x]['steps'];
$energy -= $moves * $speed[$x]['energy'];
$seconds += $moves * $speed[$x]['seconds'];
//output progress
echo "==> Take {$moves} {$speed[$x]['name']} step(s)\n\n";
echo "Steps To Go: {$steps}\tEnergy Left: {$energy}\tSeconds: {$seconds}\n\n";
}
}
}
}
?>
</pre>
</body>
</html>