Skip to content

Instantly share code, notes, and snippets.

@xorik
Last active March 21, 2019 20:37
Show Gist options
  • Save xorik/07b350e635288e66a5fb344e66a8ad39 to your computer and use it in GitHub Desktop.
Save xorik/07b350e635288e66a5fb344e66a8ad39 to your computer and use it in GitHub Desktop.

Instal

cd somewhere
composer require brick/math
php index.php

Example

New max len: 2
New result: 11111112222223344444444444444666666666666666666677777

New max len: 3
New result: 333334444444777777

New max len: 4
New result: 1112246699999999

New max len: 5
New result: 1111122222337777

New max len: 6
New result: 3333666666666777

New max len: 7
New result: 11111444447777999

New max len: 8
New result: 1111113333333344444444444499999

New max len: 9
New result: 111166666677777

New max len: 10
New result: 111111222222333333344477

New max len: 11
New result: 44777779999999999
<?php
use Brick\Math\BigInteger;
require __DIR__.'/vendor/autoload.php';
global $digits;
$digits = [2, 3, 4, 6, 7, 8, 9];
$maxLen = 0;
while (true) {
$counts = randomCounts();
$number = buildNumber($counts);
if ($number === null) {
continue;
}
$len = calcLen($number);
// Hooray
if ($len > $maxLen) {
echo "New max len: $len\n";
echo "New result: $number\n\n";
$maxLen = $len;
continue;
}
}
/**
* Get random number of all given digits
*
* Sometimes it returns all zeros
*
* @return array. Key is digit value is number of repeats
*/
function randomCounts(): array
{
global $digits;
$counts = [];
foreach ($digits as $digit) {
$rnd = rand(0, 100);
if ($rnd < 40) {
$counts[$digit] = 0;
} elseif ($rnd < 70) {
$counts[$digit] = rand(1, 5);
} elseif ($rnd < 90) {
$counts[$digit] = rand(6, 10);
} elseif($rnd < 99) {
$counts[$digit] = rand(11, 15);
} else {
$counts[$digit] = rand(16, 25);
}
}
return $counts;
}
/**
* Builds a number from counts
*
* @param array $counts result of the previous function
*
* @return BigInteger|null null if all numbers are zeros
*/
function buildNumber(array $counts): ?BigInteger
{
// The test number from the video
// return BigInteger::of('277777788888899');
$num = '';
foreach ($counts as $digit => $count) {
$num .= str_repeat($digit, $count);
}
if ($num == '') {
return null;
}
return BigInteger::of($num);
}
/**
* Count the number of steps for the given number
*
* @param BigInteger $integer
*
* @return int
*/
function calcLen(BigInteger $integer): int
{
$str = (string)$integer;
$len = strlen($str);
if ($len == 1) {
return 0;
}
$multi = BigInteger::of(1);
for ($i = 0; $i < $len; $i++) {
$multi = $multi->multipliedBy($str[$i]);
}
return calcLen($multi) + 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment