- Accuracy - How accurate are the results
- Error Handling - Proper error handling
- Readability - Proper Comments, Indentation, Code not rambled into just two functions, How easy it is to follow your code
- Efficiency - Results of benchmark
A Few Comments
There are a few things I noticed. One was no one checked whether the parameter passed was a string or not. You also shouldn't output "Invalid Character" in the results or kill the entire script when an invalid character is met. Throwing exceptions are better since they can be handled and debugged appropriately.
Atli
- Accuracy - 5
- Error Handling - 4
- Readability - 4
- Efficiency - 3
CTphpnwb
- Accuracy - 5
- Error Handling - 3
- Readability - 3.5
- Efficiency - 5
Duckington
- Accuracy - 5
- Error Handling - 3
- Readability - 3.5
- Efficiency - 3
gm04030276
- Accuracy - 5
- Error Handling - 3
- Readability - 3.5
- Efficiency - 5
hiddenghost
- Accuracy - 2.5
- Error Handling - 2.5
- Readability - 2.5
- Efficiency - 3
JackOfAllTrades
- Accuracy - 3.5
- Error Handling - 3
- Readability - 4
- Efficiency - 4.5
McSick
- Accuracy - 5
- Error Handling - 2
- Readability - 3
- Efficiency - 4.5
sBorg
- Accuracy - 5
- Error Handling - 2
- Readability - 4
- Efficiency - 4.5
snoj
- Accuracy - 5
- Error Handling - 2
- Readability - 3.5
- Efficiency - 3.5
xxxjj18
- Accuracy - 4
- Error Handling - 3.5
- Readability - 3.5
- Efficiency - 2.5
- sBorg
Spoiler<?php interface iMorseCodeTranslator { /** * @param (string) $text - Plain text that will be converted to morse code * * @return (string) - Morse code string */ public function toMorseCode($text); /** * @param (string) $morse_code - Morse code that will be converted to plain text * * @return (string) - Plain text string */ public function toPlainText($morse_code); } /** * MorseCodeTranslator Class - Converts Morse Code to plain text and vice versa * * @author sBorg */ class MorseCodeTranslator implements iMorseCodeTranslator { private $assocArray = array("A" => ".-", "B" => "-...", "C" => "-.-/>.", "D" => "-..", "E" => ".", "F" => "..-.", "G" => "--.", "H" => "....", "I" => "..", "J" => ".---", "K" => "-.-/>", "L" => ".-..", "M" => "--", "N" => "-.", "O" => "---", "P" => ".--.", "Q" => "--.-/>", "R" => ".-.", "S" => "...", "T" => "-", "U" => "..-", "V" => "...-", "W" => ".--", "X" => "-..-", "Y" => "-.-/>-", "Z" => "--..", "0" => "-----", "1" => ".----", "2" => "..---", "3" => "...--", "4" => "....-", "5" => ".....", "6" => "-....", "7" => "--...", "8" => "---..", "9" => "----.", "." => ".-.-/>.-", "," => "--..--", "?" => "..--..", "'" => ".----."); /** * @param (string) $text - Plain text that will be converted to morse code * * @return (string) - Morse code string */ public function toMorseCode($text) { $temp = ''; //Split the string into characters using str_split $inputArray = str_split(strtoupper($text)); foreach ($inputArray as $index => $character) { //If character exists as key in the reverseArray, then get value if (array_key_exists($character, $this->assocArray)) { //To make sure we do not check index as -1 in the first run if ($index > 0) $temp .= $inputArray[$index - 1] == ' ' ? '' : ' '; $temp .= $this->assocArray[$character]; }elseif ($character == ' ') $temp .= ' '; else { $temp .= "[Invalid character: $character encountered at: " . $index . " position]"; } } return $temp; } /** * @param (string) $morse_code - Morse code that will be converted to plain text * * @return (string) - Plain text string */ public function toPlainText($morse_code) { $temp = ''; //Convert string to uppercase and explode with delimiter as space $inputArray = explode(' ', (strtoupper($morse_code))); //Convert keys to values and vice versa using array_flip $reverseArray = array_flip($this->assocArray); foreach ($inputArray as $index => $character) { //If character exists as key in the reverseArray, then get value if (array_key_exists($character, $reverseArray)) { $temp .= $reverseArray[$character]; } elseif ($character == '') $temp .= ' '; else { $temp .= "[Invalid character: $character encountered at: " . $index . " position]"; } } //Replace two spaces with one, as one space is word separator return str_replace(' ', ' ', $temp); } } ?> - CTphpnwb
Spoiler
<?php interface iMorseCodeTranslator { /** * @param (string) $text - Plain text that will be converted to morse code * * @return (string) - Morse code string */ public function toMorseCode($text); /** * @param (string) $morse_code - Morse code that will be converted to plain text * * @return (string) - Plain text string */ public function toPlainText($morse_code); } class MorseCodeTranslator implements iMorseCodeTranslator { private $char_morse = array('A' => '.-', 'B' => '-...', 'C' => '-.-/>.', 'D' => '-..', 'E' => '.', 'F' => '..-.', 'G' => '--.', 'H' => '....', 'I' => '..', 'J' => '.---', 'K' => '-.-/>', 'L' => '.-..', 'M' => '--', 'N' => '-.', 'O' => '---', 'P' => '.--.', 'Q' => '--.-/>', 'R' => '.-.', 'S' => '...', 'T' => '-', 'U' => '..-', 'V' => '...-', 'W' => '.--', 'X' => '-..-', 'Y' => '-.-/>-', 'Z' => '--..', '0' => '-----', '1' => '.----', '2' => '..---', '3' => '...--', '4' => '....-', '5' => '.....', '6' => '-....', '7' => '--...', '8' => '---..', '9' => '----.', '.' => '.-.-/>.-', ',' => '--..--', '?' => '..--..', "'" => '.----.'); private $morse_char; function __construct() { $this->morse_char = array_flip($this->char_morse); // } public function toMorseCode($text) { $sp = " "; // Using non-breaking spaces to avoid browser not showing double spaces. $len = strlen($text); $text = strtoupper($text); // Morse code requires upper case text. $string = ""; // Initialize string of Morse code characters. for($i = 0; $i < $len; $i++) { if(array_key_exists($text[$i],$this->char_morse)) { // If character $i of input text is in array keys, it can be translated. $string .= $this->char_morse[$text[$i]].$sp; // Translate, adding a space between characters. } elseif($text[$i] == " ") { $string .= $sp; // End of word requires two spaces in our Morse code. } } return $string; // Return string of Morse code characters. } public function toPlainText($morse_code) { $string = ""; // Initialize plain text string $len = strlen($morse_code); while($len > 0) { if(!($space = strpos($morse_code," "))) { // If there are no spaces, then we're dealing with one character $space = strlen($morse_code); // so we use all dots/dashes in the given string of dots/dashes } $test = substr($morse_code, 0, $space); // Grab start of dots/dashes up to the first space. if(array_key_exists($test,$this->morse_char)) { // If test is in the array keys of morse_char array, it can be translated. $string .= $this->morse_char[$test]; // Translate test. } $morse_code = substr($morse_code, $space+1,$len - $space+1); // Remove dots/dashes already delt with. while(substr($morse_code,0,1) == " ") { // check for word spacing. $string.= " "; $morse_code = substr($morse_code, 1); } $len = strlen($morse_code); } return $string; // Return string of plain text. } } ?>
- snoj
Spoiler
<?php if(!interface_exists('iMorseCodeTranslator')) { interface iMorseCodeTranslator { /** * @param (string) $text - Plain text that will be converted to morse code * * @return (string) - Morse code string */ public function toMorseCode($text); /** * @param (string) $morse_code - Morse code that will be converted to plain text * * @return (string) - Plain text string */ public function toPlainText($morse_code); } } /** * A simple class to convert between Morse Code and ASCII English. * * Be aware that the Morse Code used does not follow the actual specs. * Characters in words are sepearted by 1 space, words are seperated by 2 spaces. * Unrecognized characters and codes are thrown away. */ class MorseCodeTranslator implements iMorseCodeTranslator { private $charmap_e2m; private $charmap_m2e; public function __construct() { $this->charmap_e2m = array('A' => '.-','B' => '-...','C' => '-.-/>.','D' => '-..','E' => '.','F' => '..-.','G' => '--.','H' => '....','I' => '..','J' => '.---','K' => '-.-/>','L' => '.-..','M' => '--','N' => '-.','O' => '---','P' => '.--.','Q' => '--.-/>','R' => '.-.','S' => '...','T' => '-','U' => '..-','V' => '...-','W' => '.--','X' => '-..-','Y' => '-.-/>-','Z' => '--..','0' => '-----','1' => '.----','2' => '..---','3' => '...--','4' => '....-','5' => '.....','6' => '-....','7' => '--...','8' => '---..','9' => '----.','.' => '.-.-/>.-',',' => '--..--','?' => '..--..','\'' => '.----.'); $this->charmap_m2e = array_flip($this->charmap_e2m); } /** * Convert a plain text ASCII string to Morse Code. * * Be aware that the Morse Code used does not follow the actual specs. * Characters in words are sepearted by 1 space, words are seperated by 2 spaces. * Unrecognized characters and codes are thrown away. * * @param (string) $text - Plain text that will be converted to morse code * * @return (string) - Morse code string */ public function toMorseCode($text) { $result = array(); $text = strtoupper($text); //Convert the give string to upper case since Morse doesn't recognize letter casing. $strlength = strlen($text); //get the length of the string provided. //We could do this in the for loop, but I feel that since it would be evaluated every time and we aren't changing this value, //we can precalculate the length and save on operations. for($i=0;$i<$strlength;$i++) { //Another word coming? Add two spaces. if($text[$i] == ' ') { $result[] = ' '; continue; } //Character in the map? Add it to the result array along with the required space padding. if(isset($this->charmap_e2m[$text[$i]])) { $result[] = $this->charmap_e2m[$text[$i]]; $result[] = ' '; continue; } } //Join things into a nice string and trim the character delimiter. return rtrim(implode('', $result), ' '); } /** * Convert a Morse Code string to ASCII text. * * Be aware that the Morse Code used does not follow the actual specs. * Characters in words are sepearted by 1 space, words are seperated by 2 spaces. * Unrecognized characters and codes are thrown away. * * @param (string) $morse_code - Morse code that will be converted to plain text * * @return (string) - Plain text string */ public function toPlainText($morse_code) { $result = array(); $strlength = strlen($morse_code); //So we're not re-evaluating with each loop for($i=0;$i<$strlength;$i++) { //Is this a word space? if(substr($morse_code,$i,2) == ' ') { $result[] = ' '; $i++; continue; } //Is this a character seperator? if($morse_code[$i] == ' ') { continue; } //Okay, this should be a letter now. //Get the substring from $i to the next whitespace. $mchar = @substr($morse_code, $i, strpos($morse_code, ' ', $i) - $i); //False? Usually at the end of the string. if($mchar === false) { $mchar = substr($morse_code, $i); } //If the morse code maps to a ASCII character, add if it to the results array and continue. if(isset($this->charmap_m2e[$mchar])) { $result[] = $this->charmap_m2e[$mchar]; } //Advance to the end of the word. $i+=strlen($mchar)-1; } //Join everything into a nice simple string. return implode('', $result); } } //Running tests /*if(in_array($argv[1],array('--run-test', '-rt'))) { $m = new MorseCodeTranslator(); $top = $m->toPlainText('.... . .-.. .-.. --- .-- --- .-. .-.. -..'); var_dump($top); $tom = $m->toMorseCode('hello world'); var_dump($tom); }*/ ?>
- gm04030276
Spoiler<?php interface iMorseCodeTranslator { /** * @param (string) $text - Plain text that will be converted to morse code * * @return (string) - Morse code string */ public function toMorseCode($text); /** * @param (string) $morse_code - Morse code that will be converted to plain text * * @return (string) - Plain text string */ public function toPlainText($morse_code); } class MorseCodeTranslator implements iMorseCodeTranslator { // map the characters to the morse code private $morse_chars = array( "A" => ".-", "B" => "-...", "C" => "-.-/>.", "D" => "-..", "E" => ".", "F" => "..-.", "G" => "--.", "H" => "....", "I" => "..", "J" => ".---", "K" => "-.-/>", "L" => ".-..", "M" => "--", "N" => "-.", "O" => "---", "P" => ".--.", "Q" => "--.-/>", "R" => ".-.", "S" => "...", "T" => "-", "U" => "..-", "V" => "...-", "W" => ".--", "X" => "-..-", "Y" => "-.-/>-", "Z" => "--..", "0" => "-----", "1" => ".----", "2" => "..---", "3" => "...--", "4" => "....-", "5" => ".....", "6" => "-....", "7" => "--...", "8" => "---..", "9" => "----.", "." => ".-.-/>.-", "," => "--..--", "?" => "..--..", "'" => ".----.", ); // set the character delimiter private $char_delimiter = " "; // set the word delimiter private $word_delimiter = " "; public function toMorseCode($text){ // start with a blank string $morse_code = ""; // we only have upper case characters in our morse code array so we need our input to match $text = strtoupper($text); // loop over the input string as an array $length = strlen($text); for($i = 0; $i < $length; $i++){ // if there is a space in the input if($text[$i] == " "){ // then turn that into our delimiter $morse_code .= $this->word_delimiter; }else{ // else lookup the character in our morse array and add it to the output string if(isset($this->morse_chars[$text[$i]])){ $morse_code .= $this->morse_chars[$text[$i]]; } if(($i+1 < $length) && ($text[$i+1] != " ")){ $morse_code .= $this->char_delimiter; }// add a space between characters } } // finally return the string in morse code return $morse_code; } public function toPlainText($text){ // start with a blank string $plain_text = ""; // we need to flip the character map array so we can look up the characters in the same way we did in the toMorseCode function $morse_chars = array_flip($this->morse_chars); // split the morse code based on our word delimiter $words = explode($this->word_delimiter, $text); // then loop over each word foreach($words as $word){ // for each word, split the morse code based on our character delimiter $characters = explode($this->char_delimiter, $word); // then loop over each character foreach($characters as $c){ if(!empty($c)){ $plain_text .= $morse_chars[$c]; } } unset($characters); // add a space between words $plain_text .= " "; } // finally return the string in English return $plain_text; } } - hiddenghost
Spoiler
<?php ini_set('display_errors', false); //ini_set('log_errors', 1); //ini_set('error_log', dirname(__FILE__) . '/error_log.txt'); error_reporting(E_ALL); //http://www.dreamincode.net/forums/topic/272153-php-challenge-morse-code-translator/ interface iMorseCodeTranslator { /** * @param (string) $text - Plain text that will be converted to morse code * * @return (string) - Morse code string */ public function toMorseCode($text); /** * @param (string) $morse_code - Morse code that will be converted to plain text * * @return (string) - Plain text string */ public function toPlainText($morse_code); } class MorseCodeTranslator implements iMorseCodeTranslator { // The alias for characters is the words glyphs or glyph. function __construct() { // The string for the origin of the glyphs. $glyphs = "A => .- B => -... C => -.-/>. D => -.. E => . F => ..-. G => --. H => .... I => .. J => .--- K => -.-/> L => .-.. M => -- N => -. O => --- P => .--. Q => --.-/> R => .-. S => ... T => - U => ..- V => ...- W => .-- X => -..- Y => -.-/>- Z => --.. 0 => ----- 1 => .---- 2 => ..--- 3 => ...-- 4 => ....- 5 => ..... 6 => -.... 7 => --... 8 => ---.. 9 => ----. . => .-.-/>.- , => --..-- ? => ..--.. ' => .----."; // Due to lazyness of the coder glyphs are extracted and assigned from a string instead of just assigned. // If we feel like using the array directly we can write it out by hand and not use the // $creatGlyphsFromString function. $createGlyphsFromString = function() use($glyphs){ // PHP 5.3 required here. $glyph = explode("\n", $glyphs); // Initial seperation of rows of glyphs. $count_glyph = count($glyph); $text_glyph = array(); $morse_glyph = array(); $up = 0; while($up < $count_glyph){ // Here we assign glyphs to the glyph array depending on the glyph type.(text or morse) $new_glyph = explode(" => ", $glyph[$up]); $glyph['text'][] = $new_glyph[0]; $glyph['morse'][] = $new_glyph[1]; $up++; } return $glyph; // This function seems excessive, but I really did find it easier than writing out the whole array. :)/> }; $this->glyph = $createGlyphsFromString(); // The glyph collection is assigned to $this->glyph //echo "<pre>"; print_r($this->glyph); echo "</pre>"; } public function toMorseCode($text){ $text = trim($text); $stopGlyphs = count($this->glyph); $upGlyphs = 0; // The next while loop creates the translation array named $morseToText. // The charachters become a key and the morse glyphs become values respectively. reset($this->glyph['text']); reset($this->glyph['morse']); while($upGlyphs < $stopGlyphs){ // foreach probably would have worked too, but every operation is shown here // in its unabashed nakedness. $key = current($this->glyph['text']); $value = current($this->glyph['morse']); $textToMorse[$key] = $value; next($this->glyph['text']); next($this->glyph['morse']); $upGlyphs++; } $textToMorse['0'] = "-----"; //echo "<pre>"; print_r($textToMorse); echo "</pre>"; // Translation of text to morse code starts here. // This is easier because we can just use the character array. return call_user_func(function() use($text, $textToMorse){ $text = explode(" ", $text); // Break up the words. $word_count = count($text); $word_up = 0; // We need an array to compile the sentence. $sentence = array(); while($word_up < $word_count){ // We need an array to compile the words. $words = array(); // Words is reset each loop. $text_words = $text[$word_up]; $character_count = strlen($text[$word_up]); // Count the chacters in each word. $character_up = 0; while($character_up < $character_count){ // We can now assign the glyphs to the array called $words. // The correct text glyph is chosen based on its text key by using // the $textToMorse array and changing the key with $text_words[$character_up]. // This makes a simple selection from the $textToMorse array. $words[] = $textToMorse[$text_words[$character_up]]; $character_up++; } // We make a sentence array out of words here. $sentence[$word_up] = implode(" ", $words); $word_up++; } // For display purposes is used to create a double space. return implode(" ", $sentence); }); } public function toPlainText($morse_code){ $morse_code = trim($morse_code); $stopGlyphs = count($this->glyph); $upGlyphs = 0; // The next while loop creates the translation array named $morseToText. // The morse glyphs become a key and the text glyphs become values respectively. reset($this->glyph['text']); reset($this->glyph['morse']); while($upGlyphs < $stopGlyphs){ // foreach probably would have worked too, but every operation is shown here // in its unabashed nakedness. $value = current($this->glyph['text']); $key = current($this->glyph['morse']); $morseToText[$key] = $value; next($this->glyph['text']); next($this->glyph['morse']); $upGlyphs++; } $morseToText['-----'] = '0'; //echo "<pre>"; print_r($morseToText); echo "</pre>"; // Translation of morse code to regular text starts here. return call_user_func(function() use($morse_code, $morseToText){ $morse_code = explode(" ", $morse_code); // Break up the words. $word_count = count($morse_code); $word_up = 0; // We need an array to compile the sentence. $sentence = array(); while($word_up < $word_count){ // We need an array to compile the words. $words = array(); // Words is reset each loop. $morse_words = explode(" ", $morse_code[$word_up]); // Break up words into glyphs(characters). $character_count = count($morse_words); $character_up = 0; while($character_up < $character_count){ // We can now assign the glyphs to the array called $words. // The correct text glyph is chosen based on its morse key by using // the $morseToText array and changing the key with $morse_words[$character_up]. // This makes a simple selection from the $morseToText array. $words[] = $morseToText[$morse_words[$character_up]]; $character_up++; } // We make a sentence array out of words here. $sentence[$word_up] = implode("", $words); $word_up++; } //print_r($morse_words); //print_r($sentence); // Turn the $sentence into a string to be returned after translation. return implode(" ", $sentence); }); } function __destruct() { unset($this->glyph); unset($createGlyphsFromString); } } ?>
- Duckington
Spoiler
<?php interface iMorseCodeTranslator { /** * @param (string) $text - Plain text that will be converted to morse code * * @return (string) - Morse code string */ public function toMorseCode($text); /** * @param (string) $morse_code - Morse code that will be converted to plain text * * @return (string) - Plain text string */ public function toPlainText($morse_code); } /** * Class to convert a plain text string into morse code and the reverse (morse code into plain text) */ class MorseCodeTranslator implements iMorseCodeTranslator { private $charMap; /** * Constructor method - Defines map of morse code elements to characters */ function MorseCodeTranslator(){ $this->charMap = array( 'A' => '.-', 'B' => '-...', 'C' => '-.-/>.', 'D' => '-..', 'E' => '.', 'F' => '..-.', 'G' => '--.', 'H' => '....', 'I' => '..', 'J' => '.---', 'K' => '-.-/>', 'L' => '.-..', 'M' => '--', 'N' => '-.', 'O' => '---', 'P' => '.--.', 'Q' => '--.-/>', 'R' => '.-.', 'S' => '...', 'T' => '-', 'U' => '..-', 'V' => '...-', 'W' => '.--', 'X' => '-..-', 'Y' => '-.-/>-', 'Z' => '--..', '.' => '.-.-/>.-', ',' => '--..--', '?' => '..--..', '!' => '..--.', "'" => '.----.', ' ' => ' ' ); } /** * Convert a plain text string into a series of morse code elements * @param string $text The plain text * @return string */ function toMorseCode($text){ // Convert string to <char> array $explode = str_split($text); // Return string to be used for output $string = ""; // For each character in the array, either find it's mapping, or convert it from an int foreach($explode as $character) { // If the character is a digit, convert it, otherwise get it's mapping $string .= (ctype_digit($character)) ? $this->convertTinyIntToMorse($character) : $this->charMap[strtoupper($character)] ; $string .= " "; # Space after each character } return $string; } /** * Convert a series of morse code elements into plain text * @param string $morse_code The morse code * @return string */ function toPlainText($morse_code) { // Convert string to array - split by spaces of 2 character length - actual space $explode = explode(" ", $morse_code); // Return string to be used for output $string = ""; // For each word (in morse), convert it back to plain text foreach($explode as $word) { // Convert the word to an array of characters $chars = explode(" ", $word); // For each character - Not an actual "character" as such, but an element of morse code which is converted into a single character // E.g. "..." is not 1 character, but is converted into one: "s" foreach($chars as $char) { // If there is no mapping for this character, we are assuming it is an int, so converting it, otherwise get mapping $string .= (!$c = $this->getCharMapKey( strtoupper($char) )) ? $this->convertMorseToTinyInt($char) : $c ; } // Add a space after each word $string .= " "; } return $string; } /** * Get the array key of a particular value in our mapping * @param string $val The array element's value. E.g. "..." would return a key of "S" * @return mixed */ function getCharMapKey($val) { foreach($this->charMap as $key => $char) { if($val == $char){ return $key; } } return false; } /** * Convert a morse code element into a digit * @param string $morse * @return int */ function convertMorseToTinyInt($morse) { // Loop through 0-9 until we find a match, return false otherwise for($i = 0; $i <=9; $i++) { if( $morse == ( $this->convertTinyIntToMorse($i) ) ){ return $i; } } return false; } /** * Convert a digit into a morse code element. * Iterates through numbers 0-9 adding an "." to the beginning until it reaches 5 "."s, * then begins again with "-"s * E.g: 0: ----- 1: .---- 2: ..--- 3: ...-- 4: ....- 5: ..... 6: -.... etc... * @param int $int * @return string */ function convertTinyIntToMorse($int){ // Starting point is the morse code for 0 $string = "-----"; for($i = 1; $i <= $int; $i++){ // If the last element is "-", we are adding "." - removing last element and popping one on the front // Otherwise, we're adding an "-" if($string[4] == "-"){ $this->replace($string, "."); } else { $this->replace($string, "-"); } } return $string; } /** * Replace a single character from a morse code element (. or -) * @param string &$str Reference to string * @param string $a Replacement * @return string */ function replace(&$str, $a){ // Remove last character $str = substr_replace($str, "", -1); // Pop the replacement on the front $str = $a . $str; return $str; } } ?>
- McSick
Spoiler
<?php interface iMorseCodeTranslator { /** * @param (string) $text - Plain text that will be converted to morse code * * @return (string) - Morse code string */ public function toMorseCode($text); /** * @param (string) $morse_code - Morse code that will be converted to plain text * * @return (string) - Plain text string */ public function toPlainText($morse_code); } class MorseCodeTranslator implements iMorseCodeTranslator { private $dictionary = array( 'A' => '.-', 'B' => '-...', 'C' => '-.-/>.', 'D' => '-..', 'E' => '.', 'F' => '..-.', 'G' => '--.', 'H' => '....', 'I' => '..', 'J' => '.---', 'K' => '-.-/>', 'L' => '.-..', 'M' => '--', 'N' => '-.', 'O' => '---', 'P' => '.--.', 'Q' => '--.-/>', 'R' => '.-.', 'S' => '...', 'T' => '-', 'U' => '..-', 'V' => '...-', 'W' => '.--', 'X' => '-..-', 'Y' => '-.-/>-', 'Z' => '--..', '0' => '-----', '1' => '.----', '2' => '..---', '3' => '...--', '4' => '....-', '5' => '.....', '6' => '-....', '7' => '--...', '8' => '---..', '9' => '----.', '.' => '.-.-/>.-', ',' => '--..--', '?' => '..--..', '\'' => '.----.', ' ' => ' '); public function toMorseCode($text) { $morse_code = '';//Output Morse code $len = strlen($text); //lenght of input string $text = strtoupper($text);//force everything to uppercase for valid keys for($i=0;$i<$len;$i++) { $letter = $text[$i]; //grab next letter /*if letter exsists in dictionary, grab corresponding morse value and add it to final output*/ if(array_key_exists($letter,$this->dictionary)) { $translation = $this->dictionary[$letter]; $morse_code = $morse_code . $translation . ' '; } else { //Key does not exsist, give error die('No valid translation for "'.$letter.'"!'); } } return $morse_code; } public function toPlainText($morse_code) { $text ='';//final oupput $len = strlen($morse_code); //lenght of input morse string $morse = '';//holds morse values for($i=0;$i<$len;$i++) { $char = $morse_code[$i];//get morse char from morse string if($char != ' ') { $morse = $morse . $char;//if its not a space, add it to morse character } elseif(empty($morse)) { $morse = ' ';//translate to space since 2 spaces in a row $key = array_search($morse,$this->dictionary);//search for key $morse = ''; $text = $text . $key; } else { $key = array_search($morse,$this->dictionary); //search for key from morse value if($key === False) { //key does not exsist! die('Invalid Input, No key to value "'.$morse.'"!'); } $morse = '';//reset morse character $text = $text . $key;//add character to plain text } } return $text; } } ?>
- JackOfAllTrades
Spoiler
<?php interface iMorseCodeTranslator { /** * @param (string) $text - Plain text that will be converted to morse code * * @return (string) - Morse code string */ public function toMorseCode($text); /** * @param (string) $morse_code - Morse code that will be converted to plain text * * @return (string) - Plain text string */ public function toPlainText($morse_code); } class MorseCodeTranslator implements iMorseCodeTranslator { private $translation; private $trArray = array( 'A' => '.-', 'B' =>' -...', 'C' => '-.-/>.', 'D' => '-..', 'E' => '.', 'F' => '..-.', 'G' => '--.', 'H' => '....', 'I' => '..', 'J' => '.---', 'K' => '-.-/>', 'L' => '.-..', 'M' => '--', 'N' => '-.', 'O' => '---', 'P' => '.--.', 'Q' => '--.-/>', 'R' => '.-.', 'S' => '...', 'T' => '-', 'U' => '..-', 'V' => '...-', 'W' => '.--', 'X' => '-..-', 'Y' => '-.-/>-', 'Z' => '--..', '0' => '-----', '1' => '.----', '2' => '..---', '3' => '...--', '4' => '....-', '5' => '.....', '6' => '-....', '7' => '--...', '8' => '---..', '9' => '----.', '.' => '.-.-/>.-', ',' => '--..--', '?' => '..--..', '\'' => '.----.' ); public function toMorseCode($text) { // 1. Convert the input text to uppercase // 2. Split it into an array // 3. Reassemble into a string with spaces between the letters // 4. Use the string translate function to perform the translation // using the translation array // 5. Remove a space from the triple spaces between words // (this Regex could be better, I think) // 6. Return the result return preg_replace('/\s\s(?!\s)/', ' ', strtr(implode(' ', str_split(strtoupper($text))), $this->trArray)); } public function toPlainText($morse_code) { // 1. Flip the keys & values in the translation array // 2. Use the string translate function to perform the translation // using the flipped translation array // 3. Remove the spaces between letters return preg_replace('/\s(?!\s)/', '', strtr($morse_code, array_flip($this->trArray))); } } ?>
- xxxjj18
Spoiler
<?php /** Morse Code Converter * Created by Jalen Garnett * Created on March 26th, 2012 */ interface iMorseCodeTranslator { /** * @param (string) $text - Plain text that will be converted to morse code * * @return (string) - Morse code string */ public function toMorseCode($text); /** * @param (string) $morse_code - Morse code that will be converted to plain text * * @return (string) - Plain text string */ public function toPlainText($morse_code); } class MorseCodeTranslator implements iMorseCodeTranslator { //Create an array that contains every translation of assorted characters in Morse Code protected $MorseValues = Array(); protected $plainText = Array(); //Upon construction, populate the $MorseValues and $plainText arrays public function __construct() { $this->MorseValues = Array("a" => ".-", "b" => "-...", "c" => "-.-/>.", "d" => "-..", "e" => ".", "f" => "..-.", "g" => "--.", "h" => "....", "i" => "..", "j" => ".---", "k" => "-.-/>", "l" => ".-..", "m" => "--", "n" => "-.", "o" => "---", "p" => ".--.", "q" => "--.-/>", "r" => ".-.", "s" => "...", "t" => "-", "u" => "..-", "v" => "...-", "w" => ".--", "x" => "-..-", "y" => "-.-/>-", "z" => "--..", "0" => "-----", "1" => ".----", "2" => "..---", "3" => "...--", "4" => "....-", "5" => ".....", "6" => "-....", "7" => "--...", "8" => "---..", "9" => "----.", "." => ".-.-/>.-", "," => "--..--", "?" => "..--..", "'" => ".----.", " " => " "); foreach($this->MorseValues as $key => $value) { $this->plainText[$value] = $key; } } //Method to convert plain text to Morse Code public function toMorseCode($text) { //Create $morseCode; the variable that will be returned upon function completion $morseCode = null; if(!empty($text)) { $charArray = str_split($text); //Create an Array named $charArray to hold every character of the $text string for($i = 0; $i < count($charArray); $i++) { //Match each character in $charArray to a character inside of $MorseValues, make sure unsupported characters are not included if(isset($this->MorseValues[strtolower($charArray[$i])]) && $this->MorseValues[strtolower($charArray[$i])] != " ") { //Add the Morse Code value to the $morseCode variable $morseCode .= "{$this->MorseValues[strtolower($charArray[$i])]} "; }else{ //The character is a space $morseCode .= " "; } } return $morseCode; }else{ //No text inputted! Dx Dx Dx die(); } } //Function to convert Morse Code to plain text public function toPlainText($morse_code) { //Create the variable $plainTextString and return it upon function completion $plainTextString = null; if(!empty($morse_code)) { //Convert the $morse_code string into a character array containing each individual Morse Code 'letter' $charArray = explode(" ",$morse_code); for($i = 0; $i < count($charArray); $i++) { //Check to see if the $plainText array contains the Morse Code value and is not a space character, make sure unsupported characters are not included if(isset($this->plainText[strtolower($charArray[$i])]) && $this->plainText[strtolower($charArray[$i])] != " ") { //Add the plain text character to the $plainTextString string $plainTextString .= "{$this->plainText[strtolower($charArray[$i])]}"; }else{ //The character is a space $plainTextString .= " "; } } return $plainTextString; }else{ //No Morse Code inputted xP die(); } } } ?>
- Atli
Spoiler
/** * Represents a morse code character. */ class MorseCodeChar { /* ******************************** * Char => Morse code list * ********************************/ /** @var (array) $chars */ protected static $chars = array( "." => ".-.-/>.-", "," => "--..--", "?" => "..--..", "'" => ".----.", "A" => ".-", "B" => "-...", "C" => "-.-/>.", "D" => "-..", "E" => ".", "F" => "..-.", "G" => "--.", "H" => "....", "I" => "..", "J" => ".---", "K" => "-.-/>", "L" => ".-..", "M" => "--", "N" => "-.", "O" => "---", "P" => ".--.", "Q" => "--.-/>", "R" => ".-.", "S" => "...", "T" => "-", "U" => "..-", "V" => "...-", "W" => ".--", "X" => "-..-", "Y" => "-.-/>-", "Z" => "--..", "0" => "-----", "1" => ".----", "2" => "..---", "3" => "...--", "4" => "....-", "5" => ".....", "6" => "-....", "7" => "--...", "8" => "---..", "9" => "----." ); /* ******************************** * Instance attributes and methods. * ********************************/ /** @var (string) $char The key char. */ private $char; /** @var (string) The morse sequence. */ private $morse; /** * Initialize this instance. * @param (string) $code Either a key code or the morse sequence. * @throws InvalidArgumentException If the $code is invalid. */ public function __construct($char=null, $morse=null) { // Make sure the caller is not a complete idiot. if ($char === null && $morse === null) { throw new InvalidArgumentException("You need to provide at least one of the input parameters, genious!"); } // Try to use the key char to fill in the values. if ($char !== null) { $char = mb_strtoupper($char); if (array_key_exists($char, self::$chars)) { $this->char = $char; $this->morse = self::$chars[$char]; return; } } // Use the morse sequence to search for the values. if ($morse !== null && ($key = array_search($morse, self::$chars)) !== false) { $this->char = $key; $this->morse = $morse; return; } // The input params aren't valid. FLIP OUT! throw new InvalidArgumentException("The input values aren't valid. IDIOT!"); } /** * Get the key char for the morse sequence. * @return (string) */ public function getChar() { return $this->char; } /** * Get the morse sequence * @return (string) */ public function getMorse() { return $this->morse; } }
/** * A recursive closure implementation! */ class MorseCodeTranslator implements iMorseCodeTranslator { /** * @param (string) $text - Plain text that will be converted to morse code * @return (string) - Morse code string */ public function toMorseCode($text) { /** * A recursive closure that converts the input text into morse code. * @param (int) $i Internal counter. * @param (string) $output Internal output buffer. * @use (string) $text The input text. * @use (function) $convert A self-reference, to allow recursion. * @return (string) The final morse code. */ $convert = function($i=0, &$output="") use($text, &$convert) { // Fetch the next char. multi-byte because... just because! $char = mb_substr($text, $i, 1); // If the current char is a word separator it will be enough // to just add a single space. Each morse char is trailed by // a single space also, so this makes two. if ($char == " ") { $output .= " "; } else { // Get the next char and add it, with a space. $char = new MorseCodeChar($char); $output .= $char->getMorse() . " "; } // If the next index is within the string, recurse! if (++$i < mb_strlen($text)) { return $convert($i, $output); } else { // Returne the trimmed output, to remove the trailing // space. return trim($output); } }; return $convert(); } /** * @param (string) $morse_code - Morse code that will be converted to plain text * @return (string) - Plain text string */ public function toPlainText($morse_code) { /** * Converts the input text into plain text. * @param (int) $i Internal counter. * @param (string) $sequence Internal sequence buffer. * @param (string) $output Internal output buffer. * @use (string) $morse_code The input morse code string. * @use (function) A self-rererence, allowing recursion. * @return (string) The plain-text representation. */ $convert = function($i=0, $sequence="", &$output="") use($morse_code, &$convert) { // Fetch the next char. multi-byte because... just because! $char = mb_substr($morse_code, $i, 1); // If the char is a space or is empty, then the sequence is over. if ($char == " " || $char == "") { if ($sequence == "") { // If the sequence is empty, this is a word // separator. Only the second of two consecutive // spaces will reach this point. $output .= " "; } else { // Convert the sequence into a letter and // add it, then reset the sequence so the // next one can be read. $letter = new MorseCodeChar(null, $sequence); $output .= $letter->getChar(); $sequence = ""; } } else { // Add the current char to the current sequence! $sequence .= $char; } // While the next index is less than or equal to the // input string length, recurse! if (++$i <= mb_strlen($morse_code)) { return $convert($i, $sequence, $output); } else { // Otherwise just return the current output. return $output; } }; return $convert(); } }
- Dormilich
Spoiler
class MorseCodeTranslator implements iMorseCodeTranslator { public static $alphabet = array('A' => '.-', 'B' => '-...', 'C' => '-.-/>.', 'D' => '-..', 'E' => '.', 'F' => '..-.', 'G' => '--.', 'H' => '....', 'I' => '..', 'J' => '.---', 'K' => '-.-/>', 'L' => '.-..', 'M' => '--', 'N' => '-.', 'O' => '---', 'P' => '.--.', 'Q' => '--.-/>', 'R' => '.-.', 'S' => '...', 'T' => '-', 'U' => '..-', 'V' => '...-', 'W' => '.--', 'X' => '-..-', 'Y' => '-.-/>-', 'Z' => '--..', '0' => '-----', '1' => '.----', '2' => '..---', '3' => '...--', '4' => '....-', '5' => '.....', '6' => '-....', '7' => '--...', '8' => '---..', '9' => '----.', '.' => '.-.-/>.-', ',' => '--..--', '?' => '..--..', "'" => '.----.'); private $m2t; private $t2m; public function __construct() { $this->t2m = self::$alphabet; $this->m2t = array_flip(self::$alphabet); $this->m2t["_"] = " "; } public function toMorseCode($text) { $data = str_split(strtoupper($text)); $morse = array_map(array($this, "encode"), $data); return implode(" ", $morse); } public function toPlainText($morse_code) { $data = preg_replace("@[^.\- ]@", "", $morse_code); // clean morse code $data = str_replace(" ", " _ ", $data); // preserve word spacing $data = explode(" ", $data); $text = array_map(array($this, "decode"), $data); return implode("", $text); } private function encode($item) { return isset($this->t2m[$item]) ? $this->t2m[$item] : ""; } private function decode($item) { return isset($this->m2t[$item]) ? $this->m2t[$item] : ""; } }
We also have submissions in other languages.
- GunnerInc - Assembly
Spoiler
include masm32rt.inc toMorseCode PROTO lpszText:DWORD toPlainText PROTO lpszMorse_Code:DWORD CenterWindow PROTO mainWndHndl:DWORD,targetWndHndl:DWORD SaveToFile PROTO lpszText:DWORD,lpszMorse:DWORD .data ; Alpha szA db ".-", 0 szB db "-...", 0 szC db "-.-/>.", 0 szD db "-..", 0 szE db ".", 0 szF db "..-.", 0 szG db "--.", 0 szH db "....", 0 szI db "..", 0 szJ db ".---", 0 szK db "-.-/>", 0 szL db ".-..", 0 szM db "--", 0 szN db "-.", 0 szO db "---", 0 szP db ".--.", 0 szQ db "--.-/>", 0 szR db ".-.", 0 szS db "...", 0 szT db "-", 0 szU db "..-", 0 szV db "...-", 0 szW db ".--", 0 szX db "-..-", 0 szY db "-.-/>-", 0 szZ db "--..", 0 ; Numeric sz0 db "-----", 0 sz1 db ".----", 0 sz2 db "..---", 0 sz3 db "...--", 0 sz4 db "....-", 0 sz5 db ".....", 0 sz6 db "-....", 0 sz7 db "--...", 0 sz8 db "---..", 0 sz9 db "----.", 0 ; Special szDot db ".-.-/>.-", 0 szComma db "--..--", 0 szQuestion db "..--..", 0 szApost db ".----.", 0 szSpace db 32, 0 szMenu db "What would you like to convert?", 13, 10 db "(T)ext to Morse", 13, 10 db "(M)orse to Text", 13, 10 db "'Esc' to exit",13, 10 szPrompt db ">", 0 szTextPrompt db "Enter text to convert (128 chars max)", 13, 10, 0 szMorsePrompt db "Enter morse code to convert (128 chars max)", 13, 10, 0 szAgain db 13, 10, "Again Y/N (S)ave>" ,0 CRLF db 13, 10, 0 szEmptyString db "Uh, I cannot convert an empty string!", 13, 10, 0 szTitle db "codeprada PHP Challenge, Morse Code Translator", 0 szDlgFilter db "Text Files", 0, "*.txt", 0, 0 szDlgExt db "txt", 0 szTitleSave db "Save output to file", 0 ; Lookup table - pointers to valid chars MorseTable dd 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 dd 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 dd offset szSpace,0,0,0,0,0,0,offset szApost,0,0,0,0, offset szComma,0, offset szDot,0 dd offset sz0, offset sz1, offset sz2, offset sz3, offset sz4, offset sz5, offset sz6, offset sz7, offset sz8, offset sz9,0,0,0,0,0, offset szQuestion dd 0,offset szA, offset szB, offset szC, offset szD, offset szE, offset szF, offset szG, offset szH, offset szI, offset szJ, offset szK, offset szL, offset szM, offset szN, offset szO dd offset szP, offset szQ, offset szR, offset szS, offset szT, offset szU, offset szV, offset szW, offset szX, offset szY, offset szZ,0,0,0,0,0 dd 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 dd 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 dd 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 dd 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 dd 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 dd 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 dd 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 dd 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 dd 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 dd 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 MorseTableSize equ ($ - MorseTable) /4 .data? hHeap dd ? lpInput dd ? .code MorseCodeTranslator: invoke GetProcessHeap mov hHeap, eax ; lets center the console window to desktop invoke GetConsoleWindow xchg eax, edi invoke GetDesktopWindow invoke CenterWindow, eax, edi ; macro to set console caption SetConsoleCaption offset szTitle PrintMenu: print offset szMenu ; print is a macro to simplify console writting MenuSelection: getkey ; get keypress from console .if eax == "T" || eax == "t" ; if it is t... print "Text to Morse", 13, 10 print offset szTextPrompt TextPrompt: print offset szPrompt mov lpInput, input() ; get text invoke szTrim, lpInput ; trim leading and trailing spaces invoke szLen, lpInput .if eax == 0 print offset szEmptyString ; uh, oh, empty string go again jmp TextPrompt .endif invoke toMorseCode, lpInput ; convert it xchg eax, ebx print ebx ; print it .elseif eax == "M" || eax == "m" ; if char is a m print "Morse to Text", 13, 10 print offset szMorsePrompt MorsePrompt: print offset szPrompt mov lpInput, input() invoke szTrim, lpInput invoke szLen, lpInput .if eax == 0 print offset szEmptyString jmp MorsePrompt .endif invoke szCatStr, lpInput, offset szSpace invoke toPlainText, lpInput xchg eax, ebx print ebx .elseif eax == 27 jmp GoodBye ; esc selected .else jmp MenuSelection ; all others just loop back to getkey .endif print offset szAgain ; want to go again? SelectAgain: getkey .if eax == "Y" || eax == "y" ; after each selection, free our returned buffer invoke HeapFree, hHeap, 0, ebx cls jmp PrintMenu .elseif eax == "N" || eax == "n" invoke HeapFree, hHeap, 0, ebx print offset CRLF .elseif eax == "S" || eax == "s" invoke SaveToFile, lpInput, ebx invoke HeapFree, hHeap, 0, ebx cls jmp PrintMenu .else jmp SelectAgain .endif GoodBye: invoke ExitProcess, 0 COMMENT ! ############################################################# toMorseCode - Converts text to morse code In: lpszText = Pointer to buffer containing string to convert Returns: Pointer to buffer containing morse code **Free with HeapFree when done. ############################################################! toMorseCode proc uses esi edi ebx lpszText:DWORD mov esi, lpszText invoke szUpper, esi ; Convert string to uppercase invoke szLen, esi ; get length shl eax, 3 ; multiply length by 8 invoke HeapAlloc, hHeap, HEAP_ZERO_MEMORY, eax xchg eax, edi ; save pointer lea ebx, MorseTable ; get address of lookup table ConvertNext: movzx eax, byte ptr [esi] ; get char at current pointer test eax, eax ; is it zero? jz Done ; yup, goodbye cmp eax, 32 ; is it a space je DoSpace ; must be mov ecx, [ebx + 4 * eax] ; get pointer to morse char from table index in eax test ecx, ecx ; is it a valid pointer jz NextChar ; nope jmp GoodChar DoSpace: invoke szCatStr, edi, offset szSpace ; must be a space, append a space to our out buffer jmp NextChar ; GoodChar: invoke szMultiCat, 2, edi, ecx, offset szSpace ; append morse char and space to our out buffer NextChar: inc esi ; increase our string pointer jmp ConvertNext Done: xchg edi, eax ; move converted morse buffer pointer to eax for return ret toMorseCode endp COMMENT ! ############################################################# toPlainText - Converts morse code to text In: lpszMorse_Code = Pointer to buffer containing morse code to convert Returns: Pointer to buffer containing morse code **Free with HeapFree when done. ############################################################! toPlainText proc uses esi edi ebx lpszMorse_Code local RetBuf:DWORD ; pointer to converted buffer local TempBuf[8]:BYTE ; temp buf to hold current morse char mov esi, lpszMorse_Code ; put addres of morse sting in esi lea ebx, TempBuf ; get address of TempBuf invoke szLen, esi ; get lenght of morse string invoke HeapAlloc, hHeap, HEAP_ZERO_MEMORY, eax ; and create buffer to hold it xchg eax, edi ; buffer pointer mov RetBuf, edi ; buffer pointer for return NextCode: movzx eax, byte ptr [esi] ; get current byte at current pointer cmp eax, 32 ; is it a space? je GetMorseIndex ; yes, got morse letter test eax, eax ; byte a zero? jz MorseDone ; yep, end of buffer mov byte ptr [ebx], al ; move byte to our buffer inc esi ; increase morse pointer inc ebx ; increase return pointer jmp NextCode ; get next byte GetMorseIndex: mov byte ptr [ebx], 0 ; NULL term our temp buffer lea ebx, TempBuf ; get start address of buffer push ebx ; get index of morse char, will be ASCII code for letter call GetIndex ; mov byte ptr [edi], al ; move letter to our ret buffer inc edi ; increase return buffer pointer lea ebx, TempBuf ; get start address of buffer inc esi ; increase string pointer cmp byte ptr [esi], 32 ; is next char a space? jne @F ; no, get next morse char inc esi ; yes, increase string pointer mov byte ptr [edi], 32 ; move space char to return buffer inc edi ; increase ret pointer @@: jmp NextCode MorseDone: mov eax, RetBuf ; move converted buffer pointer to eax for return ret toPlainText endp COMMENT ! ############################################################# GetIndex - Searches Morse Code lookup table for match In: lpszMorseChar = Pointer to buffer with morse code character Returns: 0 for no match Index of match = ASCII code of morse code char ############################################################! GetIndex proc uses esi edi ebx lpszMorseChar:DWORD xor esi, esi ; zero our counter mov edi, offset MorseTable ; load up lookup table MorseSearch: mov ebx, [edi + 4 * esi] ; get char pointer at index in esi test ebx, ebx ; if zero - not a valid char jz NotFound ; invoke Cmpi, lpszMorseChar, ebx ; are Lookup table char and MorseChar the same? test eax, eax jnz NotFound xchg esi, eax ; yup, put counter value in eax for return jmp SearchDone NotFound: inc esi ; increase our counter cmp esi, MorseTableSize ; are we at end of table? jne MorseSearch ; nope, get next lookup pointer MorseNotFound: xor eax, eax ; not found, return 0 SearchDone: ret GetIndex endp CenterWindow PROC USES ebx esi edi mainWndHndl:DWORD, targetWndHndl:DWORD LOCAL mainWnd :RECT LOCAL targetWnd :RECT xor eax, eax push eax lea eax, DWORD PTR [ebp-20h] push eax mov edx, DWORD PTR [ebp+0Ch] push edx call GetWindowRect lea eax, DWORD PTR [ebp-20h] mov esi, targetWnd.bottom mov edi, targetWnd.right sub esi, targetWnd.top sub edi, targetWnd.left push esi push edi shr esi, 1 shr edi, 1 lea eax, DWORD PTR [ebp-10h] push eax mov edx, DWORD PTR [ebp+8] push edx call GetWindowRect mov eax, mainWnd.bottom mov ecx, mainWnd.right sub eax, mainWnd.top sub ecx, mainWnd.left shr eax, 1 shr ecx, 1 sub eax, esi sub ecx, edi mov ebx, mainWnd.top mov edx, mainWnd.left add ebx, eax add edx, ecx push ebx push edx mov eax, targetWndHndl push eax call MoveWindow ret CenterWindow ENDP SaveToFile proc uses edi esi ebx lpszText:DWORD, lpszMorse:DWORD local hSaveFile:DWORD local lpWritten:DWORD local ofn:OPENFILENAME local SavePath[MAX_PATH + 1]:BYTE invoke RtlZeroMemory, addr ofn, sizeof OPENFILENAME mov ofn.lStructSize, sizeof OPENFILENAME mov ofn.hwndOwner, edi invoke GetModuleHandle, NULL mov ofn.hInstance, eax mov ofn.Flags, OFN_HIDEREADONLY or OFN_EXPLORER mov ofn.lpstrFilter, offset szDlgFilter mov ofn.lpstrTitle, offset szTitleSave lea esi, SavePath mov ofn.lpstrFile, esi mov ofn.nMaxFile, MAX_PATH + 1 mov ofn.lpstrDefExt, offset szDlgExt invoke GetSaveFileName, addr ofn invoke szLen, esi .if eax > 0 ; open the file if it exists, or create new if not exist invoke CreateFile, esi, GENERIC_WRITE, NULL, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL mov hSaveFile, eax ; set file pointer to end of file to append invoke SetFilePointer, eax, NULL, NULL, FILE_END invoke szLen, lpszText lea ebx, lpWritten invoke WriteFile, hSaveFile, lpszText, eax, ebx, NULL invoke WriteFile, hSaveFile, offset CRLF, 2, addr lpWritten, NULL invoke szLen, lpszMorse invoke WriteFile, hSaveFile, lpszMorse, eax, ebx, NULL invoke WriteFile, hSaveFile, offset CRLF, 2, addr lpWritten, NULL invoke CloseHandle, hSaveFile .endif ret SaveToFile endp end MorseCodeTranslator
- AdamSpeight2008 - VB.net (.net 4.5)
Spoiler
Public Module MorseCode Private Morse()() As String = { ({"A", ".-"}), ({"B", "-..."}), ({"C", "-.-/>."}), ({"D", "-.."}), ({"E", "."}), ({"F", "..-."}), ({"G", "--."}), ({"H", "...."}), ({"I", ".."}), ({"J", ".---"}), ({"K", "-.-/>"}), ({"L", ".-.."}), ({"M", "--"}), ({"N", "-."}), ({"O", "---"}), ({"P", ".--."}), ({"Q", "--.-/>"}), ({"R", ".-."}), ({"S", "..."}), ({"T", "-"}), ({"U", "..-"}), ({"V", "...-"}), ({"W", ".--"}), ({"X", "-..-"}), ({"Y", "-.-/>-"}), ({"Z", "--.."}), ({"0", "-----"}), ({"1", ".----"}), ({"2", "..---"}), ({"3", "...--"}), ({"4", "....-"}), ({"5", "....."}), ({"6", "-...."}), ({"7", "--..."}), ({"8", "---.."}), ({"9", "----."}), ({".", ".-.-/>.-"}), ({",", "--..--"}), ({"?", "..--.."})} '({"",".----."}), <Runtime.CompilerServices.Extension()> Public Iterator Function FromMorseCode(s As String) As IEnumerable(Of Char) Dim lu = Function(ss As IEnumerable(Of Char)) Dim ns As New String(ss.ToArray()) Dim l = (From mc In Morse Where mc(1).Equals(ns) Select mc(0)).FirstOrDefault() Return l End Function Dim en = s.GetEnumerator Dim DotsAndDashes As New List(Of Char) Dim prev As Char = Nothing While en.MoveNext() Select Case en.Current Case "."c, "-"c : DotsAndDashes.Add(en.Current) Case " "c : Yield If(prev <> " ", lu(DotsAndDashes), " "c) : DotsAndDashes.Clear() ' True: Inter-Letter False: Inter-Word gap Case Else End Select prev = en.Current End While If DotsAndDashes.Count > 0 Then Yield lu(DotsAndDashes) DotsAndDashes.Clear() End Function <Runtime.CompilerServices.Extension()> Public Iterator Function ToMorseCode(s As String) As IEnumerable(Of Char) For Each ch In s If ch = " " Then Yield " "c : Yield " "c ' Inter-Word Gap Else Dim cs = (From mc In Morse Where mc(0).Equals(ch) Select mc(1)).FirstOrDefault() If cs <> "" Then For Each l In cs Yield l ' Dot / Dash Next Yield " " 'Inter-Char gap End If End If Next End Function End Module
This post has been edited by codeprada: 19 April 2012 - 04:21 PM

New Topic/Question
Reply


MultiQuote


|