• Coding
  • Exercise - Self Insertion

This is a C++ version. There are a few pain points that annoyed me. I am becoming a C# programmer. Farewell C++. (Not really).
string input = "I inserted it I inserted it in myselfin myself";
int length = input.size();
int hLength = input.size()/2;
vector<string> subsequences(hLength);

int i = 0;
generate(subsequences.begin(), subsequences.end(),
	[=, &i]() { return input.substr(i++, hLength); } );

i = 0;
auto found = find_if(subsequences.begin(), subsequences.end(),
	[=, &i](string sub) -> bool {
		string rhs = input.substr(0, i).append(input.substr(i + hLength, length - (i+hLength)));
		i++;
		return sub == rhs;
});
if(found != subsequences.end()){
	cout << *found << endl;
}
10 months later
PHP. It's quite verbose, could be reduced by about half.
I'm not bringing anything new, the same algorithm in a different language, so sorry if resurrecting that thread poses a problem. There is probably a more efficient way to do it, CPU-cycles-wise.
<pre>
<?php

function findSolutions($input) {
	$solutions = array();
	$inputLen = strlen($input);
	$partLen = $inputLen / 2;
	for ($i=0; $i<=$partLen; $i++) {
		$preChunk = substr($input, 0, $i);
		$chunk = substr($input, $i, $partLen);
		$postChunk = substr($input, $i+$partLen);
		// print_r("Testing $chunk against $preChunk.$postChunk \n");
		if($chunk == $preChunk.$postChunk) {
			$solutions[$i] = $chunk;
		}
	}
	return($solutions);
}


$input = "ababcc";
$solutions = findSolutions($input);
echo "Input: $input \n";
echo "Solutions, [position] => string \n";
print_r($solutions);

?>
</pre>