PHP classical algorithm face questions

A few days recently compiled some classical algorithm php title, partial basis, please correct me.

  1. A group of monkeys arranged in a circle, press 1,2, ..., n are numbered. Then one starts from the first number, the number to m only, it kicked circle, then the number of starts from the back of it, and then only to the m-number, in which the kick ..., thus performed repeatedly until the last So far only a monkey, the monkey is called king. This process requires simulation program, input m, n, the output of the last king number.

Thinking

The monkey into an ordered array, in order to meet the requirements of unset or out into an array Finally, the recursive loop.

function circle($n,$m)
{
    $list = []; 
    for($i = 1; $i <= $n; $i++)
    {
        $list[$i] = $i;
    }

    $array = kick($list, $m);

    return implode($array);
}

function kick($array,$m)
{
    if(count($array) == 1)
    {
        return $array;
    }

    foreach($array as $key => $value)
   {
       if($key%$m == 0) 
       {
           unset($array[$key]);
       }
       else
       {
           array_push($array,$array[$key]);
           unset($array[$key]);
       }
   }

    $array = kick($array, $m);

    return $array;

}

//  7
echo circle(8,3);
  1. There is a cow, can give birth to 4 years old, one year, are born of the same cow, the 15-year-old neutered, no longer students, 20-year-old death, asked how many head of cattle n years later.

Thinking

Set the total number of statistics, a single cow through each year, if less than 15 years old at the same time is a multiple of four, the total number is incremented (birth to a calf), if it reaches 20 years of age minus one (dead body), out of more than 20 years old loop (it will not change the total amount). The essence of this question is that every birth a calf, to its total number of years = total number of years - a few years before the birth, so you can calculate the total of its output and the death of how many cattle, both as static variables total cumulative calculation result.

function cow($year)
{
    static $sum = 1;

    for($i = 1; $i <= $year; $i++)
    {
        if($i > 20)
        {
            break;
        }
        if($i <15 && $i%4 == 0)
        {
            $sum++;
            cow($year - $i);
        }
        if($i == 20)
        {
            $sum --;
        }
    }

    return $sum;
}

echo cow(100);
  1. Pascal's Triangle

Here Insert Picture Description
Thinking

1 on both sides, a row corresponding to each other on a number = the number of two and

function triangle($n)
{
    $base = ['1'=>[1],'2'=>[1,1],'3'=>[1,2,1]];

    if($n <= 3)
    {
        return $base;
    }

    for($i =4; $i <= $n; $i ++)
    {
        $temp = [1];
        for($j = 0; $j < count($base[$i - 1]) - 1; $j ++)
        {
            $temp[] = $base[$i - 1][$j] + $base[$i - 1][$j+1];
        }
        $temp[] = 1;
        $base[$i] = $temp;
    }

    return $base;
}

var_dump(triangle(10));
  1. Bubble Sort

Thinking

Comparing the first number from the back of the beginning of each number and the number to put in front of the small, so that after a traverse, the maximum number will be the last one, the second pass to the penultimate place to order forth.

function maopao($data)
{
    $len = count($data);

    for($i = $len; $i > 1; $i --)
    {
        for($j = 0; $j < $i - 1; $j ++)
        {
            if($data[$j] > $data[$j + 1])
            {
                $temp = $data[$j + 1];
                $data[$j + 1] = $data[$j];
                $data[$j] = $temp;
            }
        }
    }

    return $data;
}

var_dump(maopao([5,1,8,3,6,4,9,2,7]));
  1. Quick Sort

Thinking

Taken first, through the array, the array is less than it into the left, right or greater it into an array, then the left and right respectively recursive sorted array to form a tree structure, so that when only one, above the nodes are sorted good combination that was.
This algorithm is the optimal time complexity is O (log2n), than the bubble of O (n) to be fast, slow, like most of the situation.

function quick($data)
{
    if(count($data) <= 1)
    {
        return $data;
    }

    $key = $data[0];
    $left = [];
    $right = [];

    for($i = 1; $i < count($data); $i ++)
    {
        if($data[$i] < $key)
        {
            $left[] = $data[$i];
        }
        else
        {
            $right[] = $data[$i];
        }
    }

    $left = quick($left);
    $right = quick($right);

    return array_merge($left,array($key),$right);
}

var_dump(quick([5,1,8,3,6,4,9,2,7]));
  1. Returns an array of binary search sequence index

Thinking

Each taking several intermediate contrast, a large number on the left and contrast, small and right on the comparison, I was intercepted array, in fact, use the left and right lower standard, replacing the contrast subscript save more memory, you can try.

function twoSearch($x, $data)
{
    $i = round(count($data)/2);
    $middle = $data[$i];
    if($x == $middle)
    {
        return $i;
    }
    else if($x > $middle)
    {
        twoSearch($x, array_slice($data, 0, $i));
    }
    else
    {
        twoSearch($x, array_slice($data, $i, -1));
    }

    return false;
}

var_dump(twoSearch(16,[11,12,13,14,15,16,17,18,19,20]));
  1. Character set: an input string, the string comprising a set of characters is obtained, the sort order and press the (English)

Thinking

String into the array, de-duplication, reordering.

function character($data)
{
    $array = str_split($data); 
    $array = array_unique($array); 
    sort($array); 
    return implode('', $array);
}

var_dump(character('optimization'));
  1. File traverse the next file all files and subfolders under

Thinking

Use php function to read the file and folder, traverse read.

function readFile($dir)
{
    $data = [];

    if($handle = opendir($dir))
    {
        while($file = readdir($handle) != false)
        {
            if($file != '.' && $file != '..')
            {
                if(is_dir($dir.'/'.$file))
                {
                    $data[$file] = readFile($dir.'/'.$file);
                }
                else
                {
                    $data[] = $file;
                }
            }
        }

        closedir($handle);
    }
    return $data;
}
  1. A n-level steps, you can only cross Class 1 or Class 2 cross, Q: How many ways to finish the level.

Thinking

When a person went to the n-th stage, only two possibilities, the n-1 grade level across the level, or across the two n-1 steps.

function fibonacci($n)
{
    if($n <= 2)
    {
        return $n == 1 ? 1 : 2;
    }

    $n = fibonacci($n - 1) + fibonacci($n - 2);

    return $n;
}

var_dump(fibonacci(10));
Released five original articles · won praise 0 · Views 79

Guess you like

Origin blog.csdn.net/jy615183000/article/details/105271632