Amir 76 Amir 76 - 1 month ago 7
PHP Question

Make an A* Function

I would like to make a function to process a text file.

This function must process the text file and then find the shortest way to achieve point A to point B

Example:

* 1 - - - * *
* * * * - - *
* * - - - * -
* * * * - * -
2 - * * - * -
* - - * - * -
* * - - - - -

Answer

It could be optimized, but i had a few minutes to kill so here is what i came up with. The basic idea is to read the file by line, then explode it space. Iterate over lines, then characters marking where each point is. Find the difference between each X and Y and generate a string based on those differences. The output is the path taken.

<?php 
//39883901.txt is the text file above
$File = fopen("39883901.txt", "r");
$Lines = array();
$PositionA = array();
$PositionB = array();
if($File) 
{
    while(($line = fgets($File)) !== false)
    {
        $Lines[] = explode(' ', $line);
    }

    fclose($File);
}
if(count($Lines) > 0)
{
    foreach($Lines as $y => $xvalues)
    {
        foreach($xvalues as $x => $value)
        {
            if($value == '1')
            {
                $PositionA['x'] = $x;
                $PositionA['y'] = $y;
            }
            if($value == '2')
            {
                $PositionB['x'] = $x;
                $PositionB['y'] = $y;
            }
        }
    }
    if(isset($PositionA['x'], $PositionA['y'], $PositionB['x'], $PositionB['y']))
    {
        $DifferenceX = $PositionB['x'] - $PositionA['x'];
        $DifferenceY = $PositionB['y'] - $PositionA['y'];
        $PadX = "R";
        $PadY = "D";
        if($DifferenceX < 0)
        {
            $PadX = "L";
            $DifferenceX = $DifferenceX * -1;
        }
        if($DifferenceY < 0)
        {
            $PadY = "U";
            $DifferenceY = $DifferenceY * -1;
        }
        $Travel = "";
        $Travel = str_repeat($PadX, $DifferenceX);
        $Travel .= str_repeat($PadY, $DifferenceY);

        echo "Travel Path: " . $Travel;
        //Travel Path: LDDDD
    }
}
?>