O
O
object_Object2021-01-07 23:45:02
PHP
object_Object, 2021-01-07 23:45:02

How to decompose a number in PHP?

The essence of the idea:
Let's say I have ip 192.168.0.1
The sum of all numbers 28 (1 + 9 +2 +1 + 6 + 8 + 0 + 1 = 28)
How can I get all possible variations of IP addresses from number 28 (zero incl. h.)?

Thank you all in advance!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Ezhgurov, 2021-01-08
@object_Object

You can immediately get the desired IP addresses without going through all the options - if you go not from numbers, but from the sum of the digits of each number.
As a result, the script in which echo was replaced by ++$count ran for less than 14 seconds and counted 112279695 addresses.

$tbl = array_fill(0, 20, []);
for ($i = 0; $i < 256; ++$i) { $tbl[intdiv($i, 100) + intdiv($i, 10) % 10 + $i % 10][] = $i; }
for ($i = 0; $i <= 19; ++$i) {
    for ($j = 0; $j <= min(19, 28 - $i); ++$j) {
        for ($k = max(0, 28 - 19 - $i - $j); $k <= min(19, 28 - $i - $j); ++$k) {
            foreach($tbl[$i] as $v1) {
                foreach($tbl[$j] as $v2) {
                    foreach($tbl[$k] as $v3) {
                        foreach($tbl[28 - $i - $j - $k] as $v4) {
                            echo $v1, '.', $v2, '.', $v3, '.', $v4, "\n";
                        }
                    }
                }
            }
        }
    }
}

The sum of the digits of a number in the range 0..255 has a range of values ​​from 0 (0) to 19 (199).
$tbl - an array of lists of numbers in the range 0..255 that have the same sum of digits.

X
xmoonlight, 2021-01-08
@xmoonlight

192.168.0.1
This is an alphabet from 0 to 255.
Permutations are an anagram for a 4-letter word.
It is possible to hash through prime numbers :

0 -> 2
1 -> 3
2 -> 5
3 -> 7
...
255 -> ...
Then multiply the simple 4th numbers (to the right of the arrow) corresponding to one of the 4 values ​​(from 0 to 255: ABCD) in the ip address: the result for any permutation will always be the same.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question