Golang
Golang

 

 

Introduction

Morse code is a method of encoding text characters as sequences of dots and dashes (or short and long signals). It has historically been used for telecommunication and remains popular for educational and recreational purposes. This program demonstrates how to translate text to Morse code and vice versa using the Go programming language.

Objective

The goal of this program is to take user input as either plain text or Morse code and provide a translation to the other format. This program will help users understand the basics of Morse code and how to programmatically handle text encoding and decoding.

Code

        package main

        import (
            "bufio"
            "fmt"
            "os"
            "strings"
        )

        var morseCodeMap = map[string]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": "-----", " ": "/",
        }

        var reverseMorseCodeMap = func() map[string]string {
            revMap := make(map[string]string)
            for key, value := range morseCodeMap {
                revMap[value] = key
            }
            return revMap
        }()

        func textToMorse(text string) string {
            text = strings.ToUpper(text)
            var morse []string
            for _, char := range text {
                if code, exists := morseCodeMap[string(char)]; exists {
                    morse = append(morse, code)
                } else {
                    morse = append(morse, "?") // Unknown character
                }
            }
            return strings.Join(morse, " ")
        }

        func morseToText(morse string) string {
            var text []string
            for _, code := range strings.Split(morse, " ") {
                if char, exists := reverseMorseCodeMap[code]; exists {
                    text = append(text, char)
                } else {
                    text = append(text, "?") // Unknown Morse code
                }
            }
            return strings.Join(text, "")
        }

        func main() {
            reader := bufio.NewReader(os.Stdin)

            fmt.Println("Morse Code Translator")
            fmt.Println("Choose an option:")
            fmt.Println("1. Text to Morse Code")
            fmt.Println("2. Morse Code to Text")

            fmt.Print("Enter your choice: ")
            choice, _ := reader.ReadString('\n')
            choice = strings.TrimSpace(choice)

            switch choice {
            case "1":
                fmt.Print("Enter text to translate to Morse code: ")
                text, _ := reader.ReadString('\n')
                text = strings.TrimSpace(text)
                fmt.Println("Morse Code:", textToMorse(text))

            case "2":
                fmt.Print("Enter Morse code to translate to text: ")
                morse, _ := reader.ReadString('\n')
                morse = strings.TrimSpace(morse)
                fmt.Println("Text:", morseToText(morse))

            default:
                fmt.Println("Invalid choice. Please run the program again.")
            }
        }

Explanation

This program is structured as follows:

  1. Morse Code Maps: Two maps are used: one for encoding text to Morse code and another for decoding Morse code to text. The reverse map is generated programmatically.
  2. Translation Functions: The textToMorse function translates text to Morse code, and the morseToText function translates Morse code back to text.
  3. User Input: The program takes user input to determine whether to encode or decode and then processes the input accordingly.
  4. Error Handling: Unknown characters or Morse codes are replaced with a ? to indicate invalid input.

How to Run

  1. Install Go from the official Go website.
  2. Copy the code into a file named morse_translator.go.
  3. Run the program using the command:
                    go run morse_translator.go
    
  4. Follow the on-screen prompts to translate text to and from Morse code.
© 2024 Learn Programming. All rights reserved.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)