Home > OS >  PHP write a number out of an array
PHP write a number out of an array

Time:03-26

I have a PHP problem. I need to write a number from a sets of digits 0-9. Each set has 10 digits, each digit once. I need to count the number of sets that I have to use to write the number. For example number 10 is written from one set, but number 300 uses 2 sets because it has two zeros. But, the problem is that 6 and 9 are considered the same. They can be rotated by 180 degrees. Number 266 will be using one set, 369 also is using one set, but 5666 is using 2 sets. I would be very grateful if you could somehow help me. Here is how I have started and stuck up, have no more clue how to loop through it. Tried many things, nothing successful.

<?php
function countSet($num) {
 $array = str_split($num); 
 $statarr = [0,1,2,3,4,5,6,7,8,9];
 $a1 = $array; $a2 = $statarr; 
 $result = array_intersect($a1,$a2);
 $count = array_count_values($result); }
?>

CodePudding user response:

If you just need to know how many sets you need for a number, you can solve by counting the numbers. For the case of the 9, just replace every 9 by a 6 and divide the number of 6 by two. Something like this (sorry if there's any syntax error, I'm on mobile):

function countSet($input) {
    // Convert the input into a string and replace every 9 by a 6. Then convert it to array
    $numbers = str_split(str_replace("9", "6", strval($input)));

    // Count occurrences for each number
    $usedNumbers = array_count_values($numbers);
    
// If we have a 6, must divide it by 2 (6 represents 6 and 9
    if (array_key_exists("6", $usedNumbers)) {
      $usedNumbers["6"] = ceil($usedNumbers["6"] / 2);
    }
    
    // Now we just need to know the max number of occurrences for a single number as our result.
    return max($usedNumbers);
}

See an online demo here

  • Related