Created
October 31, 2013 07:55
-
-
Save scintill/7245782 to your computer and use it in GitHub Desktop.
"Interleave" two strings in every possible way.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* "Interleave" two strings in every possible way. | |
* interleave('ABC', 'DE') = | |
* ABCDE ABDCE ABDEC ADBCE ADBEC ADEBC DABCE DABEC DAEBC DEABC | |
* | |
* Nothing real special here, just thought it was an interesting | |
* problem that gets annoying for humans but after some thought is | |
* quite simple to a programmer and a computer. | |
* | |
* PHP isn't that horrible for functional-type programming either. | |
*/ | |
function catter($a, $s) { | |
return array_map(function($v) use ($s) { return $s . $v; }, $a); | |
} | |
function interleave($p, $q) { | |
if (!strlen($p)) { | |
return array($q); | |
} | |
if (!strlen($q)) { | |
return array($p); | |
} | |
return array_merge( | |
catter(interleave(substr($p, 1), $q), substr($p, 0, 1)), | |
catter(interleave($p, substr($q, 1)), substr($q, 0, 1)) | |
); | |
} | |
$l = interleave('ABC', 'DE'); | |
echo implode("\n", $l); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment