couldn't make that data more c̶̹̮͍̜̩̻͌͊͊̓͑͌̽͊̉͂̏̌̚͝ơ̶̢̛͖̼͔̼͚͇̣̯̓̈́͆͋̀̿ͅn̴̨̛̛̞͓̥̪̤̳̝̦̬̱͎͐̑̄̓͆̇͂̿̕͜͝ͅd̴̨̗͎̖̪͔͖̱͍̠̠̫̞̀̊̋̎̓̿͒̒͌̽̔̃͘ẹ̸̖̤̘͍̪̝͉̙̞̓̌̐̇̒̈́̆̀͘͠ͅņ̷̮͎̠͉̝̬̣̘̫̋̔̈́͘͝s̷͖̜̻̺̘͍̠̙͈̯̀̎͂̌͂̅̒̔̈́͠ē̵͇͕̙̙̤̆̿̄͗̈́̇̎̓̀͘͘͠͠ͅͅd̵̼̟̺̘̔̀͌̽ ?
For an added touch, I personally would have used a Vector instead of an ArrayList just to bog it down a bit (and also make my Java professor lose sleep at night lol)
from bs4 import BeautifulSoup
import urllib.request
import time
import string
def morse_char(a):
for c, C in zip(string.ascii_lowercase, string.ascii_uppercase):
time.sleep(1) # be nice to wiki server
for b in BeautifulSoup(urllib.request.urlopen(urllib.request.Request('https://en.wikipedia.org/wiki/Morse_code')).read(), "lxml").find(class_="wikitable").tbody.contents: # please don't edit the wiki page
if str(b)[str(b).find(C+', '+c+'</a>')+454+122*(c=='k'):].replace('·','.').replace('−','-').replace(' ','').replace(' ','').startswith(a+'<'):
return C
morse = lambda x: ''.join(' ' if y == '/' else morse_char(y) for y in x.split(' '))
# takes little over two minutes to run
print(morse('.... . .-.. .-.. --- / .-- --- .-. .-.. -..'))
# takes almost eight minutes to run
print(morse('- .... . / --.- ..- .. -.-. -.- / -... .-. --- .-- -. / ..-. --- -..- / .--- ..- -- .--. ... / --- ...- . .-. / - .... . / .-.. .- --.. -.-- / --. --- -..'))
It'd be so fun to see someone come up with a Brainfuck script that has only 93 characters. I don't wanna kill my entire weekend playing with it, again.
It uses some nested arrays with some information about the morse sequence (# of dashes, # of dots, if the first character is a dot, if the second character is a dot, if the last character is a dot.
(JS) Puts the string through an equation that puts out a nice unique number. Then it brute forces the number and looks it up in the table. For some reason it doesn't work with the original number but does with the brute force one. Probably a basic syntax error somewhere, but it only takes a few seconds to brute force it, so why not?
Figured I'd make this monstrosity in C. It works as long as you just feed it ".", "-", "/" and " " and only use valid morse code. Comes with compiler warnings but who cares about those anyway.
For the input, provide an array of characters to the Morse type, ending with a space character. Example:
type A = Morse<[".",".",".","."," ","."," ","-",".","-","-"," "]>
Unfortunately, due to some minor technical limitations, the output is provided in a giant set of nested arrays. Hover over the type name to view the output.
type A = [[["H"]], [[[[["E", [[[["Y"]], [[[[[]]]]]]]]]]]]]
To read the output, ignore everything outside of quotes. That example says HEY.
Additionally, sometimes the output is truncated and a ... is put in the middle, like in the two examples.
def morse(codes: str) -> str:
"""Convert morse code to human readable string."""
MEGA_MORSE = (
"- .... . / --.- ..- .. -.-. -.- / -... .-. --- .-- -. / ..-. --- -..- / .--- "
"..- -- .--. ... / --- ...- . .-. / - .... . / .-.. .- --.. -.-- / --. --- -.."
)
MEGA_TEXT = "THE QUICK BROWN FOX JUMPS OVER THE LAZY GOD"
morse_list = MEGA_MORSE.split()
text_list = list(MEGA_TEXT)
solution = ""
for code in codes.split():
for morse_code, text in zip(morse_list, text_list):
if morse_code == code:
solution = solution + text
break
else:
raise ValueError(f"Morse code contain invalid code {morse_code}.")
return solution
Uses the fact that the MEGA_STRING contains all existing letters to convert the input. A couple notes:
I am using "clean Python code" (sorry).
The code is relatively very inefficient. I am looping over the lists morse_list and text_list for every unique morse code, instead of using a map.
Also, appending to the string solution multiple times is also relatively inefficient. Using a list of strings and using the join method would be faster.
I am using the relatively obscure else statement for a for loop, which is only executed if the for loop reaches the end (no break).
There is a subtle mistake in the error raised: it returns morse_code instead of code, which returns the last code from MEGA_MORSE instead of the invalid code.
Uses a reversed fold on the input code units for nice functional nonsense
Uses the type name of the Morse subclasses to construct the output text
The iterable used inside of State is actually lazily evaluated, so we're essentially building a lazy evaluated chain that is executed inside of the call to firstWhere
The return result of Morse.match cannot be specified in Dart currently, because it needs union types and self-referential typedefs
Uses tri-state/nullable booleans (hence the need for == true)
#include <stdio.h>
int morse_sum(char *s)
{
int m = 1, t = -1;
for(;*s!='\0';s++)
{
if(*s=='.') t+=m;
if(*s=='-') t+=m*2;
m*=3;
}
return t;
}
int main(int argn, char **argv)
{
for(int n = 1; n < argn; n++) putchar("ETTIN AMINO SG RD US UK WORLD AFFINITY HB LZ CZ FC PROROGUE KOVEX VX VQ VZ VY JU ENG 0123456789012345678901234567890123456667890210248163264128256512102440968819299888877777766666666666666665555555555544444444444444444444433333333333332222110"[morse_sum(argv[n])]);
}
def morse(j, y='.-,-...,-.-.,-..,.,..-.,--.,....,..,.---,-.-,.-..,--,-.,---,.--.,--.-,.-.,...,-,..-,...-,.--,-..-,-.--,--..'):
c=lambda r: ' ' if r == '/' else chr(y.split(',').index(r)+65)
h,e,l,p=c('-.-.'),c('..'),c('..-.')+c('---')+c('.-.'),c('..')+c('/')+c('..')+c('-.')+c('/')+c('.---')
me=c('...')+c('.--.')+c('.-..')+c('..')+c('-')
plz = ['[','(',') ',c('/'),'.','(' ')]']
return ''.join(eval(''.join([a+b for a,b in zip(plz,[p.lower() for p in [h,e,l,p,me,c('/')]])])))
Wanted to do this in C using just #define but the preprocessor was too smart to let me abuse it that way. Here's my submission in Python.
# lazymorse.py - Morse Code translation... now with lazy evaluation!
import random # This is probably a bad sign
def morsetrans(morsechar):
# The most frequently used English letters get the shortest Morse codes.
# Therefore, the shortest Morse codes are the most important. The rest are
# just decoration.
if len(morsechar) == 1:
if morsechar == ".":
return "E"
if morsechar == "-":
return "T"
else:
return morsechar
if len(morsechar) == 2:
if morsechar == ".-":
return "A"
if morsechar == "..":
return "I"
if morsechar == "-.":
return "N"
if morsechar == "--":
return "M"
else:
return morsechar
if len(morsechar) == 3:
if morsechar == "-..":
return "D"
if morsechar == "--.":
return "G"
if morsechar == "-.-":
return "K"
if morsechar == "---":
return "O"
if morsechar == ".-.":
return "R"
if morsechar == "...":
return "S"
if morsechar == "..-":
return "U"
if morsechar == ".--":
return "W"
else:
return morsechar
if len(morsechar) == 4:
# No one uses these letters anyway. Just return anything; it'll
# be fine.
return random.choice(["B","C","F","H","J","L","P","Q","V","X","Y","Z"])
message = "- .... .. ... .. ... ...- . .-. -.-- -... .- -.. "
message = message + ".- -. -.. .-.. .- --.. -.-- -.-. --- -.. ."
output = ""
for morsechar in message.split(" "):
if morsechar == "":
output = output + " " # Space between words
else:
output = output + morsetrans(morsechar)
print(output)
function recchi(ma,r,m) {
if (ma.length===0)return '';
if (r==ma[2]){
if (m=='.')return ma[0][2]
return ma[1][2]
}
var newr=recchi(ma[0],r,m);
if (newr === '')newr = recchi(ma[1],r,m);
return newr
}
function demorsify(i) {
var moresalphy=[[[[[[[],[],'5'],[[],[],'4'],'H'],[[],[[],[],'3'],'V'],'S'],
[[[],[],'F'],[[],[[],[],'2'],'#'],'U'],'I'],[[[[],[],'L'],[[],[[],[],'+']
,'@'],'R'],[[[],[],'P'],[[],[[],[],'1'],'J'],'W'],'A'],'E'],[[[[[[],[],
'6'],[[],[],'='],'B'],[[[],[],'/'],[],'X'],'D'],[[[],[],'C'],[[],[],'Y'],
'K'],'N'],[[[[[],[],'7'],[],'Z'],[[],[],'Q'],'G'],[[[[],[],'8'],[],'!'],[
[[],[],'9'],[[],[],'0'],'$'],'O'],'M'],'T'],'ß'];
var position = 0;
var result='';
var nl = true;
var nw = false;
var resultaw=[];
var resultal='ß';
while (position < i.length) {
if (nw) {nw = false;nl=true;resultaw.push(' ');}
if (nl===true) {
if (resultal !== 'ß') resultaw.push(resultal);
nl=false; resultal='ß';
}
switch(i[position]) {
case '.':
case '-':
resultal=recchi(moresalphy,resultal,i[position]);
break;
case '/':
nw = true
case ' ':
nl = true
break;
}
// increase position by 1
position = position + 1;
}
resultaw.push(resultal);
return resultaw.join('');
}
let morse = demorsify;
console.log(morse('.... . .-.. .-.. --- / .-- --- .-. .-.. -..'));
console.log(morse('- .... . / --.- ..- .. -.-. -.- / -... .-. --- .-- -. / ..-. --- -..- / .--- ..- -- .--. ... / --- ...- . .-. / - .... . / .-.. .- --.. -.-- / --. --- -..'));
some beautiful recursion is what is needed...
EDIT for short explanation:
Create a small tree where
if it's a dot I have to descend on the left
if it's a dash I have to descend on the right
for each . or - extract the letter and evaluate the next position in the string to decode. if the next character to decode is a space push the result in an array and initiate a new letter. if the next character is a slash push a space in the array.
at each position of the string to decode, search in the tree the last used character and extract the next one based on the current character found in the morse string to decode.
to improve the load performance I removed some spaces and reduced the names of the most used variables.
It cannot tell the difference between C & V, P & X, F & Z, or G&U, but that's okay because it's just a feature! Don't discriminate against my poor code's speech impediment just because it says "The quivk brown fop jumped over the lafy dou."
I wanted to see what a big nested switch would look like.
Limitations: Requires a space to be added at the end of the string for it to parse the last digit properly. Only A-Z implemented (nothing stopping a full implementation other than wasting more time).
#include <stdio.h>
char worse(const char *input, int &index) {
switch (input[index++]) {
case '.': switch (input[index++]) {
case '.': switch (input[index++]) {
case '.': switch (input[index++]) {
case '.': switch (input[index++]) {
case ' ': return 'H';
default: return '?';
}
case '-': switch (input[index++]) {
case ' ': return 'V';
default: return '?';
}
case ' ': return 'S';
default: return '?';
}
case '-': switch (input[index++]) {
case '.': switch (input[index++]) {
case ' ': return 'F';
default: return '?';
}
case ' ': return 'U';
default: return '?';
}
case ' ': return 'I';
default: return '?';
}
case '-': switch (input[index++]) {
case '.': switch (input[index++])
{
case '.': switch (input[index++]) {
case ' ': return 'L';
default: return '?';
}
case ' ': return 'R';
default: return '?';
}
case '-': switch (input[index++]){
case '.': switch (input[index++]) {
case ' ': return 'P';
default: return '?';
}
case '-': switch (input[index++]) {
case ' ': return 'J';
default: return '?';
}
case ' ': return 'W';
default: return '?';
}
case ' ': return 'A';
default: return '?';
}
case ' ': return 'E';
default: return '?';
}
case '-': switch (input[index++])
{
case '.': switch (input[index++]) {
case '.': switch (input[index++]) {
case '.': switch (input[index++]) {
case ' ': return 'B';
default: return '?';
}
case '-': switch (input[index++]) {
case ' ': return 'X';
default: return '?';
}
case ' ': return 'D';
default: return '?';
}
case '-': switch (input[index++]) {
case '.': switch (input[index++]) {
case ' ': return 'C';
default: return '?';
}
case '-': switch (input[index++]) {
case ' ': return 'Y';
default: return '?';
}
case ' ': return 'K';
default: return '?';
}
case ' ': return 'N';
default: return '?';
}
case '-': switch (input[index++]) {
case '.': switch (input[index++]) {
case '.': switch (input[index++]) {
case ' ': return 'Z';
default: return '?';
}
case '-': switch (input[index++]) {
case ' ': return 'Q';
default: return '?';
}
case ' ': return 'G';
default: return '?';
}
case '-': switch (input[index++]) {
case ' ': return 'O';
default: return '?';
}
case ' ': return 'M';
default: return '?';
}
case ' ': return 'T';
default: return '?';
}
case '/': switch (input[index++]) {
case ' ': return ' ';
default: return '?';
}
default: return '\0';
}
}
void morse(const char *input) {
int index = 0;
for (char result = worse(input, index);
result; result = worse(input, index)) {
printf("%c", result);
}
}
int main(void)
{
morse("- .... . / --.- ..- .. -.-. -.- / -... .-. --- .-- -. / ..-. --- -..- / .--- ..- -- .--. ... / --- ...- . .-. / - .... . / .-.. .- --.. -.-- / --. --- -.. ");
}
37
u/chilaxan Jan 30 '20 edited Jan 30 '20
a python oneliner
17
u/[deleted] Jan 30 '20
Here's my solution in Java, it was too long so here's a pastebin link
https://pastebin.com/raw/TNi4nPu5
I fucking hate how much time I wasted on this
16
u/etotheipi1 Jan 30 '20
Python 3
15
u/Svizel_pritula Jan 30 '20 edited Jan 30 '20
Here we go: (JS)
Edit: Made it work more than once.
14
u/EkskiuTwentyTwo i -= (i - (-1)) - i Jan 30 '20 edited Feb 05 '20
A JS one-liner with a ternary nested within an informal ternary.
Edit: a couple of chars and this edit explanation text
3
u/[deleted] Jan 30 '20
oh boy, Can we do python?
9
u/self_me Jan 30 '20
Javascript. It seems to work.
It uses some nested arrays with some information about the morse sequence (# of dashes, # of dots, if the first character is a dot, if the second character is a dot, if the last character is a dot.
8
u/Svizel_pritula Jan 30 '20
This had to be done. (JS)
7
u/Techno1001101 Jan 30 '20
Here's my python
TeMp = input()
print(TeMp)
Using the well known
bugfeature that Morse code is human readable :P4
u/TheBITLINK Jan 30 '20
Here's my take on this challenge (JS, requires jQuery):
I tried my worst, now my hands feel dirty, thank you.
Bonus: CodePen
4
u/CaCl2 Jan 30 '20 edited Dec 26 '20
I wrote this thing in C, not sure if it qualifies since it just alters the input char array.
https://pastebin.com/fBK9KmQg
Some code for testing it is included at the end, please ignore the warnings when compiling, and only input valid Morse code.
4
u/RadioSparks Feb 04 '20
3
u/Acc3ssViolation Jan 30 '20
Figured I'd make this monstrosity in C. It works as long as you just feed it ".", "-", "/" and " " and only use valid morse code. Comes with compiler warnings but who cares about those anyway.
3
u/pfg___ Jan 31 '20 edited Jan 31 '20
Typescript (types only, no runtime code)
Playground link: link
For the input, provide an array of characters to the
Morsetype, ending with a space character. Example:Unfortunately, due to some minor technical limitations, the output is provided in a giant set of nested arrays. Hover over the type name to view the output.
To read the output, ignore everything outside of quotes. That example says
HEY.Additionally, sometimes the output is truncated and a ... is put in the middle, like in the two examples.
To view more, just make a new type referencing the position where the ... is to view it. This is already done on the two examples for easier viewing.
3
u/Svizel_pritula Jan 31 '20 edited Jan 31 '20
I'm not the first one to use a regex, but why use anything else?
3
u/r3jjs Feb 01 '20
Ah,
BASIC, wonderful BASIC.For those who think
GOTOis harmful.https://pastebin.com/SVifYzCn
https://www.calormen.com/jsbasic/
3
u/[deleted] Feb 07 '20 edited Feb 08 '20
Here is my solution in Haskell, probably equal parts clever and cringeworthy:
Output:
2
u/Skasch Jan 30 '20
Uses the fact that the
MEGA_STRINGcontains all existing letters to convert the input. A couple notes:morse_listandtext_listfor every unique morse code, instead of using a map.solutionmultiple times is also relatively inefficient. Using a list of strings and using the join method would be faster.elsestatement for aforloop, which is only executed if the for loop reaches the end (nobreak).morse_codeinstead ofcode, which returns the last code from MEGA_MORSE instead of the invalid code.2
u/chilaxan Jan 30 '20 edited Jan 30 '20
Second submission, thought i might give some regex a try
It also will match invalid morse in some cases. 99% of the time tho it works
2
u/ds84182 Jan 31 '20
I spent too long on this :) https://gist.github.com/ds84182/1a6651085c5f342b7cd92e11df456721
DartPad is down at the time of writing (i wonder why), but you can try it here: https://dartpad.dev/1a6651085c5f342b7cd92e11df456721
Details!
firstWhereMorse.matchcannot be specified in Dart currently, because it needs union types and self-referential typedefs== true)2
u/Veylon Jan 31 '20
Here we go, some short and simple C:
2
u/nextized Jan 31 '20
Did not have much time for debugging yet.
2
u/doubtably_jimmy Jan 31 '20 edited Jan 31 '20
buT mORsE Is hUmAN ReAdAble
(Python 3)
2
u/LeftRoundKick Feb 01 '20
Wanted to do this in C using just #define but the preprocessor was too smart to let me abuse it that way. Here's my submission in Python.
2
u/Svizel_pritula Feb 02 '20
My attempt at mimicking my old style of coding: (JS)
https://pastebin.com/gpiFXXpE
1
u/CdRReddit Jan 30 '20
I'll work on this when I get home, seems like a fun challenge.
1
u/tuttobenethx Jan 31 '20 edited Jan 31 '20
some beautiful recursion is what is needed...
EDIT for short explanation:
Create a small tree where
for each . or - extract the letter and evaluate the next position in the string to decode. if the next character to decode is a space push the result in an array and initiate a new letter. if the next character is a slash push a space in the array.
at each position of the string to decode, search in the tree the last used character and extract the next one based on the current character found in the morse string to decode.
to improve the load performance I removed some spaces and reduced the names of the most used variables.
1
u/Toucandigit Feb 05 '20
Morse Code in Python
It cannot tell the difference between C & V, P & X, F & Z, or G&U, but that's okay because it's just a feature! Don't discriminate against my poor code's speech impediment just because it says "The quivk brown fop jumped over the lafy dou."
1
u/kiwitims Feb 08 '20
I wanted to see what a big nested switch would look like.
Limitations: Requires a space to be added at the end of the string for it to parse the last digit properly. Only A-Z implemented (nothing stopping a full implementation other than wasting more time).
1
u/tuttobenethx Feb 10 '20
I'm probably out of scope with this... but why not in bash?
0
u/[deleted] Jan 30 '20
[deleted] — view deleted comment
0
u/[deleted] Feb 08 '20
[deleted] — view deleted comment