Mon 17 Nov 2008
so, the question goes a-like-a this: write a function that, given an array of strings, will return the number of those strings that contain the letters c,h,e,v,r,o and n in that order. there may or may not be other letters around and in between. Here’s was my first attempt:
$strings = array( "i like cheetos, but everyone knows cheez-its are better", "che guevara was born in argentina", "i own a chevrolet", "hello world" ); echo(chevronMatch($strings)); function chevronMatch($strings) { $chevron="chevron"; $chevronCount=0; foreach($strings as $testString) { $hitCount=0; for($y=0;$y<strlen($testString);$y++) { if ($testString[$y]==$chevron[$hitCount]) { if ($hitCount<strlen($chevron)-1) { $hitCount++; } else { $chevronCount++; break; } } } } return $chevronCount; }
Obviously, iterative code like that would make a regex guru like bj upset. here’s my second attempt, this time with ereg
function chevronMatch($strings) { $chevronsMatched=0; foreach($strings as $string) { $chevron=array('c','h','e','v','r','o','n'); $regex="[a-z,\-\ ]*"; $regexString=$regex.implode($regex,$chevron).$regex; if (ereg($regexString,$string)) $chevronsMatched++; } return $chevronsMatched; }
The puzzle “You have two hard eggs. But the question is ‘how hard are they?’ You have a 100 story building and only the two eggs, how would you find out which is the highest floor of the building you can drop the eggs from, before they break? It could be the 1st floor but it could also be the 99th floor—you must try dropping the eggs from different floors and see what happens. Your goal is to find the answer with the least number of egg drops.”