Morsecode

leus

New member
hi jungs, ich habe das Programm mal in Ruby geschrieben. Die Leerstellen habe ich als # dargestellt und die einzeln Buchstaben trenne ich mit |, dies dient nur der besseren Unterscheidung. Werde mich noch dran setzten und die Rückwärtsfunktion auch noch schreiben
Code:
morse ={'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'=>'-----',' '=>'#'}
erg =[]
print "Bitte Satz eingeben: "
wort = gets.chomp.upcase.split("").each{|e| erg.push(morse[e])}
puts satz = erg.join("|")

mfg
leus
 

Ivan Dolvich

New member
GiggyGsk, ich denke Du hast richtig für die erste Variante einen Hash statt Array verwendet, so musst Du nicht im Array suchen sondern kriegst das Morse-Zeichen direkt. Würde auch so einen Ansatz wählen. Aber vielleicht solltest du noch ein Hash für den Rückweg nehmen, den Du anhand des ersten erzeugen kannst (momentan suchst du sequentiell im Hash soweit ich den code verstehe?).

leus, auch eine wirklich nette kurze Lösung in Ruby :)

Ivan
 

System.I/O

New member
Moinsen,

hier is noch eine Lösung der Aufgabe in C#

Code:
using System;
using System.Collections.Generic;

class MorseCrypter {	
	private string[] morseAlphabet;
	private string[] alphabet;
	
	public MorseCrypter() {
		this.morseAlphabet = new string[]{".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--..",".-.-","---.","..--","...--..",".-.-.","--..--","-.-.-","-.--.-","-...-",".----","..---","...--","....-",".....","-....","--...","---..","----.","-----"};
		this.alphabet = new 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","Ä","Ö","Ü","ß","<",",","(",")","=","1","2","3","4","5","6","7","8","9","0"};	
	}
	
	public string[] Encrypt(string text) {
		List<string> morseCodes = new List<string>();
		for(int count=0; count < text.Length; count++) {
			for(int index=0; index < this.alphabet.Length; index++) {
				if(this.alphabet[index] == Convert.ToString(text[count]).ToUpper())
					morseCodes.Add(this.morseAlphabet[index]);			
			}
		}
		return morseCodes.ToArray();
	}
	
	public string Decrypt(string[] morseCodes) {
		string text = string.Empty;
		foreach(string morseCode in morseCodes) {
			for(int index=0; index < this.morseAlphabet.Length; index++) {
				if(this.morseAlphabet[index] == morseCode)
					text = text.Insert(text.Length, this.alphabet[index]);
			}
		}
		return text;
	}
}

class MainClass {
	public static void Main() {
		MorseCrypter crypter =  new MorseCrypter();
		Console.Write("1: Text to MorseCode\n2: MorseCode to Text\n\nAuswahl: ");		
		switch(Console.ReadLine()) {
			case "1":
				Console.Write("\nText eingeben: ");
				string[] morseCodes = crypter.Encrypt(Console.ReadLine());
				Console.Write("\nMorseCodes: ");
				foreach(string morseCode in morseCodes) {
					Console.Write(morseCode+" ");
				}
				break;
			case "2":
				Console.Write("\nMorseCode eingeben: ");				
				Console.Write("\nText: "+crypter.Decrypt(Console.ReadLine().Split(' ')));
				break;
			default:
				Console.Write("\nUngueltige Auswahl !!!");
				break;		
		}	
		Console.Read();
	}
}
 

Indiziert

Member
Hallo zusammen,

habe vor paar tagen mit Python angefangen, und diese aufgabe nochmal nachprogrammiert:

Code:
import string

morsecode={"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":"-----"," ":" "}

text=string.lower(raw_input("Bitte den Fliesstext hier eingeben: \n")) 
liste=list(text)
i=0
for a in range(len(liste)):
	print morsecode[liste[i]], 
	i+=1

ich habe das mit linux geprogt und habe ein problem, wieso bekomme ich ne fehlermeldung wenn ich den unicode verwende (s=u(öäü)). Da kommt immer ne fehlermeldung, wieso?

und wie kann ich den fertig ausgegebenen morsecode in eine variable zwingen?

mfg
 

ravenstorm04

New member
Code:
import string   
morsecode={"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":"-----"," ":" "}   
text=string.lower(raw_input("Bitte den Fliesstext hier eingeben: \n"))  
liste=list(text) 
ausgabe=""  
for a in range(len(liste)):  	
    ausgabe+=morsecode[liste[a]] 
print ausgabe
Meinst du etwa so ?
mfg

ps. Wenn du innerhalb der forschleife a als Zählvariable nimmst, braucht man nicht mehr i dafür "missbrauchen"
 

derLichtschalter

New member
So, hier meine vorläufige Lösung in Java

EDIT: das hier ist meine vorläufig endgültige Version ;-):

Code:
import java.awt.event.*;
import javax.swing.*;

public class MorseCode extends JFrame {
	
	static char[] 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',
		'Ä', 'Ö', 'Ü', '.', ',', '(', ')', '='};
	
	static String[] Morsecode = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", 
		"..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", 
		"..-", "...-", ".--", "-..-", "-.--", "--..",
		"-----", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----.",
		".-.-", "---.", "..--", ".-.-.", "--..--", "-.-.-", "-.--.-", "-...-"};
	
	static String eingabe;
	static String ausgabe = "";
	static String[] segments;
	static int Länge;
	static int s;
	
	public static void main (String args []) {
		MorseCode Fenster = new MorseCode();
		Fenster.setSize(800, 400);
		
		final JTextArea TextFeld = new JTextArea();
		TextFeld.setPreferredSize(new java.awt.Dimension(780,200));
		
		final JLabel Label = new JLabel("Morsezeichen durch I trennen, Wörter durch Leer");
		Label.setPreferredSize(new java.awt.Dimension(300,200));
		
		JButton Button1 = new JButton("Übersetze in Morse-Code");	
		Button1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				eingabe = TextFeld.getText();
				for (int i = 0; i < eingabe.length(); i++) {
					char Buchstabe = eingabe.charAt(i);
					encrypt(Buchstabe);
				}
				Label.setText(ausgabe + "...-...");
				eingabe = "";
				ausgabe = "";
			}
		});
		
		JButton Button2 = new JButton("Übersetze in lat. Buchstaben");
		Button2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				eingabe = TextFeld.getText();
				MorseLänge(eingabe);
				for (int i = 0; i < Länge; i++) {
					String Morsezeichen = segments[i];
					decrypt(Morsezeichen);
				}
				Label.setText(ausgabe + " _Ende.");
				eingabe = "";
				ausgabe = "";
			}
		});
		
		JPanel Panel = new JPanel();
		Panel.add(TextFeld);
		Panel.add(Label);
		Panel.add(Button1);
		Panel.add(Button2);
		
		Fenster.add(Panel);
		Fenster.addWindowListener(new CloseWindowAction());
		Fenster.setVisible(true);
	}
	static void encrypt(char x) {
		for (int i = 0; i < 44; i++) {
			if (x == ' ') {
				ausgabe += " ";
				break;
			}
			else if (x == Alphabet[i]) {
				ausgabe += Morsecode[i] + "I";
			}
		}
	}
	static void decrypt(String x) {
		for (int i = 0; i < 44; i++) {
			if (x.equals(" ")) {
				ausgabe += " I";
				break;
			}
			else if (x.equals(Morsecode[i])) {
				ausgabe += Alphabet[i];
			}
		}
	}
	static void MorseLänge(String y) {
		segments = y.split("I");
		Länge = segments.length;
	}
}
class CloseWindowAction extends WindowAdapter { 
	  public void windowClosing(WindowEvent e) {
		  System.exit(0);
	  }
}
 

Darkslide

Member
@cubic warum from string import * und import string? o_O

Zumal * Imports nie verwendet werden sollten.

@ravensturm

du brauchst len nicht wenn du über die Liste iteretierst. Das ist hässliches C/C++ und nicht gerade "pythonisch"
 

shafire

New member
Code:
#!/usr/bin/env ruby
class MorseCode
  def get_codes input
    codes, codes_temporary, signals, ret = %w(. -), [], %w(. -), {}
    
    3.times {
      codes.each { |x|
        signals.each { |y|
          codes_temporary << x+y
        }
      }
      codes += codes_temporary
      codes, codes_temporary = codes.uniq, []
    }
    
    alphabet = "etianmsurwdkgohvfüläpjbxcyzqö".force_encoding("utf-8").split("") << "ch"
    
    if input == "alphabet"
      alphabet.each_with_index { |v, k| ret[v] = codes[k] }
    else
      alphabet.each_with_index { |v, k| ret[codes[k]] = v }
    end
    
    ret[" "] = " "; ret
  end
  
  def encrypt string
    codes = get_codes("alphabet")
    string.downcase.split("").map { |x| codes[x] }.join(" ")
  end
  
  def decrypt string
    codes, ret = get_codes("morse"), []
    string.split(/ /).map { |x| codes[x] }.each { |x| if !ret.empty? and ret.last == nil and x == nil then next else ret << x end }
    ret.map { |x| x = " " if x.nil?; x }.join
  end
end

p MorseCode.new.encrypt("FREIE ENZYKLOPAEDIE")
p MorseCode.new.decrypt("..-. .-. . .. .   . -. --.. -.-- -.- .-.. --- .--. .- . -.. .. .")
 

olla

New member
Code:
<html>

<head>
<title>Morsecode-Generator 1.0 - Autor: Oliver Altena</title>
<style>
h1
{
	font-face: Arial;
}

b
{
	font-face: Arial;
	font-size: 11px;
}

input
{
	font-face: Arial;
	font-weight:bold;
	font-size:11px;
	border:1px solid black;
}

textarea
{
	width:70%;
	font-face: Arial;
	font-weight:bold;
	font-size:11px;
	border:1px solid black;
}

fieldset
{
	width:70%;
	font-face: Arial;
	font-weight:bold;
	font-size:11px;
	border:1px solid black;
}
</style>
<script>
standardAlph = new 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",
							"ä", "ö", "ü", "ß", ".", ",", "(", ")", "=",
							"1", "2", "3", "4", "5", "6", "7", "8", "9", "0", " ", "\n");		
											
morseAlph = new Array(	".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", 
						".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.",
						"...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", ".-.-",
						"---.", "..--", "...--..", ".-.-.", "--..--", "-.-.-", "-.--.-",
						"-...-", ".----", "..---", "...--", "....-", ".....", "-....",
						"--...", "---..", "----.", "-----", "@", "#");
						
saLen = standardAlph.length;
maLen = morseAlph.length;

function textToCharArray(text)
{
	textLen = text.length;
	charArray = new Array(textLen);
	for(i=0;i<textLen;i++)
	{
		charArray[i] = text.substr(i,1);
	}	
	return charArray;
}

function standardToMorse()
{
	userText = document.form1.in_element.value;
	userText = userText.toLowerCase();
	textArr = textToCharArray(userText);
	textArrLen = textArr.length;
	for(i=0;i<textArrLen;i++)
	{
		for(j=0;j<saLen;j++)
		{
			if(textArr[i] == standardAlph[j])
			{
				document.form1.out_element.value += morseAlph[j]+" ";
			}
		}
	}
}

function morseToStandard()
{
	userText = document.form1.in_element.value;
	wordArr = userText.split(" ");
	waLen = wordArr.length;
	for(i=0;i<waLen;i++)
	{
		for(j=0;j<maLen;j++)
		{
			if(wordArr[i] == morseAlph[j])
			{
				document.form1.out_element.value += standardAlph[j];
			}
		}
	}
}
</script>
</head>

<body>
<center>
<h1>Morsecode-Generator</h1>
	<form name="form1">
		<fieldset>
			<legend><span>Eingabe</span></legend>
				<textarea name="in_element" rows="15"></textarea><br>
				<input type="button" onClick="document.form1.in_element.value='';" value="Löschen"><br><br>
		</fieldset><br><br>
				<input type="button" onClick="standardToMorse()" value="Text -> Morsecode"> 
				<input type="button" onClick="morseToStandard()" value="Morsecode -> Text"> 
				<input type="reset" value="Textfelder löschen"><br><br>
		<fieldset>
			<legend><span>Ausgabe</span></legend>
				<div id='wCanvas'></div>
				<textarea name="out_element" rows="15"></textarea><br>
				<input type="button" onClick="document.form1.out_element.value='';" value="Löschen"><br><br>
		</fieldset>
	</form>
<b>- ©2008 <a href="mailto:oaltena@yahoo.de">Oliver Altena</a> -</b>
</center>
</body>

</html>

Das wäre dann mal meine HTML/JavaScript-Lösung.

Habe das Leerzeichen-Problem einfach durch meine "@"-Erweiterung gelöst ^^

EDIT: Absätze sind nun auch möglich ("\n" -> "#")
 

rami

New member
hier ne php-klasse. rückübersetzung kommt vielleicht noch.
PHP:
<?php
class morsen {
  var $morsealphabet;
  function init(){
      $this->morsealphabet = array(
                       " " => "  /  ",
                       "a" => " ?- ", //Alle Zeichen
                       "b" => " -??? ",
                       "c" => " -?-? ",
                       "d" => " -?? ",
                       "e" => " ? ",
                       "f" => " ??-? ",
                       "g" => " --? ",
                       "h" => " ???? ",
                       "i" => " ?? ",
                       "j" => " ?--- ",
                       "k" => " -?- ",
                       "l" => " ?-?? ",
                       "m" => " -- ",
                       "n" => " -? ",
                       "o" => " --- ",
                       "p" => " ?--? ",
                       "r" => " --?- ",
                       "s" => " ??? ",
                       "t" => " - ",
                       "u" => " ??- ",
                       "v" => " ???- ",
                       "w" => " ?-- ",
                       "x" => " -??- ",
                       "y" => " -?-- ",
                       "z" => " --?? ",
                       "0" => " ----- ",
                       "1" => " ?---- ",
                       "2" => " ??--- ",
                       "3" => " ???-- ",
                       "4" => " ????- ",
                       "5" => " ????? ",
                       "6" => " -???? ",
                       "7" => " --??? ",
                       "8" => " ---?? ",
                       "9" => " ----? ",
                       "ä" => " ?-?- ",
                       "ö" => " ---? ",
                       "ü" => " ??-- ",
                       "." => " ?-?-?- ",
                        "," => " --??-- ",
                       ":" => " ---??? ",
                       "=" => " -???- ",
                       "(" => " -?--? ",
                       ")" => " -?--?- ",
                       "ß" => " ???--? ",
                       "?" => " ??--?? ",
                       "\n" => " \n");           
  }
  function strtomorse ($string){
    $newstring = strtolower($string);
    foreach ($this->morsealphabet as $normal => $morse){
      $newstring = str_replace($normal, " ".$morse."  ", $newstring);
    }
    return $newstring;
  }
  //Rückumwandlung folgt
}
$morse = new morsen;
$morse->init(); //Klasse starten
echo $morse->strtomorse("Hello World");
?>
 

Ook!

New member
Hallo!

Meine Groovy Lösung

Code:
String morse(text){
	codes = ['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':"-----",
	         ' ':" ",
	         '~':"...-...", '^':".-.-." ]
	
	text = text.toLowerCase();
	String result = ""; 
	for(idx=0; idx<text.length(); idx++)
		if(codes[text[idx]] != null)
			result += codes[text[idx]]
		else
			result += "#";
	return result += codes['^'];
}

println morse("Ook") // -------.-.-.-.

Gruß
Felix
 

DMRMcK

New member
Morsecode Übersetzer

Und hier eine Lösung in VB

Code:
Module Module1

    Sub Main()

        Dim Alpha() As String = New 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", "Ä", "Ö", "Ü", "ß", ".", ",", _
                                        "(", ")", "=", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", " "}

        Dim Morse() As String = New String() {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", _
                                        "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", _
                                        "...-", ".--", "-..-", "-.--", "--..", ".-.-", "---.", "..--", "...--..", _
                                        ".-.-.", "--..--", "-.-.-", "-.--.-", "-...-", ".----", "..---", "...--", "....-", _
                                        ".....", "-....", "--...", "---..", "----.", "-----", "@"}

        Console.WriteLine("Text eingeben (bei Morsecode: Trennungszeichen: ""|"", Leerzeichen: ""@""):")
        Console.WriteLine()

        Dim textAlt As String = (Console.ReadLine()).ToUpper
        Dim textNeu As String = ""

        If textAlt.IndexOf("|") = -1 Then
            For i As Integer = 0 To textAlt.Length - 1
                textNeu &= Morse(Array.IndexOf(Alpha, textAlt.Substring(i, 1)))
            Next
        Else
            Dim anzahl As Integer = 0

            For i As Integer = 0 To textAlt.Length - 1
                If textAlt.Substring(i, 1) = "|" Then
                    anzahl += 1
                End If
            Next
            For i As Integer = 0 To anzahl - 1
                textNeu &= Alpha(Array.IndexOf(Morse, textAlt.Substring(0, textAlt.IndexOf("|"))))
                textAlt = textAlt.Substring(textAlt.IndexOf("|") + 1)
            Next
        End If

        Console.WriteLine()
        Console.WriteLine(textNeu)
        Console.ReadLine()

    End Sub

End Module
 

v2.0

Stammuser
Hier wäre dann noch meine Lösung dafür in Java.
Das Programm arbeitet aber nur mit normalen Buchstaben und Zahlen, Sonderzeichen werden ignoriert.

Code:
import javax.swing.JOptionPane;
public class MorseZeichen {
    static String code(String text) {
        char alphabet[] = new char[] { '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 morsecode[] = new String[] { ".- ","-... ","-.-. ","-.. ",". ","..-. ","--. ",".... ",
                    ".. ",".--- ","-.- ",".-.. ","-- ","-. ","--- ",".--. ",
                    "--.- ",".-. ","... ","- ","..- ","...- ",".-- ","-..- ",
                    "-.-- ","--.. ",".---- ","..--- ","...-- ","....- ","..... ",
                    "-.... ","--... ","---.. ","----. ","----- " };
        text = text.toUpperCase();
        
        StringBuffer codedText = new StringBuffer();
        for (int i=0; i<text.length(); i++) {
            for (int j=0; j<alphabet.length; j++) {
                if (text.charAt(i) == alphabet[j]) {
                    codedText.append(morsecode[j] + " ");
                }
            }    
        }
        return codedText.toString();
    }
    public static void main(String[] args) {
        String eingabe = JOptionPane.showInputDialog("Geben Sie einen Text ein: ");
        JOptionPane.showMessageDialog(null,  "Text in Morsecode: " + code(eingabe));
    }
}
 
F

Fluffy

Guest
Nette Übung, vor allem wenn man längere Zeit kein C++ mehr gemacht hat^^.

PHP:
#include<iostream>
#include<string>
#include<map>
#include<list>
#include<ios>
#include<algorithm>
#include<iterator>

std::map<std::string,std::string>* getEncodingMap() {
    std::map<std::string, std::string> *encodeMap = new std::map<std::string, std::string>();

    encodeMap->insert(std::pair<std::string,std::string>("A" , ".-"));
    encodeMap->insert(std::pair<std::string,std::string>("B" , "-..."));
    encodeMap->insert(std::pair<std::string,std::string>("C" , "-.-."));
    encodeMap->insert(std::pair<std::string,std::string>("D" , "-.."));
    encodeMap->insert(std::pair<std::string,std::string>("E" , "."));
    encodeMap->insert(std::pair<std::string,std::string>("F" , "..-."));
    encodeMap->insert(std::pair<std::string,std::string>("G" , "--."));
    encodeMap->insert(std::pair<std::string,std::string>("H" , "...."));
    encodeMap->insert(std::pair<std::string,std::string>("I" , ".."));
    encodeMap->insert(std::pair<std::string,std::string>("J" , ".---"));
    encodeMap->insert(std::pair<std::string,std::string>("K" , "-.-"));
    encodeMap->insert(std::pair<std::string,std::string>("L" , ".-.."));
    encodeMap->insert(std::pair<std::string,std::string>("M" , "--"));
    encodeMap->insert(std::pair<std::string,std::string>("N" , "-."));
    encodeMap->insert(std::pair<std::string,std::string>("O" , "---"));
    encodeMap->insert(std::pair<std::string,std::string>("P" , ".--."));
    encodeMap->insert(std::pair<std::string,std::string>("Q" , "--.-"));
    encodeMap->insert(std::pair<std::string,std::string>("R" , ".-."));
    encodeMap->insert(std::pair<std::string,std::string>("S" , "..."));
    encodeMap->insert(std::pair<std::string,std::string>("T" , "-"));
    encodeMap->insert(std::pair<std::string,std::string>("U" , "..-"));
    encodeMap->insert(std::pair<std::string,std::string>("V" , "...-"));
    encodeMap->insert(std::pair<std::string,std::string>("W" , ".--"));
    encodeMap->insert(std::pair<std::string,std::string>("X" , "-..-"));
    encodeMap->insert(std::pair<std::string,std::string>("Y" , "-.--"));
    encodeMap->insert(std::pair<std::string,std::string>("Z" , "--.."));
    encodeMap->insert(std::pair<std::string,std::string>("Ä" , ".-.-"));
    encodeMap->insert(std::pair<std::string,std::string>("Ö" , "---."));
    encodeMap->insert(std::pair<std::string,std::string>("Ü" , "..--"));
    encodeMap->insert(std::pair<std::string,std::string>("ß" , "...--.."));
    encodeMap->insert(std::pair<std::string,std::string>("." , ".-.-."));
    encodeMap->insert(std::pair<std::string,std::string>(" " , "/"));
    encodeMap->insert(std::pair<std::string,std::string>("," , "--..--"));
    encodeMap->insert(std::pair<std::string,std::string>("(" , "-.-.-"));
    encodeMap->insert(std::pair<std::string,std::string>(")" , "-.--.-"));
    encodeMap->insert(std::pair<std::string,std::string>("=" , "-...-"));
    encodeMap->insert(std::pair<std::string,std::string>("1" , ".----"));
    encodeMap->insert(std::pair<std::string,std::string>("2" , "..---"));
    encodeMap->insert(std::pair<std::string,std::string>("3" , "...--"));
    encodeMap->insert(std::pair<std::string,std::string>("4" , "....-"));
    encodeMap->insert(std::pair<std::string,std::string>("5" , "....."));
    encodeMap->insert(std::pair<std::string,std::string>("6" , "-...."));
    encodeMap->insert(std::pair<std::string,std::string>("7" , "--..."));
    encodeMap->insert(std::pair<std::string,std::string>("8" , "---.."));
    encodeMap->insert(std::pair<std::string,std::string>("9" , "----."));
    encodeMap->insert(std::pair<std::string,std::string>("0" , "-----"));

    return encodeMap;
}

int main(int argc, char** argv) {
    std::map<std::string, std::string>* codeMap = getEncodingMap();
    std::string msg;
    std::list<std::string> encodedMsg;
    std::list<std::string> decodedMsg;
    std::map<std::string, std::string>::iterator it;

    std::cout<<"Type Message"<<std::endl;
    std::getline(std::cin>>std::uppercase,msg);
    std::transform(msg.begin(), msg.end(),msg.begin(), toupper);

    for(std::string::iterator msgIt = msg.begin(); msgIt != msg.end(); msgIt++) {
        it = codeMap->find(std::string(1, *msgIt));
    
        if(it == codeMap->end()) {
            std::cout<<"not found"<<std::endl;
        } else {
            encodedMsg.push_back(it->second);
        }
    }

    for(std::list<std::string>::iterator encIt = encodedMsg.begin(); encIt != encodedMsg.end(); encIt++) {
        for(std::map<std::string, std::string>::iterator codeMapIt = codeMap->begin(); codeMapIt != codeMap->end(); codeMapIt++) {
            if(codeMapIt->second == *encIt) {
                it = codeMapIt;
                break;
            } else {
                it = codeMap->end();
            }
        }

        if(it == codeMap->end()) {
            std::cout<<"not found"<<std::endl;
        } else {
            std::cout<<it->first;
        }
    }

    return 0;
}
PHP:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;

public class MorseCode {
    public static HashMap<String,String> dictEncode = new HashMap(){{
        put("A", ".-");
        put("B", "-...");
        put("C", "-.-.");
        put("D", "-..");
        put("E", ".");
        put("F", "..-.");
        put("G", "--.");
        put("H", "....");
        put("I", "..");
        put("J", ".---");
        put("K", "-.-");
        put("L", ".-..");
        put("M", "--");
        put("N", "-.");
        put("O", "---");
        put("P", ".--.");
        put("Q", "--.-");
        put("R", ".-.");
        put("S", "...");
        put("T", "-");
        put("U", "..-");
        put("V", "...-");
        put("W", ".--");
        put("X", "-..-");
        put("Y", "-.--");
        put("Z", "--..");
        put("Ä", ".-.-");
        put("Ö", "---.");
        put("Ü", "..--");
        put("ß", "...--..");
        put(".", ".-.-.");
        put(" ", "/");
        put(",", "--..--");
        put("(", "-.-.-");
        put(")", "-.--.-");
        put("=", "-...-");
        put("1", ".----");
        put("2", "..---");
        put("3", "...--");
        put("4", "....-");
        put("5", ".....");
        put("6", "-....");
        put("7", "--...");
        put("8", "---..");
        put("9", "----.");
        put("0", "-----");
    }};

    public static HashMap<String,String> dictDecode = new HashMap(){{
        put(".-", "A");
        put("-...", "B");
        put("-.-.", "C");
        put("-..", "D");
        put(".", "E");
        put("..-.", "F");
        put("--.", "G");
        put("....", "H");
        put("..", "I");
        put(".---", "J");
        put("-.-", "K");
        put(".-..", "L");
        put("--", "M");
        put("-.", "N");
        put("---", "O");
        put(".--.", "P");
        put("--.-", "Q");
        put(".-.", "R");
        put("...", "S");
        put("-", "T");
        put("..-", "U");
        put("...-", "V");
        put(".--", "W");
        put("-..-", "X");
        put("-.--", "Y");
        put("--..", "Z");
        put(".-.-", "Ä");
        put("---.", "Ö");
        put("..--", "Ü");
        put("...--..", "ß");
        put(".-.-.", ".");
        put("/", " ");
        put("--..--", ",");
        put("-.-.-", "(");
        put("-.--.-", ")");
        put("-...-", "=");
        put(".----", "1");
        put("..---", "2");
        put("...--", "3");
        put("....-", "4");
        put(".....", "5");
        put("-....", "6");
        put("--...", "7");
        put("---..", "8");
        put("----.", "9");
        put("-----", "0");
    }};

    public static void main(String[] args) {

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            String msg = reader.readLine().toUpperCase().trim();
            StringBuffer encodedString = new StringBuffer(""), decodedString = new StringBuffer("");

            for(int i = 0; i < msg.length(); i++) {
                if(dictEncode.containsKey(Character.toString(msg.charAt(i)))) {
                    encodedString.append(dictEncode.get(Character.toString(msg.charAt(i))) + " ");
                } else {
                    encodedString.append(" _?_ ");
                }
            }

            String[] encodedStringSplit = encodedString.toString().split(" ");

            for(String part: encodedStringSplit) {
                if(dictDecode.containsKey(part)) {

                    decodedString.append(dictDecode.get(part));
                } else {
                    decodedString.append(" _?_ ");
                }
            }

            System.out.println(decodedString);
        } catch(Exception e){
            System.out.println("Whoopsy s.th. went wrong");
        }
    }
}
PHP:
<?php
$map = 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" => "--..",
    "Ä" => ".-.-",
    "Ö" => "---.",
    "Ü" => "..--",
    "ß" => "...--..",
    "." => ".-.-.",
    " " => "/",
    "," => "--..--",
    "(" => "-.-.-",
    ")" => "-.--.-",
    "=" => "-...-",
    "1" => ".----",
    "2" => "..---",
    "3" => "...--",
    "4" => "....-",
    "5" => ".....",
    "6" => "-....",
    "7" => "--...",
    "8" => "---..",
    "9" => "----.",
    "0" => "-----"
);

function substitudeCharacters($input, $map) {
    array_walk($input, function(&$item) use($map){
       $item = array_key_exists($item, $map)? $map[$item]: ' _?_ ';
    });

    return $input;
}
echo "please enter data:" . PHP_EOL;

$morseDecode = implode("", substitudeCharacters(explode(" ", implode(" ", substitudeCharacters(str_split(strtoupper(trim(fgets(STDIN))), 1), $map))), array_flip($map)));

echo $morseDecode;

PHP:
map = {
    "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": "-----"
}
print("Bitte geben sie Text ein:")
print(''.join([{value:key for key, value in map.items()}.get(x, ' _?_ ') for x in ' '.join([map.get(x, ' _?_ ') for x in input().upper()]).split(' ')]))
 

psittacus

Stammuser
Vielleicht nicht unbedingt schön, aber es funktioniert:
Meine C++ Version
Code:
#include <iostream>
#include <vector>
#include <string>

using namespace std;

string alphabet[26] = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
string umlaut [4] = {".-.-","---.","..--","...--.."};
string puncchar [5] = {".-.-.","--..--","-.-.-","-.--.-","-...-"};
string number [10] = {".----","..---","...--","....-",".....","-....","--...","---..","----.","-----"};

string normAlphabet[26] = {"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"};
string normUmlaut [4]   = {"Ä","Ö","Ü","ß"};
string normPuncchar [5] = {".",",","(",")","="};
string normNumber [10] = {"1","2","3","4","5","6","7","8","9","0"};

int main(int argc, char const *argv[])
{
    string sentence;
    string newSentence = "";


    cout << "Please enter a Sentence: ";
    getline(cin, sentence);


    for (int i = 0; i < sentence.length(); i++) {
        string tempSentence = "";
        tempSentence += sentence[i];
        //cout << tempSentence;
            for (int j = 0; j < 26; j++) {
                if(tempSentence == normAlphabet[j]){
                    newSentence = newSentence + " | " +alphabet[j];
                }
            }
            for(int j = 0; j < 4; j++) {
                if(tempSentence == normUmlaut[j]){
                    newSentence = newSentence + umlaut[j];
                }
            }
            for(int j = 0; j < 4; j++) {
                if(tempSentence == normPuncchar[j]){
                    newSentence = newSentence + puncchar[j];
                }
            }
            for(int j = 0; j < 4; j++) {
                if(tempSentence == normNumber[j]){
                    newSentence = newSentence + number[j];
                }
            }
    }

    cout << "\n\nYour sentence: " << newSentence << " |"<< endl;
    return 0;
}
 

elite-noob

New member
Wahrscheinlich auch nicht die Effizienteste Lösung (ich lasse mir gerne sagen, wie es besser gegangen wäre).Aber hier eine Mögliche Lösung in Powershell
Code:
#################################################### Morsecode Translator by Christian Z.      ###### Scripted on 19.09.2018                    #######################################################Clear Screen from old outputClear-Host###Welcome MessageWrite-Host "Willkommen beim Morsecode Übersetzer. Bitte geben Sie ihren Text ein."Write-Host "Sollten Sie ihren Text als Morsecode eingeben, bitte nach jedem Fertigen Zeichen ein Leerzeichen setzen."Write-Host "Also für A zum Beispiel '.- ' vielen Dank."$TranslateIt = (Read-Host "Was soll übersetzt werden?")function Translation ($Translate)  {    $Morse = $false    ### Prüfen ob Morsecode oder Text    IF (($Translate -like ".*") -OR ($Translate -like "-*"))      {        $Morse = $true      }    IF ($Morse -eq $true)      {        Write-Host ""        foreach ($Letter in $TranslateIt.Split(" "))          {            switch ($Letter)               {                ".-" { Write-Host -NoNewline "a" }                "-..." { Write-Host -NoNewline "b"}                "-.-." { Write-Host -NoNewline "c"}                "-.." { Write-Host -NoNewline "d"}                "." { Write-Host -NoNewline "e"}                "..-." { Write-Host -NoNewline "f"}                "--." { Write-Host -NoNewline "g"}                "...." { Write-Host -NoNewline "h" }                ".." { Write-Host -NoNewline "i" }                ".---" { Write-Host -NoNewline "j" }                "-.-" { Write-Host -NoNewline "k" }                ".-.." { Write-Host -NoNewline "l" }                "--" { Write-Host -NoNewline "m" }                "-." { Write-Host -NoNewline "n" }                "---" { Write-Host -NoNewline "o" }                ".--." { Write-Host -NoNewline "p" }                "--.-" { Write-Host -NoNewline "q" }                ".-." { Write-Host -NoNewline "r" }                "..." { Write-Host -NoNewline "s" }                "-" { Write-Host -NoNewline "t" }                "..-" { Write-Host -NoNewline "u" }                "...-" { Write-Host -NoNewline "v" }                ".--" { Write-Host -NoNewline "w" }                "-..-" { Write-Host -NoNewline "x" }                "-.--" { Write-Host -NoNewline "y" }                "--.." { Write-Host -NoNewline "z" }                ".-.-" { Write-Host -NoNewline "ä" }                "---." { Write-Host -NoNewline "ö" }                "..--" { Write-Host -NoNewline "ü" }                "...--.." { Write-Host -NoNewline "ß" }                ".-.-." { Write-Host -NoNewline "." }                "--..--" { Write-Host -NoNewline "," }                "-.-.-" { Write-Host -NoNewline "(" }                "-.--.-" { Write-Host -NoNewline ")" }                "-...-" { Write-Host -NoNewline "=" }                ".----" { Write-Host -NoNewline "1" }                "..---" { Write-Host -NoNewline "2" }                "...--" { Write-Host -NoNewline "3" }                "....-" { Write-Host -NoNewline "4" }                "....." { Write-Host -NoNewline "5" }                "-...." { Write-Host -NoNewline "6" }                "--..." { Write-Host -NoNewline "7" }                "---.." { Write-Host -NoNewline "8" }                "----." { Write-Host -NoNewline "9" }                "-----" { Write-Host -NoNewline "0" }                "...-..." { Write-Host -NoNewline "roger" }                ".-.-." { Write-Host -NoNewline "finish" }                default {}              }          }      }    IF ($Morse -eq $false)      {        Write-Host ""        foreach ($Letter in $TranslateIt.ToCharArray())          {            switch ($Letter)               {                "a" { Write-Host -NoNewline ".- "}                "b" { Write-Host -NoNewline "-... " }                "c" { Write-Host -NoNewline "-.-. " }                "d" { Write-Host -NoNewline "-.. " }                "e" { Write-Host -NoNewline ". " }                "f" { Write-Host -NoNewline "..-. " }                "g" { Write-Host -NoNewline "--. " }                "h" { Write-Host -NoNewline ".... " }                "i" { Write-Host -NoNewline ".. " }                "j" { Write-Host -NoNewline ".--- " }                "k" { Write-Host -NoNewline "-.- " }                "l" { Write-Host -NoNewline ".-.. " }                "m" { Write-Host -NoNewline "-- " }                "n" { Write-Host -NoNewline "-. " }                "o" { Write-Host -NoNewline "--- " }                "p" { Write-Host -NoNewline ".--. " }                "q" { Write-Host -NoNewline "--.- " }                "r" { Write-Host -NoNewline ".-. " }                "s" { Write-Host -NoNewline "... " }                "t" { Write-Host -NoNewline "- " }                "u" { Write-Host -NoNewline "..- " }                "v" { Write-Host -NoNewline "...- " }                "w" { Write-Host -NoNewline ".-- " }                "x" { Write-Host -NoNewline "-..- " }                "y" { Write-Host -NoNewline "-.-- " }                "z" { Write-Host -NoNewline "--.. " }                "ä" { Write-Host -NoNewline ".-.- " }                "ö" { Write-Host -NoNewline "---. " }                "ü" { Write-Host -NoNewline "..-- " }                "ß" { Write-Host -NoNewline "...--.. " }                "." { Write-Host -NoNewline ".-.-. " }                "," { Write-Host -NoNewline "--..-- " }                "(" { Write-Host -NoNewline "-.-.- " }                ")" { Write-Host -NoNewline "-.--.- " }                "=" { Write-Host -NoNewline "-...- " }                "1" { Write-Host -NoNewline ".---- " }                "2" { Write-Host -NoNewline "..--- " }                "3" { Write-Host -NoNewline "...-- " }                "4" { Write-Host -NoNewline "....- " }                "5" { Write-Host -NoNewline "..... " }                "6" { Write-Host -NoNewline "-.... " }                "7" { Write-Host -NoNewline "--... " }                "8" { Write-Host -NoNewline "---.. " }                "9" { Write-Host -NoNewline "----. " }                "0" { Write-Host -NoNewline "----- " }                "roger" { Write-Host -NoNewline "...-... " }                "finish" { Write-Host -NoNewline ".-.-. " }                default {}              }          }      }      }Translation $TranslateIt
So, jetzt ein paar mal versucht, aber irgendwie zerhackt er mir das ganze wenn ich es in Code Tags mache und macht nen Einzeiler draus :-(
 
Zuletzt bearbeitet:
Oben