[Solution] Facebook Hacker Cup 2012 – Qualification round – Alphabet soup (letters)

Was bored so decided to optimize my solution a little bit more.

You can find the original solution here.

 

$file_content = explode("\n",(fread(fopen("input.txt",'r'), filesize("input.txt")));

$output = fopen("output.txt", 'w');
$hacker = array('h','a','c','k','e','r','u','p');

for ($j = 1; $j <= intval($file_content[0]); $j++){
for ($zzz = 0; $zzz < count($hacker); $zzz++){
$freq[$hacker[$zzz]] = 0;
}
	$word = strtolower(str_replace(" ","",$file_content[$j]));
	$len = strlen($word);
		for ($i=0; $i<$len; $i++) {
		  $letter = $word[$i];
		  if (in_array($letter,$hacker)){
		     if ($letter =="c") {$freq[$letter] +=  0.5;}
		     else {$freq[$letter]++;}
		}
		}
	$stringData = "Case #" . $j . ": " . intval(min($freq)) . "\n";
	fwrite($output, $stringData);
}
fclose($output);

 

[Solution] Facebook Hacker Cup 2012 – Qualifying round – Alphabet Soup

This was by far the easiest problem out of the three.

Here’s my solution, written in PHP. It reads a file called input.txt and outputs the results to output.txt!

UPDATE – a much more optimized solution here.

$filename = "input.txt";
$input = fopen($filename, 'r');
$theData = fread($input, filesize($filename));
fclose($input);

$file_content = explode("\n",$theData);
$test_cases = intval($file_content[0]);
$outputFile = "output.txt";
$output = fopen($outputFile, 'w') or die("can't open file");

for ($j = 1; $j <= $test_cases; $j++){
	$freq = array();
	$word = strtolower(str_replace(" ","",$file_content[$j]));
	$len = strlen($word);
		for ($i=0; $i<$len; $i++) {
		  $letter = $word[$i];
		  if (array_key_exists($letter, $freq)) {
			$freq[$letter]++;
		  } else {
			$freq[$letter] = 1;
		  }
		}
      if (!isset($freq['h']) || !isset($freq['a']) || !isset($freq['c'])
       || !isset($freq['k']) || !isset($freq['e']) || !isset($freq['r'])
       || !isset($freq['u']) || !isset($freq['p'])
       || (intval($freq['c'] == 1)))
                {
		$stringData =  "Case #" . $j . ": 0\n";
		fwrite($output, $stringData);
		}
	else {
		$counting = array();
		$letters = array('h','a','c','k','e','r','u','p');
			for ($z = 0; $z < count($letters); $z++){
			$var_name = "count".$letters[$z];
				if ($var_name == "countc"){
				    $$var_name = $freq[$letters[$z]]/2;
				    $counting[] = intval($$var_name);
				}
				else {
				    $$var_name = $freq[$letters[$z]];
				    $counting[] = intval($$var_name);
				}
			}
	$stringData = "Case #" . $j . ": " . min($counting) . "\n";
	fwrite($output, $stringData);
	}
}

fclose($output);

Download link: alphabet-soup