Skip to content

Instantly share code, notes, and snippets.

@kpx-dev
Created April 14, 2012 00:35
Show Gist options
  • Save kpx-dev/2381189 to your computer and use it in GitHub Desktop.
Save kpx-dev/2381189 to your computer and use it in GitHub Desktop.
Solution to: Problem A. Speaking in Tongues
<?php
/**
* Google Code Jam 2012
*
* @author Kien Pham - kien@sendgrid.com
*/
$C = new CodeJam();
$C->run();
class CodeJam
{
private $_filename = 'in.in';
private $_data;
private $_cases;
private $_file_out_handle;
public function algorithm1($data, $case)
{
// 'a' -> 'y', 'o' -> 'e', and 'z' -> 'q'.
// q, z
$string = 'ejp mysljylc kd kxveddknmc re jsicpdrysi rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd de kr kd eoya kw aej tysr re ujdr lkgc jv y e q z';
$string = str_split($string);
$answer = 'our language is impossible to understand there are twenty six factorial possibilities so it is okay if you want to just give up a o z q';
$answer = str_split($answer);
$maps = array();
foreach ($string as $key => $val)
{
$maps[$val] = $answer[$key];
}
ksort($maps);
//print_r($maps);exit;
$string = trim($data[0]);
echo 'processing case # ' . $case . "\n";
echo 'items is: ' . $string . "\n";
echo 'result is: ';
$result = null;
$strings = str_split($string);
foreach ($strings as $string)
{
$result .= $maps[$string]; // isset($maps[$string]) ? $maps[$string]:' ';
}
//echo $result;exit;
return $result;
}
public function __construct()
{
$this->_filename = $_SERVER['argv'][1];
}
public function run()
{
// remove output file:
$this->removeFile($this->_filename . '.out');
$data = $this->readFile();
// call algorithm here:
//$data = $this->algorithm1($data);
// write to file:
//$this->writeFile($data);
// close output file:
$this->closeFile();
}
public function readFile()
{
$file_handle = fopen($this->_filename, 'r');
$case = 1;
$data = array();
do
{
if (!$this->_cases)
{
$this->_cases = fgets($file_handle);
}
else
{
$current_case = array(fgets($file_handle));
$indexes = $this->algorithm1($current_case, $case);
$this->writeFile($indexes, $case);
$case++;
}
}
while (!feof($file_handle) and $case <= $this->_cases);
$content = file_get_contents($this->_filename);
return $content;
}
public function writeFile($data, $case)
{
$out = "Case #$case: $data\n";
echo $out;
$this->_file_out_handle = fopen($this->_filename . '.out', 'a');
fwrite($this->_file_out_handle, $out);
}
public function closeFile()
{
fclose($this->_file_out_handle);
}
public function removeFile($file)
{
if (file_exists($file))
{
unlink($file);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment