Answer the question
In order to leave comments, you need to log in
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
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";
}
}
}
}
}
}
}
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 questionAsk a Question
731 491 924 answers to any question