为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用 PHP 解决此问题陈述?

如何使用 PHP 解决此问题陈述?

PHP
慕容708150 2021-10-08 13:04:25
假设给出一个正整数类型的数字,例如:312。请帮我用 PHP 编写一个程序,将给定的数字转换为具有相同位数的新数字,并且新数字的所有数字必须相等到给定数字的任何数字(例如:333、111、222,每个数字一次递减或递增 1)。但只打印生成该序列所需步骤数较少的数字序列,并打印生成该序列所需的步骤数。解释:输入:一个正整数 N(例如:312)将数字 (312) 转换为 3 的序列3 2 23 3 23 3 3这里的步骤数 = 3现在,将数字(312)转换为 1 的序列2 1 21 1 21 1 1这里的步骤数 = 3最后将数字(312)转换为2的序列2 1 22 2 2这里的步骤数 = 2所以,输出:222步数:2这是我尝试过但失败的方法<?php$num = 312;$arr_num = array_map('intval', str_split($num));//steps taken for each sequence will be stored in this array$steps = array();//printing numberfor($i = 0; $i < count($arr_num); $i++)    echo $arr_num[$i];//calculationfor($i = 0; $i < count($arr_num); $i++) {    $count = 0;    for($j = 0; $j < count($arr_num); $j++) {        if($arr_num[$i] == $arr_num[$j])            ++$j;        elseif($arr_num[$i] > $arr_num[$j]) {            while($arr_num[$j] != $arr[$i]) {                $arr_num[$j] += 1;                $count++;            }        }        else {            while($arr_num[$j] != $arr_num[$i]) {                $arr_num[$j] -= 1;                $count++;            }        }    }    //pushing the count to steps array for each sequence    array_push($steps, $count);}//I am stuck here...can't find the further solution?>
查看完整描述

3 回答

?
收到一只叮咚

TA贡献1821条经验 获得超4个赞

<?php

class SeqSolver

{

    public function solve($str_num)

    {

        if(!ctype_digit($str_num))

            throw new Exception('Invalid input.  Input string must contain digits between 0 and 9 only.');


        $digits = str_split($str_num);

        $length = count($digits);


        foreach(array_unique($digits) as $digit)

            $results[$digit] = $this->stepsToSequence($str_num, $digit);


        //var_export($results);

        $min_keys = array_keys($results, min($results));


        // Prepare result

        $result['input'] = $str_num;

        foreach($min_keys as $key)

            $result['solutions'][] = [

                'sequence' => str_repeat($key, $length),

                'steps'    => $results[$key]

            ];


        return $result;

    }


    public function stepsToSequence($str_num, $target_digit) {

        $digits = str_split($str_num);

        $steps  = 0;

        foreach($digits as $digit)

            $steps += abs($digit - $target_digit);


        return $steps;

    }

}

使用示例:


$solver = new SeqSolver;

foreach(['312', '334', '39'] as $input) {

    $result = $solver->solve($input);

    var_export($result);

    echo "\n";

}

输出:


array (

  'input' => '312',

  'solutions' => 

  array (

    0 => 

    array (

      'sequence' => '222',

      'steps' => 2,

    ),

  ),

)

array (

  'input' => '334',

  'solutions' => 

  array (

    0 => 

    array (

      'sequence' => '333',

      'steps' => 1,

    ),

  ),

)

array (

  'input' => '39',

  'solutions' => 

  array (

    0 => 

    array (

      'sequence' => '33',

      'steps' => 6,

    ),

    1 => 

    array (

      'sequence' => '99',

      'steps' => 6,

    ),

  ),

)


查看完整回答
反对 回复 2021-10-08
?
慕标琳琳

TA贡献1830条经验 获得超9个赞

这有效(根据我非常快速的测试)):


 $intIn = 312;


# function changeDigits( $intIn ) { // uncomment for function

  $digits = str_split( $intIn ); // convert to array of digits

  $numerOfDigits = count($digits);

  $numberOfSteps = array();


 # check each digit in number

 for ($i=0; $i < $numerOfDigits; $i++) {

    $numberOfSteps[$i] = 0;

    $currentDigit = $digits[$i];


    # count the number of inc/decrements to change the other digits to this digit

    foreach($digits as $otherDigit) {

     if ($currentDigit > $otherDigit) $numberOfSteps[$i] += $currentDigit - $otherDigit;

     if ($currentDigit < $otherDigit) $numberOfSteps[$i] += $otherDigit - $currentDigit;

    }

  }

  $digitKey = array_search( min($numberOfSteps), $numberOfSteps );

  echo 'Number of Steps: ' . $numberOfSteps[$digitKey] . PHP_EOL;  // (or '<br>')

  echo 'New number = ' . str_repeat( $digits[$digitKey], $numerOfDigits );

 #}


# changeDigits(312);


查看完整回答
反对 回复 2021-10-08
  • 3 回答
  • 0 关注
  • 127 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信