Link to home
Create AccountLog in
Avatar of December2000
December2000

asked on

C++ Functionality

Hi Experts,

Just wondering.... What functionality could I add to my code to make it more "sophisticated" or “upgrade it”?

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

// Prototypes
string toMorse(char);

// Global data. Each valid character and its equivalent
// morse code are stored in the parallel arrays.
const int NUM_CHARS = 40;
char regular[NUM_CHARS] = { ' ', ',', '.', '?', '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' 
                          };

string morse[NUM_CHARS] = { " ", "--..--" , ".-.-.-" , "..--.." ,
                            "-----", ".----", "..---", "...--",
                            "....-", ".....", "-....", "--...",
                            "---..", "----.", ".-", "-...",
                            "-.-.", "-..", ".", "..-.",
                            "--.", "....", "..", ".---",
                            "-.-", ".-..", "--", "-.",
                            "---", ".--.", "--.-", ".-.",
                            "...", "-", "..-", "...-",
                            ".--", "-..-", "-.--", "--.."
                          };

int main()
{
    string str;        // To hold the user's input

    // Get a word from the user.
    cout << "Enter a word and I will translate it to Morse code.\n";
    cout << "-> ";
    getline(cin, str);

    // Translate each character and display it.
    int index = 0;
    while (index < str.size())
    {
        cout << toMorse(toupper(str[index])) << endl;
        index++;
    }
	cin.get();
    return 0;
	
}

// The toMorse function accepts a char argument and
// returns a string containing the morse code
// for that character.

string toMorse(char ch)
{
    // Find the character in the array.
    int index = 0;
    while (index < NUM_CHARS && ch != regular[index])
    {
        index++;
    }

    string morseValue;  // To hold the morse code

    if (index >= NUM_CHARS)
        morseValue = "UNDEFINED";  // ch was not found
    else
        morseValue = morse[index]; // Get the morse code
		
    return morseValue;

}

Open in new window

SOLUTION
Avatar of evilrix
evilrix
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Hi December2000,

in addition I would suggest to implement a better kind of mapping to improve performance of toMorse. You could add a map which maps a string to a single character so you don't need to iterate through the regular array for every passed character.

You could do it somehow like this (untested) sample:
#include <map>
...
std::map< char, std::string > morseMap;
void InitMap()
{
 for ( int i = 0; i < NUM_CHARS; i++ )
 {
  morseMap[regular[i]] = morse[i];
 }
}
...
int main()
{
 InitMap();
 ...
}
...
string toMorse(char ch)
{
 std::map< char, std::string >::iterator it = morseMap.find( ch );
 if ( it == morseMap.end() )
 {
  return "UNDEFINED";
 }
 return it->second;
}

Open in new window

Hope that helps,

ZOPPO
Hey Zoppo. I'm just thinking, given the universe size of an array based on a char is going to be  <=255 doesn't a vector (or string, as used here) make more sense? The look up for a vector will have a O(1) time complexity vs. the O(log n) of a map. Just an observation.
Yes, I agree, using an array/vector would be even faster if the character to search for is equal to the array entry's index ... IMO that's a good idea.
Avatar of December2000
December2000

ASKER

Thanks @Zoppo and  @evilrix, What is an example of how I would use array/vector?
Hm - starting from the original code you could do it somehow like this:
std::string arr[255];

void Init()
{
 for ( int i = 0; i < NUM_CHARS; i++ )
 {
  arr[regalar[i]] = morse[i];
 }
}
...
string toMorse(char ch)
{
 std::string ret = arr[ch];
 if ( false != ret.empty() )
 {
  return "UNDEFINED";
 }
 return ret;
}

Open in new window

ZOPPO
Hm - maybe that can produce errors, I think you should change the occurances of char to unsigned char.
How would we write the else clause to return the results, with the if clause being ( false != ret.empty() )?  It wil always default to undefined, no?
SOLUTION
Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
And any time the array returned an empty sting, you would know the character was invalid.
>> How would we write the else clause to return the results
Hm? There's no need for an else clause:

In case the string is empty ret.empty() returns true so we return "UNDEFINED" in the if's execution block.

If it's not empty the ret.empty() returns false so the program continues after the if's execution block.

ZOPPO
@Zoppo ----- Thank you,

When I run the modified code comes back undefined :( .... see below

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

// Prototypes
string toMorse(char);

// Global data. Each valid character and its equivalent
// morse code are stored in the parallel arrays.
const int NUM_CHARS = 40;
char regular[NUM_CHARS] = { ' ', ',', '.', '?', '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' 
                          };

string morse[NUM_CHARS] = { " ", "--..--" , ".-.-.-" , "..--.." ,
                            "-----", ".----", "..---", "...--",
                            "....-", ".....", "-....", "--...",
                            "---..", "----.", ".-", "-...",
                            "-.-.", "-..", ".", "..-.",
                            "--.", "....", "..", ".---",
                            "-.-", ".-..", "--", "-.",
                            "---", ".--.", "--.-", ".-.",
                            "...", "-", "..-", "...-",
                            ".--", "-..-", "-.--", "--.."
                          };

int main()
{
    string str;        // To hold the user's input

    // Get a word from the user.
    cout << "Enter a word and I will translate it to Morse code.\n";
    cout << "-> ";
    getline(cin, str);

    // Translate each character and display it.
    int index = 0;
    while (index < str.size())
    {
        cout << toMorse(toupper(str[index])) << endl;
        index++;
    }

	cin.get();
    return 0;
	
}

// The toMorse function accepts a char argument and
// returns a string containing the morse code
// for that character.

std::string arr[255];

void Init()
{
 for ( int i = 0; i < NUM_CHARS; i++ )
 {
  arr[regular[i]] = morse[i];
 }
}

string toMorse(char ch)
{
 std::string ret = arr[ch];
 if ( true != ret.empty() )
 {
  return "UNDEFINED";
 }
 return ret;
} 

Open in new window

SOLUTION
Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
ASKER CERTIFIED SOLUTION
Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
Thank You! I learned so much from all of you! Cool stuff... geek it!