Recent Entries 10
- pattern minor 112d agoMorse code translator GUII made a Morse code translator in Java in which a user inputs a word/words into a text field and the program converts it to Morse code and beeps the Morse code. I have a feeling that my code could be much better, and that it is not efficient enough. Please tell me if there is anything wrong with my code, including efficiency and coding conventions. ``` import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; public class MorseCode extends JFrame implements ActionListener{ char[] alpha = { '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', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', ' ' }; String[] dottie = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----.", "-----", "|" }; public static void play(String filename) { try { Clip clip = AudioSystem.getClip(); clip.open(AudioSystem.getAudioInputStream(new File(filename))); clip.start(); } catch (Exception exc) { exc.printStackTrace(System.out); } } JTextField wordField; JTextField morseField; JButton convertButton; public MorseCode() { getContentPane().setLayout(null); setSize(300, 300); setVisible(true); setDefaultCloseOperation(EXIT_ON_CLOSE); JLabel lblEnglish = new JLabel("English"); getContentPane().add(lblEnglish); lblEnglish.setBounds(10, 11, 46, 14); wordField = new JTextField(); getContentPane().add(wordField); wordField.setBounds(10, 36,
- pattern moderate 112d agoMorse Code ConversionChallenge Write a program which reads a file containing Morse Code and outputs the conversion. Specifications - The first argument is a path to a file. - The file contains multiple lines. - Each line is a string of Morse code. - Each letter is separated by a space. - Each word is separated by two spaces. Constraints - The input file is correctly formatted. - The Morse Code strings are alphanumeric. Sample Input ``` .- ...- ..--- .-- .... .. . -.-. -..- ....- ..... -... .... ...-- ``` Sample Output AV2WHIECX 45 BH3 Source My Solution: ``` import sys import re morse_alphabet = { '' : ' ', '.-' : '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' } def decode(morse): decoded = '' line = re.split('\s', morse) for letter in line: decoded += morse_alphabet.get(letter) return decoded def main(filename): with open(filename) as input_file: for line in input_file: print(decode(line)) if __name__ == "__main__": try: main(sys.argv[1]) except: sys.exit("No argument provided / file not found.") ``` Applying the insight gained from my previous question. It seems fairly succinct but I wonder is it pythonic?
- pattern minor 112d agoConverting Morse CodeChallenge Write a program which reads a file containing Morse Code and outputs the conversion. Specifications - The first argument is a path to a file. - The file contains multiple lines. - Each line is a string of morse code. - Each letter is separated by a space. - Each word is separated by two spaces. Constraints - The input file is correctly formatted. - The Morse Code strings are alphanumeric. Sample Input ``` .- ...- ..--- .-- .... .. . -.-. -..- ....- ..... -... .... ...-- ``` Sample Output AV2WHIECX 45 BH3 Source My Solution: ``` import java.io.File; import java.io.FileNotFoundException; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class Solution { private static final Map morseAlphabet = new HashMap<>(); static { morseAlphabet.put(".-", 'A'); morseAlphabet.put("-...", 'B'); morseAlphabet.put("-.-.", 'C'); morseAlphabet.put("-..", 'D'); morseAlphabet.put(".", 'E'); morseAlphabet.put("..-.", 'F'); morseAlphabet.put("--.", 'G'); morseAlphabet.put("....", 'H'); morseAlphabet.put("..", 'I'); morseAlphabet.put(".---", 'J'); morseAlphabet.put("-.-", 'K'); morseAlphabet.put(".-..", 'L'); morseAlphabet.put("--", 'M'); morseAlphabet.put("-.", 'N'); morseAlphabet.put("---", 'O'); morseAlphabet.put(".--.", 'P'); morseAlphabet.put("--.-", 'Q'); morseAlphabet.put(".-.", 'R'); morseAlphabet.put("...", 'S'); morseAlphabet.put("-", 'T'); morseAlphabet.put("..-", 'U'); morseAlphabet.put("...-", 'V'); morseAlphabet.put(".--", 'W'); morseAlphabet.put("-..-", 'X'); morseAlphabet.put("-.--", 'Y'); morseAlphabet.put("--..", 'Z'); morseAlphabet.put("-----", '0'); morseAlphabet.put(".----", '1'); morseAlphabet.put("..---", '2'); morseAlphabet.put("...--", '3'); mor
- pattern minor 112d agoMorse code translator in C#I'm writing a Morse code translator for homework in C#. It takes an input from the user and returns the Morse code version of their input. I understand that this code may look horrible, so how could I improve it in terms of efficiency and readability? Program.cs ``` using System; using System.Collections.Generic; namespace MorseCodeTranslator { class Program { static Dictionary translator; static void Main(string[] args) { InitialiseDictionary(); getUserInput(); } private static void InitialiseDictionary() { char dot = '.'; char dash = '−'; translator = new Dictionary() { {'a', string.Concat(dot, dash)}, {'b', string.Concat(dash, dot, dot, dot)}, {'c', string.Concat(dash, dot, dash, dot)}, {'d', string.Concat(dash, dot, dot)}, {'e', dot.ToString()}, {'f', string.Concat(dot, dot, dash, dot)}, {'g', string.Concat(dash, dash, dot)}, {'h', string.Concat(dot, dot, dot, dot)}, {'i', string.Concat(dot, dot)}, {'j', string.Concat(dot, dash, dash, dash)}, {'k', string.Concat(dash, dot, dash)}, {'l', string.Concat(dot, dash, dot, dot)}, {'m', string.Concat(dash, dash)}, {'n', string.Concat(dash, dot)}, {'o', string.Concat(dash, dash, dash)}, {'p', string.Concat(dot, dash, dash, dot)}, {'q', string.Concat(dash, dash, dot, dash)}, {'r', string.Concat(dot, dash, dot)}, {'s', string.Concat(dot, dot, dot)}, {'t', string.Concat(dash)}, {'u', string.Concat(dot, dot, dash)}, {'v', string.Concat(dot, dot, dot, dash)}, {'w', string.Concat(dot, dash, dash)}, {'x', string.Concat(
- pattern moderate 112d agoMorse code translatorI have a Morse Code translator, which can translate text to Morse code and vice-versa. Note that for the two files that the first three lines are generated by the Code::Blocks IDE. translator.h ``` #ifndef SPLIT_H_INCLUDED #define SPLIT_H_INCLUDED #endif // SPLIT_H_INCLUDED #include #include #include #include "split.h" std::string SPACE (" "); std::map charMap; std::map morseMap; bool hasInit = false; void init() { charMap['a'] = ".-"; charMap['b'] = "-..."; charMap['c'] = "-.-."; charMap['d'] = "-.."; charMap['e'] = "."; charMap['f'] = "..-."; charMap['g'] = "--."; charMap['h'] = "...."; charMap['i'] = ".."; charMap['j'] = ".---"; charMap['k'] = "-.-"; charMap['l'] = ".-.."; charMap['m'] = "--"; charMap['n'] = "-."; charMap['o'] = "---"; charMap['p'] = ".--."; charMap['q'] = "--.-"; charMap['r'] = ".-."; charMap['s'] = "..."; charMap['t'] = "-"; charMap['u'] = "..-"; charMap['v'] = "...-"; charMap['w'] = ".--"; charMap['x'] = "-..-"; charMap['y'] = "-.--"; charMap['z'] = "--.."; charMap['0'] = "-----"; charMap['1'] = ".----"; charMap['2'] = "..---"; charMap['3'] = "...--"; charMap['4'] = "....-"; charMap['5'] = "....."; charMap['6'] = "-...."; charMap['7'] = "--..."; charMap['8'] = "---.."; charMap['9'] = "----."; charMap['.'] = ".-.-.-"; charMap[','] = "--..--"; charMap['?'] = "..--.."; charMap[' '] = "/"; for (std::map::iterator i = charMap.begin(); i != charMap.end(); i++) { morseMap[i -> second] = i -> first; } } std::string translateToMorse(std::string plainText) { if (!hasInit) { init(); } std::string result; for (int i = 0; plainText[i]; i++) { result.append(charMap[plainText[i]]); result.append(SPACE); } return result; } std::string translateFromMorse(std::string morseText) { if (!hasInit) { init(); } std::s
- pattern moderate 112d agoSimple Morse code interpreterThis is a simple Morse code interpreter with a CLI. It's a naive table-lookup implementation, and uses my-py for type checking. It automatically detects the input (English or Morse) and converts accordingly. It has the simplest possible CLI that I could think of. There is a git repo here. I don't often write Python; I write Ruby for work and Clojure in my free time, but I do love Python and have a bit of experience with it. I welcome any suggestions on how to write more "Pythonic" code, simpler code or interfaces, or how to make the code more robust. Ideally, I want it to "just work" and be able to take even malformed data. Unfortunately, I think I need to keep the `msg` argument surrounded by quotes from the command line, otherwise the shell will interpret a single or double dot as the current or parent directory. I'm considering using the Boyer-Moore algorithm instead of a lookup table, but I'm not sure if that's worth it. `import re import argparse from typing import Dict eng = { "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" : "----.", "," : ",", "." : ".", "!" : "!", "?" : "?", } # type: Dict[str, str] morse = {v: k for k, v in eng.items()} # type: Dict[str, str] def morsep(msg: str) -> bool: if msg[0][0] in ['.', '-', '/']: return True else: return False def morse_to_eng(msg: str) -> str: out = "" # type: str split_msg = re.
- pattern moderate 112d agoMorse code string - follow-upThis is probably one of the many follow-ups coming. What I have edited: - Added `equals()` and `hashCode()` - Added `.` and `,` to my Morse code "dictionary" - Used a `Pattern` for regex checking - Edited method names Concerns: - Any bad practices in the new code? - Does it "smell"? ``` import java.util.regex.Pattern; public class MorseString { public static final char CHAR_SEPARATOR = ' '; public static final char WORD_SEPARATOR = '/'; public static final char DOT = '.'; public static final char DASH = '-'; private String string; private String codeString; /* * Constructor that takes the Morse Code as a String as a parameter */ public MorseString(String s) { if(!isValidMorse(s)) { throw new IllegalArgumentException("s is not a valid Morse Code"); } if(!s.isEmpty()) { this.string = translate(s); } else { this.string = s; } this.codeString = s; } /* * Checks if it is a valid Morse Code */ private static final Pattern VALID_MORSE_PATTERN = Pattern.compile( "(" + Pattern.quote(Character.toString(DASH)) + "|" + Pattern.quote(Character.toString(DOT)) + "|" + Pattern.quote(Character.toString(WORD_SEPARATOR)) + "|\\s)*"); public boolean isValidMorse(CharSequence ch) { return VALID_MORSE_PATTERN.matcher(ch).matches(); } /* * Traslates from Morse in a String to a String * e.g. ".... .." to "hi" */ private String translate(String code) { String[] words = code.split(Character.toString(WORD_SEPARATOR)); StringBuilder result = new StringBuilder(words.length * words[0].length()); // Rough guess of size for(String word : words) { String[] letters = word.trim().split(Character.toString(CHAR_SEPARATOR)); for(String letter : letters) { result.append(MorseCode.decode(let
- pattern minor 112d agoMorse code stringI was bored recently and decided to write a class, `MorseString`. What this class does, is it takes a `String` that is coded like Morse (`.... ..`) and stores it. It also translates the `String` that is coded like Morse into a more "English-friendly" way (`HI`). This is just the basics I have written; there is much more to come. ``` public class MorseString { public static final char CHAR_SEPARATOR = ' '; public static final char WORD_SEPARATOR = '/'; public static final char DOT = '.'; public static final char DASH = '-'; private String string; private String codeString; /* * Constructor that takes the Morse Code as a String as a parameter */ public MorseString(String s) { if(!isValidMorse(s)) { throw new IllegalArgumentException("s is not a valid Morse Code"); } if(!s.isEmpty()) { this.string = translate(s); } else { this.string = s; } this.codeString = s; } /* * Checks if it is a valid Morse Code */ private boolean isValidMorse(String s) { return s.matches("[" + DOT + "\\" + DASH + WORD_SEPARATOR + "\\s" + "]*"); } /* * Traslates from Morse in a String to a String * e.g. ".... .." to "hi" */ private String translate(String code) { String[] words = code.split(Character.toString(WORD_SEPARATOR)); StringBuilder result = new StringBuilder(words.length * words[0].length()); // Rough guess of size for(String word : words) { String[] letters = word.trim().split(Character.toString(CHAR_SEPARATOR)); for(String letter : letters) { result.append(MorseCode.decode(letter)); } result.append(CHAR_SEPARATOR); } return result.toString().substring(0, result.length() - 1); } public static MorseString parse(String s) { if (!s.matches("[\\s\\dA-Za-z]*")) { throw n
- pattern moderate 112d agoMorse code converterI wanted an uncomplicated project to get myself started again. Although this works I was wondering if it's the best approach, especially when it comes to validation parts? It seems to me that I'm potentially looping quite a while, and this may not be the best or even common practice. I was hoping the CR community could enlighten me on this matter, as well as any other shortcomings this suffers from, as it has graciously done thus far. ``` public enum Morse { MC_1(".----", '1'), MC_2("..---", '2'),MC_3("...--", '3'), MC_4("....-", '4'), MC_5(".....", '5'), MC_6("-....", '6'), MC_7("--...", '7'), MC_8("---..", '8'), MC_9("----.", '9'), MC_0("-----", '0'), MC_A(".-", 'A'), MC_B("-...", 'B'), MC_C("-.-.", 'C'), MC_D("-..", 'D'), MC_E(".", 'E'), MC_F("..-.", 'F'), MC_G("--.", 'G'), MC_H("....", 'H'), MC_I("..", 'I'), MC_J(".---", 'J'), MC_K("-.-", 'K'), MC_L(".-..", 'L'), MC_M("--", 'M'), MC_N("-.", 'N'), MC_O("---", 'O'), MC_P(".--.", 'P'), MC_Q("--.-", 'Q'), MC_R(".-.", 'R'), MC_S("...", 'S'), MC_T("-", 'T'), MC_U("..-", 'U'), MC_V("...-", 'V'), MC_W(".--", 'W'), MC_X("-..-", 'X'), MC_Y("-.--", 'Y'), MC_Z("--..", 'Z'), MC_SPACE("/", ' '); public final String morse; public final char code; Morse(String morse, char code) { this.morse = morse; this.code = code; } } ``` This contains the `Main` class: ``` import java.util.Scanner; public class MorseCodeConverter { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter String to be converted to Morse Code: "); String userInput = input.nextLine(); System.out.println(morseConversion(userInput)); } public static String morseConversion(String s) { String ms = s.toUpperCase().trim(); // modified string StringBuilder result = new StringBuilder(); for (int i = 0; i < ms.length(); i++) { isValid(ms.char
- pattern moderate 112d agoMorse code emitterAs the first step for writing a Morse code practice program, I thought I'd start with the very simplest step of a text-based Morse code translator. This simple program reads lines from `stdin` and emits them as a text-based representation of the Morse code equivalent. Any character that doesn't have a Morse code equivalent is simply skipped. I'm interested particularly in a few things. - Is there a better representation than `map` that I should use? - Is there a way to declare it as `constexpr`? - Would this be better implemented as a `facet`? The private `emit` member function is intended to be replaced by a mechanism that will queue up audio output. Morse.cpp: ``` #include #include #include #include /* Morse code ITU-4 M.1677 */ class Morse { public: Morse &operator coding; }; std::map Morse::coding = { {' ', " "}, {'\n', "\n"}, {'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', "--.."}, {'1', ".----"}, {'2', "..---"}, {'3', "...--"}, {'4', "....-"}, {'5', "....."}, {'6', "-...."}, {'7', "--..."}, {'8', "---.."}, {'9', "----."}, {'0', "-----"}, {'.', ".-.-.-"}, {',', "--..--"}, {'?', "..--.."}, {'-', "-...-"}, {'/', "-..-."}, {'@', ".--.-."}, {'+', ".-.-."}, {'=', "-..."}, {'\'', ".----"}, {'(', "-.--"}, {')', "-.--."}, {'\"', ".-..-"}, {'\x04', "...-.-"}, //EOT = SK }; int main() { using namespace std; Morse morse; string line; while (getline(cin, line)) morse << line << '\n'; } ```