Yes this is homework but I have spent a few hours trying to figure it out. So right now I am doing a project in which you convert plain text into morse code, I was able to do so and it was relatively easy. However, now I need to convert the morse code back into text and I've run into a roadblock. I am not sure if I should make a new dictionary and reverse the text and char or if I should just reverse the existing dictionary that I have already made. Also we're not allowed to use if or case statements which makes it a bit harder but not by too much. Here is what I have so far:
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Morse_Code_Converter
{
public partial class Form1 : Form
{
private Dictionary<char, String> morse = new Dictionary<char, String>()
{
{' ', " /" },{',', " --..--" }, {'.', " .-.-.-" }, {'?'," ..--.."},{'0'," -----"},{'1', " .----"},
{'2'," ..---"},{'3'," ...--"},{'4'," ....-"},{'5'," ....."},{'6'," -...."},{'7'," --..."},{'8'," ---.."},
{'9'," ----." },{'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'," --.."}
};
public Form1()
{
InitializeComponent();
}
private void convertToMorseButton_Click(object sender, EventArgs e)
{
string input = morseTextBox.Text;
var sb = new StringBuilder();
for (int index = 0; index < input.Length; index++)
{
var t = input[index];
input = input.ToLower();
string morseValue;
morse.TryGetValue(t, out morseValue);
sb.Append(morseValue);
}
textToMorseLabel.Text = sb.ToString();
}
private void morseToTextButton_Click(object sender, EventArgs e)
{
//This is where I want to convert
}
private void exitButton_Click(object sender, EventArgs e)
{
this.Close();
}
private void clearButton_Click(object sender, EventArgs e)
{
morseTextBox.Text = "";
}
private void morseClearButton_Click(object sender, EventArgs e)
{
textBox.Text = "";
}
}
}
If someone can help guide me in the right direction that would greatly appreciated.
Since this is a school project, I don't give you the code, but I will try to explain, how you can do it.
I suppose morse codes (in input) are separated by a space, so first use
String.Split(' ')to get astring[]each with a morsecode string.I also assume, that you're not familiar with 'Linq' (yet) - or are not allowed to use it, so now you iterate (with a
forloop) through this array, then use aforloop to find the item inmorsesDictionary that has thevalueequal to this morsecode and return thekey.Using this method you don't need an extra dictionary. However, if this was real code, you should create a reverse
Dictionary, which is faster than this approach.