[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

2 thoughts on “[Solution] Facebook Hacker Cup 2012 – Qualifying round – Alphabet Soup

  1. Pingback: [Solution] Facebook Hacker Cup 2012 – Qualification round – Alphabet soup (letters) | just another blog page . . .

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>