How can I iteratively create a variant of "Murrays" that has an apostrophe after each letter? The end-result should be:
"m'rrays,mu'rrays,mur'rays,murr'ays,murra'ys,murray's"
How can I iteratively create a variant of "Murrays" that has an apostrophe after each letter? The end-result should be:
"m'rrays,mu'rrays,mur'rays,murr'ays,murra'ys,murray's"
You want to iterate through the name, and re-print it with apostrophe's? Try the following:
<?php
$string = "murrays";
$array = str_split($string);
$length = count($array);
$output = "";
for ($i = 0; $i < $length; $i++) {
for($j = 0; $j < $length; $j++) {
$output .= $array[$j];
if ($j == $i)
$output.= "'";
}
if ($i < ($length - 1))
$output .= ",";
}
print $output;
?>
My suggestion:
<?php
function generate($str, $add, $separator = ',')
{
$split = str_split($str);
$total = count($split) - 1;
$new = '';
for ($i = 0; $i < $total; $i++)
{
$aux = $split;
$aux[$i+1] = "'" . $aux[$i+1];
$new .= implode('', $aux).$separator;
}
return $new;
}
echo generate('murrays', "'");
?>
Here’s another solution:
$str = 'murrays';
$variants = array();
$head = '';
$tail = $str;
for ($i=1, $n=strlen($str); $i<$n; $i++) {
$head .= $tail[0];
$tail = substr($tail, 1);
$variants[] = $head . "'" . $tail;
}
var_dump(implode(',', $variants));
well that's why functionnal programming is here
this code works on OCAML and F#, you can easily make it running on C#
let generate str =
let rec gen_aux s index =
match index with
| String.length s -> [s]
| _ -> let part1 = String.substr s 0 index in
let part2 = String.substr s index (String.length s) in
(part1 ^ "'" ^ part2)::gen_aux s (index + 1)
in gen_aux str 1;;
generate "murrays";;
this code returns the original word as the end of the list, you can workaround that :)
Here you go:
$array = array_fill(0, strlen($string) - 1, $string);
implode(',', array_map(create_function('$string, $pos', 'return substr_replace($string, "\'", $pos + 1, 0);'), $array, array_keys($array)));