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,
),
),
)
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);
- 3 回答
- 0 关注
- 127 浏览
添加回答
举报