Pistrie

Pistrie

How do I check whether a string only consists of characters that are keys inside a map?

I’m creating a piece of code that translates a string into Morse code, but I need to check whether the string can be translated into Morse code at all. I’ve got a map that has all the translations, so I figured the most optimal way would be to check whether all the characters in the string appear in this map. Would it somehow be possible to turn this into a regex so I can simply use String.match?/2?

@morse_dict %{
  "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" => "----.",
  "." => ".-.-.-",
  "," => "--..--",
  "?" => "..--..",
  "'" => ".----.",
  "!" => "-.-.--",
  "/" => "-..-.",
  "(" => "-.--.",
  ")" => "-.--.-",
  "&" => ".-...",
  ":" => "---...",
  ";" => "-.-.-.",
  "=" => "-...-",
  "+" => ".-.-.",
  "-" => "-....-",
  "_" => "..--.-",
  "\"" => ".-..-.",
  "$" => "...-..-",
  "@" => ".--.-.",
  " " => "/"
}

Thanks :slight_smile:

Marked As Solved

JohnnyCurran

JohnnyCurran

You can do it in 3 lines. Split, map, then join

defmodule MorseCode do
  @morse_dict %{
    "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 translate(string) when is_binary(string) do
    characters = String.split(string, "", trim: true)
    maybe_morse = for c <- characters, do: @morse_dict[c]
    if Enum.all?(maybe_morse), do: IO.puts(Enum.join(maybe_morse)), else: IO.puts("Could not translate #{string} to morse code")
  end
end

MorseCode.translate("THIS IS VALID MORSE CODE")
MorseCode.translate("THIS IS <INVALID> MORSE CODE")

Outputs:

-........./...../...-.-.-....-../-----.-...../-.-.----...
Could not translate THIS IS <INVALID> MORSE CODE to morse code

Also Liked

adamu

adamu

I’m not sure if there’s a way to create the regex automatically, but here’s a handwritten one. This is faster than all the versions I could think of (including JonnyCurran’s above) that actually translate the message:

def valid?(str), do: str =~ ~r/^[\w.,?'!\/()&:;=+_\\$@ -]+$/

Here’s a version that does it by generating function clauses from the map at compile-time, and uses binary pattern matching, which is faster than the regex:

for char <- Map.keys(@morse_dict) do
  defp valid_char?(unquote(char)), do: true
end

defp valid_char?(_), do: false

def valid?(<<char::binary-1>>), do: valid_char?(char)
def valid?(<<char::binary-1, rest::binary>>), do: valid_char?(char) and valid?(rest)

Where Next?

Popular in Questions Top

dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
New
LegitStack
I’m hoping you guys can give me some general advice and perhaps code examples if you’re feeling up to it. I’m very interested in Elixir,...
New
New
dokuzbir
Hello, I am trying to convert my lists to string without losing brackets.For start i have 3 map. They look like these buyer = %{ id: ...
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New

Other popular topics Top

lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New

We're in Beta

About us Mission Statement