Write a formatted Morse code cheatsheet

24

1

Challenge:

Write a program that produces the following output:

. E   .. I   ... S   .... H
                     ...- V
             ..- U   ..-. F
                     ..--  
      .- A   .-. R   .-.. L
                     .-.-  
             .-- W   .--. P
                     .--- J
- T   -. N   -.. D   -... B
                     -..- X
             -.- K   -.-. C
                     -.-- Y
      -- M   --. G   --.. Z
                     --.- Q
             --- O   ---.  
                     ----  

This is a formatted table of the Morse codes of the letters from A to Z. Each column is separated by three spaces.

There are four missing slots, which are used by international character sets. Your program must write a space there.

The output must consist of ASCII spaces, dots, dashes, uppercase letters and newlines (either LF or CRLF) only.

Your program accepts no input.

The following is a sample Python program that produces the desired output:

b = "."
out = []
last = 0
ch = "EISHVUF ARL WPJTNDBXKCYMGZQO  "
cx = 0
while b:
    if last >= len(b):
        print("   ".join(out))
        out = ["   ", "    ", "     ", "      "][0:len(b) - 1]
    out.append(b + " " + ch[cx])
    cx += 1
    last = len(b)
    if len(b) < 4:
        b += "."
    elif b[-1] == ".":
        b = b[0:-1] + "-"
    else:
        i = len(b) - 1
        while b[i] == "-":
            i -= 1
            if i < 0:
                break
        if i < 0:
            break
        b = b[0:i] + "-"
print("   ".join(out))

This is , so the shortest answer in bytes wins.

Locoluis

Posted 2017-05-23T15:29:44.220

Reputation: 741

1can each line 3 prepending spaces? – dzaima – 2017-05-23T18:58:27.313

1Standard loopholes disallow solution hard coding. How much of the table are we allowed to hard code? – Brunner – 2017-05-23T18:58:27.943

@Brunner considering the table is around 450 bytes, I doubt hard coding is the optimal solution – Cyoce – 2017-05-23T19:48:39.693

@Cyoce Definitely not the shortest version here, but Joerg Huelsermann got it down to 208 bytes in his brilliant php answers. – Brunner – 2017-05-23T20:57:09.390

@Brunner I don't think hard coding is an issue with Kolgomorov-Complexity challenges, since it is pretty much in the definition of the challenge. It doesn't take input, so how would you get to the solution, other than by hard coding it (and compressing or building it up in some shape or form)? – JAD – 2017-05-25T16:29:34.190

@JarkoDubbeldam I'm not opposed to hard-coding, I was just wondering if there was a limit. To answer your question, it doesn't have to be all or nothing. – Brunner – 2017-05-25T17:01:27.640

@Brunner Generally, there are better (shorter) ways to create the output than a simple print statement with the entire output in there. So while there isn't really a limit to the hardcoding, you generally won't win doing it like that. – JAD – 2017-05-25T18:30:50.277

@JarkoDubbeldam I never said that was the case and I wasn't implying that hard-coding might be an advantage. I do F# answers, I don't expect to win with any of those :) It's like I said earlier, I was just curious if there was an additional constraint or not. – Brunner – 2017-05-25T20:05:14.237

1Are we allowed to have trailing spaces? – Adám – 2017-05-28T21:17:28.440

If there´s a pattern, generating the content is almost always the shortest approach. – Titus – 2017-05-29T09:18:55.177

@Adám The default for [tag:ascii-art] is that it's just the visual effect of the output that matters, not the actual characters that make it up; thus, differences in invisible characters (like trailing whitespace) don't matter. The OP can override that if they want to, but I don't see why they would here. – None – 2017-06-18T22:20:16.087

Why no CR newlines? – CalculatorFeline – 2017-06-18T23:47:38.360

Answers

5

Jelly, 85 bytes

ØQj⁶“_ȦeƤbṅỌU@⁼Cq’œ?;⁶$⁺ṁ®L€€¤
4R2ṗ©ị⁾.-;€€⁶ż"¢;€€⁶$⁺W€€j"731Dẋ@⁶¤ZµKFṚ;⁶ẋ³¤ḣ29ṫ3Ṛµ€Y

A full program printing the cheat sheet.

Try it online!

How?

Note: I do think there may be a way to trim this down by forming a list which formats correctly by use of the grid atom, G, but I can't quite work out how.

ØQj⁶“_ȦeƤbṅỌU@⁼Cq’œ?;⁶$⁺ṁ®L€€¤ - Link 1: get "letters" lists: no arguments
ØQ                             - Qwerty yield = ["QWERTYUIOP","ASDFGHJKL","ZXCVBNM"]
  j⁶                           - join with spaces = "QWERTYUIOP ASDFGHJKL ZXCVBNM"
    “_ȦeƤbṅỌU@⁼Cq’             - base 250 number = 23070726812742121430711954614
                  œ?           - lexicographical permutation at index = "ETIANMSURWDKGOHVF L PJBXCYZQ"
                       ⁺       - do this twice:
                      $        -   last two links as a monad
                    ;⁶         -     concatenate a space              = "ETIANMSURWDKGOHVF L PJBXCYZQ  "
                             ¤ - nilad followed by link(s) as a nilad:
                         ®     -   recall from registry (4R2ṗ from the Main link)
                          L€€  -   length for €ach for €ach = [[1,1],[2,2,2,2],[3,3,3,3,3,3,3,3],[4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4]]
                        ṁ      - mould like = ["ET","IANM","SURWDKGO","HVF L PJBXCYZQ  "]

4R2ṗ©ị⁾.-;€€⁶ż"¢;€€⁶$⁺W€€j"731Dẋ@⁶¤ZµKFṚ;⁶ẋ³¤ḣ29ṫ3Ṛµ€Y - Main link: no arguments
4R                                                     - range(4) = [1,2,3,4]
  2ṗ                                                   - Cartesian power with 2 = [[[1],[2]],[[1,1],[1,2],[2,1],[2,2]],...,[...,[2,2,2,2]]]
    ©                                                  - copy to register and yield
      ⁾.-                                              - literal ['.','-']
     ị                                                 - index into (makes all the codes, in four lists by length like reading the output top-bottom, left-right)
         ;€€⁶                                          - concatenate a space to each code
               ¢                                       - call last link (1) as a nilad (get the letters reordered as required)
             ż"                                        - zip left and right with zip dyad
                     ⁺                                 - do this twice:
                    $                                  -   last two links as a monad:
                ;€€⁶                                   -     concatenate a space to each code, letter pair
                      W€€                              - wrap each code, letter pair in a list
                                  ¤                    - nilad follwed by link(s) as a nilad:
                           731                         -   literal 731
                              D                        -   to decimal list = [7,3,1]
                               ẋ@⁶                     -   repeat a space = ["       ","   "," "]
                         j"                            - zip with dyad join
                                   Z                   - transpose
                                    µ              µ€  - for each:
                                     K                 -   join with spaces
                                      F                -   flatten
                                       Ṛ               -   reverse
                                            ¤          -   nilad followed by link(s) as a nilad:
                                         ⁶ẋ³           -     space repeated 100 times
                                        ;              -   concatenate
                                             ḣ29       -   head to 29 (make all "lines" the same length)
                                                ṫ3     -   tail from 3 (trim off two spaces from each line)
                                                  Ṛ    -   reverse
                                                     Y - join with newlines
                                                       - implicit print

Jonathan Allan

Posted 2017-05-23T15:29:44.220

Reputation: 67 804

7

Python 3.6, 201 197 193 187 bytes

for i in range(16):print('   '.join(i%k and' '*(2+j)or f'{i//k:0{j}b}'.replace(*'0.').replace(*'1-')+' '+'ETIANMSURWDKGOHVF L PJBXCYZQ  '[2**j-2+i//k]for j,k in zip((1,2,3,4),(8,4,2,1))))

Uses some formatting, unpacking and A000918 magic.

Uriel

Posted 2017-05-23T15:29:44.220

Reputation: 11 708

By the way, f'{i//k:0{j}b}'.replace(*'0.').replace(*'1-') is the same length as ''.join('.-'[int(x)]for x in f'{i//k:0{j}b}') – Uriel – 2017-05-23T17:59:37.373

5

Retina, 125 bytes

^
. EISHVUF_ARL_WPJ¶- TNDBXKCYMGZQO__
+m`^((.*?)([-.]+) )(\w)((\w)+?)(((?<-6>)\w)+)$
$2$3 $4   $3. $5¶$.1$*     $3- $7
T`\_`p

Try it online! Should be 121 bytes but I was too lazy to deal with the whitespace at the start and end. Explanation:

[blank line]
. EISHVUF_ARL_WPJ¶- TNDBXKCYMGZQO__

The letters whose code begins with . and - respectively are preloaded. (It is theoretically possible to avoid preloading the .- but it saves bytes this way.) _s are used instead of spaces as they are considered to be letters which makes them easier to match below.

+m`^((.*?)([-.]+) )(\w)((\w)+?)(((?<-6>)\w)+)$
$2$3 $4   $3. $5¶$.1$*     $3- $7

Here we split each line up into five pieces:

  • The letters for prefixes, if any
  • The current Morse code
  • The current letter
  • The first half of the remaining letters (their next character is .)
  • The second half of the remaining letters (their next character is -)

The pieces are then reassembled onto two lines:

  • The letters for prefixes, the current Morse code, the current letter, the Morse code with a . suffix, the first half of the remaining letters
  • Spaces replacing the first three pieces, the Morse code with a - suffix, the second half of the remaining letters

The new lines follow the same format as the existing line, just with an extra Morse prefix and half as many letters remaining to process. This is then repeated until each line has only one letter.

_
  [single space]

The _s are then changed back into spaces.

Neil

Posted 2017-05-23T15:29:44.220

Reputation: 95 035

3

JavaScript (ES6), 154 147 145 bytes

f=(n=r='',d=i=k=0)=>(r+=n&&' '.repeat([d++&&3,21,13,6][i-(i=d-k)])+n+' '+'EISHVUF ARL WPJTNDBXKCYMGZQO  '[k++],d<4)?f(n+'.',d)&&f(n+'-',d):r+=`
`

o.innerHTML = f()
<pre id=o>

Arnauld

Posted 2017-05-23T15:29:44.220

Reputation: 111 334

Oh dang! I missed this one... wouldn't have bothered otherwise! Well done :-) – Bumpy – 2017-05-24T06:59:45.763

2

PHP, 208 Bytes

<?=gzinflate(base64_decode("dZDJEQMhDAT/RNEJaHLwfd+38w/EWrRlu6gVnwZpGhWIGSCxqhCXoFgWhpa3jHtpasYtKOaZZwZ9z/OjCnEOim3imX7et2Y8guKYeR5aF+PqB4/tK8Q0KMbDnnWPeZamZmyCYpJ5Pu/V93y7qxCLoHgnXnf5qZnn/iGo9u1/Gf+XDw=="));

Try it online!

PHP, 229 Bytes

<?=strtr("3E0.3I053S0.53H12 2.54V1254U05-3F12 25-4 1.4A0.-3R0.-.3L12 2.-.4 12.-4W0.63P12 2.64J
4T0-3N0-.3D0-53B12 2-54X12-.4K0-.-3C12 2-.-4Y1-4M063G06.3Z12 26.4Q1264O0-63 12 2-64 ",[$a="   ","
$a$a","$a $a",". ","- ","..","--"]);

Try it online!

Jörg Hülsermann

Posted 2017-05-23T15:29:44.220

Reputation: 13 026

2

Perl 5, 158 156 bytes

map{$a=sprintf'%04b',$_;map{$a=~/.{$_}/;print(-$'?' 'x$_:$&=~y/01/.-/r,' ',(' EISHVUF ARL WPJTNDBXKCYMGZQO  '=~/./g)[!-$'&&++$i],$_-4?'   ':"\n")}1..4}0..15

faubi

Posted 2017-05-23T15:29:44.220

Reputation: 2 599

2

APL (Dyalog), 92 bytes

Needs ⎕IO←0 which is default on many systems.

0 3↓¯1⌽⍕{' ',(16⍴1↑⍨16÷≢⍵)⍀'.-'[⍉2⊥⍣¯1⍳≢⍵],' ',⍪⍵}¨'ET' 'IANM' 'SURWDKGO' 'HVF L PJBXCYZQ  '

Try it online!

{}¨'' apply the following anonymous function to each of the strings:

⍪⍵ make the argument into a column

' ', prepend a space (on each row)

'.-'[], prepend the string after it has been indexed with:

  ≢⍵ the length of the argument

   the indices of that (0, 1, 2, …, length-1)

  2⊥⍣¯1 anti-base-2 (uses as many bits as needed)

   transpose (from one representation in each column to one in each row)

()⍀ expand by (insert blank rows as indicated by zeros in):

  ≢⍵ the length of the argument

  16÷ divide sixteen by that

  1↑⍨ (over)take from one (makes a list of a one followed by 1-n zeros)

  16⍴ recycle that pattern until it has sixteen elements

' ', prepend a space

 format (the list of tables into a single table, padding each with a space on each side)

¯1⌽ rotate one step right (thus moving the trailing space to the front)

0 3↓ drop zero rows and three columns (thus removing the three leading spaces)

Adám

Posted 2017-05-23T15:29:44.220

Reputation: 37 779

Hey, where does 16÷⍨ appear in your code‽ – Zacharý – 2017-06-18T18:30:13.237

@ZacharyT It sure doesn't. Nicely spotted, sir. – Adám – 2017-06-18T20:16:55.900

2

PHP, 184 183 181 bytes

for(;$y<16;$y++,print str_pad(ltrim("$r
"),28," ",0))for($r="",$c="03231323"[$y&7];$c++<4;)$r.=strtr(sprintf("   %0${c}b ",$y>>4-$c),10,"-.")."EISHVUF ARL WPJTNDBXKCYMGZQO  "[$i++];

Run with -nr or try it online.

breakdown

for(;$y<16;$y++,                                    # loop through rows
    print str_pad(ltrim("$r\n"),28," ",0)               # 4. pad to 28 chars and print
    )
    for($r="",                                          # 1. result=empty
        $c="03231323"[$y&7];                            # 2. $c=bits in 1st code -1
        $c++<4;)                                        # 3. loop through columns
        $r.=strtr(sprintf("   %0${c}b ",$y>>4-$c),10,"-.")  # append morse code
            ."EISHVUF ARL WPJTNDBXKCYMGZQO  "[$i++];            # append letter

-7 bytes with leading spaces: Replace ltrim("$r\n") with "$r\n" and 28 with 31.

171 (= -10) bytes with trailing spaces:

for(;$y<16;$y++)for(print str_pad("
",[0,7,14,22][$c="03231323"[$y&7]]);$c++<4;)echo strtr(sprintf("%0${c}b %s   ",$y>>4-$c,"EISHVUF ARL WPJTNDBXKCYMGZQO"[$i++]),10,"-.");

breakdown try it online

for(;$y<16;$y++)                                    # loop through rows
    for(
        print str_pad("\n",[0,7,14,22][             # 2. print left padding
            $c="03231323"[$y&7]                     # 1. $c=bits in 1st code -1
        ]); 
        $c++<4;)                                        # 3. loop through columns
        echo                                                # print ...
            strtr(sprintf("%0${c}b %s   ",                  # 3. delimiting spaces
            $y>>4-$c,                                       # 1. morse code
            "EISHVUF ARL WPJTNDBXKCYMGZQO"[$i++]            # 2. letter
        ),10,"-.");

Titus

Posted 2017-05-23T15:29:44.220

Reputation: 13 814

1No true line break this time? – Christoph – 2017-05-29T09:40:15.433

1for(;$y<16;$y++,print str_pad(ltrim("$r\n"),28," ",0))for($r="",$c="03231323"[$y&7];$c++<4;)$r.=strtr(sprintf(" %0${c}b ",$y>>4-$c),10,"-.")."EISHVUF ARL WPJTNDBXKCYMGZQO "[$i++]; should save 2 bytes. – Christoph – 2017-05-29T09:53:32.983

1It seems you droped a space too much: In the last line ---- doesn't match with the rest. "EISHVUF ARL WPJTNDBXKCYMGZQO " should have 2 spaces in the end. – Christoph – 2017-05-29T10:59:00.800

1

Bubblegum, 133 bytes

000000: e0 01 be 00   7d 5d 00 17   08 05 23 e4   96 22 00 5d │ à.¾.}]....#ä.".]
000010: e5 e9 94 d3   78 24 16 ec   c1 c4 ad d8   6e 4d 41 e8 │ åé.Óx$.ìÁÄ.ØnMAè
000020: a3 a1 82 e6   f4 88 d9 85   6f ae 6b 93   aa 44 c8 e3 │ £¡.æô.Ù.o®k.ªDÈã
000030: 29 6f df 65   aa 4a f8 06   f5 63 1a 73   a7 e4 4d 19 │ )oßeªJø.õc.s§äM.
000040: 03 2c 87 59   7b df 27 41   4b b6 12 dd   7c e5 78 27 │ .,.Y{ß'AK¶.Ý|åx'
000050: 9c 9f 99 db   f6 8e 42 fd   43 68 48 46   37 da d7 21 │ ...Ûö.BýChHF7Ú×!
000060: a9 ca ea be   f4 57 e0 da   c1 16 97 ef   7a 0c e9 3c │ ©Êê¾ôWàÚÁ..ïz.é<
000070: 8e c2 b6 22   ca e4 e5 53   57 f0 f4 fb   a4 fb c0 a7 │ .¶"ÊäåSWðôû¤ûÀ§
000080: ec cd 6e 00   00                                      │ ìÍn..

Compressed as a LZMA stream.

Uriel

Posted 2017-05-23T15:29:44.220

Reputation: 11 708

1

SOGL, 106 105 102 bytes

¹θΞk“r²{r³³a:IA2─l4;- 0*;+Ζ0.ŗΖ1-ŗø4∫BƧ| ⁵±+⁷b<?⁄@*}+;j;@3*+}±kkk≥x}¹±č┐"7ŗ◄∑f^│N≥Χ±⅜g,ιƨΛ.⌡׀¹*ΛβΧκ‘čŗ

If prepending spaces are allowed, 102 99 bytes

¹θΞk“r²{r³³a:IA2─l4;- 0*;+Ζ0.ŗΖ1-ŗø4∫BƧ| ⁵±+⁷b<?⁄@*}+;j;@3*+}±≥x}¹±č┐"7ŗ◄∑f^│N≥Χ±⅜g,ιƨΛ.⌡׀¹*ΛβΧκ‘čŗ

141 bytes, compression

Πa≤χ≥∫RωθΩ≡⅛QΨ═Λ9⁶Ul¹&╔²‘č"‼¼⁸Ƨ,9█ω½└╗«ωΤC¡ιΝ/RL⌡⁄1↑οπ∞b∑#⁵ø⁶‘č"⁵ ?∙«Σf⁾ƨ╤P1φ‛╤Β«╚Δ≡ΟNa1\÷╬5ŗķ§⁷D◄tFhžZ@š⁾¡M<╔↓u┌⁽7¡?v¦#DΘø⌡ ⁹x≡ō¦;⁵W-S¬⁴‘' n

just wanted to see how well could SOGL do with just compression (well it's got more than just compression, but it's 97% compressed strings)

dzaima

Posted 2017-05-23T15:29:44.220

Reputation: 19 048

1

Ruby, 144 143 141 bytes

k=0
16.times{|i|4.times{|j|$><<("%0#{j+1}b 9   "%(i>>3-j)).tr('109',(i+8&-i-8)>>3-j>0?'-.'+'  OQZGMYCKXBDNTJPW LRA FUVHSIE'[k-=1]:" ")}
puts}

Ungolfed

k=0                                                     #setup a counter for the letters
16.times{|i|                                            #16 rows    
  4.times{|j|                                           #4 columns
    $><<("%0#{j+1}b 9   "%(i>>3-j)).                    #send to stdout a binary number of j+1 digits, representing i>>3-j, followed by a 9, substituted as follows.
      tr('109',(i+8&-i-8)>>3-j>0?                       #(i&-i) clears all but the least significant 1's bit of i. the 8's ensure a positive result even if i=0.
      '-.'+'  OQZGMYCKXBDNTJPW LRA FUVHSIE'[k-=1]:      #if the expression righshifted appropriately is positive, substitute 1and0 for -and. Substitute 9 for a letter and update counter.
      " ")}                                             #else substiture 1,0 and 9 for spaces.
puts}                                                   #carriage return after each row.

Level River St

Posted 2017-05-23T15:29:44.220

Reputation: 22 049

1

JavaScript (205 bytes)

for(A='EISHVUF ARL WPJTNDBXKCYMGZQO     ',q=0,i=15;30>i++;){for(x=i.toString(2).replace(/(.)/g,a=>1>a?'.':'-'),o='',j=4;j--;)o+=(i%2**j?A.slice(-6+j):x.slice(1,5-j)+' '+A.charAt(q++))+'   ';console.log(o)}

for(A='EISHVUF ARL WPJTNDBXKCYMGZQO     ',q=0,i=15;30>i++;){for(x=i.toString(2).replace(/(.)/g,a=>1>a?'.':'-'),o='',j=4;j--;)o+=(i%2**j?A.slice(-6+j):x.slice(1,5-j)+' '+A.charAt(q++))+'   ';console.log(o)}

Bumpy

Posted 2017-05-23T15:29:44.220

Reputation: 489

1

C, 199 195 bytes

#define P putchar
m;p(i,v){printf("%*s",i&1|!v?v*(v+11)/2:3,"");for(m=1<<v;m;m/=2)P(45+!(i&m));P(32);P("  ETIANMSURWDKGOHVF L PJBXCYZQ  "[i]);v<3?p(2*i,v+1):P(10);++i&1&&p(i,v);}main(){p(2,0);}

Live on coliru (with #include to avoid the warning message.)

UPDATE: Saved four characters by moving the "declaration" of m outside the function, as suggested by @zacharyT

Uses what seems to be a standard strategy: keep the letters in an array-encoded binary tree, so the children of element i are 2*i and 2*i+1. This tree is rooted at 2 rather than 1 because the arithmetic worked out a little shorter, I think. All the rest is golfing.

Ungolfed:

// Golfed version omits the include
#include <stdio.h>
// Golfed version uses the string rather than a variable.
char* tree = "  ETIANMSURWDKGOHVF L PJBXCYZQ  ";
/* i is the index into tree; v is the number of bits to print (-1) */
void p(int i, int v) {
  /* Golfed version omits all types, so the return type is int.
   * Nothing is returned, but on most architectures that still works although
   * it's UB.
   */
  printf("%*s", i&1 || !v ? v*(v+11)/2 : 3, "");
  /* v*(v+11)/2 is v*(v+1)/2 + 3*v, which is the number of spaces before the odd
   * element at level v. For even elements, we just print the three spaces which
   * separate adjacent elements. (If v is zero, we're at the margin so we
   * suppress the three spaces; with v == 0, the indent will be 0, too.
   *
   * Golfed version uses | instead of || since it makes no semantic difference.
   */

  /* Iterate over the useful bits at this level */
  for (int m=1<<v; m; m/=2) {
    /* Ascii '-' is 45 and '.' is 46, so we invert the tested bit to create the
     * correct ascii code.
     */
    putchar('-' + !(i&m));
  }
  /* Output the character */
  putchar(' ');
  putchar(tree[i]);
  /* Either recurse to finish the line or print a newline */
  if (v<3)
    p(2*i,v+1);
  else
    putchar('\n');
  /* For nodes which have a sibling, recurse to print the sibling */
  if (!(i&1))
    p(i+1, v);
}

int main(void) {
  p(2,0);
}

rici

Posted 2017-05-23T15:29:44.220

Reputation: 601

Could you move the int m to be m; outside of the function? – Zacharý – 2017-06-18T17:24:46.577

Does this work https://repl.it/Iqma?

– Zacharý – 2017-06-18T18:17:51.950

@ZacharyT: I suppose it will work but it's one character longer (the open parenthesis in the #define) so there seems little point. – rici – 2017-06-18T21:21:43.727

I counted 194 bytes with that version, am I missing something? – Zacharý – 2017-06-18T23:42:16.587

1

Pyth, 106 bytes

DhNR.n.e+]++.[\.sllN::.Bk\0\.\1\-\ b*]*\ +2sllNt/16lNNjmj*3\ d.t[h"ET"h"IANM"h"SURWDKGO"h"HVF L PJBXCYZQ  

Test it online!

Explanation

In a few words, what I do here is to generate the table column by column and then transpose the table before printing it. We notice that in a column, the morse codes for the letters can be represented as binary strings (replace . by 0 and - by 1) when counting from zero to the index of the last letter in the column.

The algorithm relies on a function from which I give an example run below (for the second column):

1. Takes "IANM" as input
2. Generates the binary representations of zero up to len("IANM"): ["0", "1", "10", "11"]
3. Replace with dots and hyphens: [".", "-", "-.", "--"]
4. Pad with dots up to floor(log2(len("IANM"))): ["..", ".-", "-.", "--"]
5. Add the corresponding letters: [".. I", ".- A", "-. N", "-- M"]
6. After each element, insert a list of 16 / len("IANM") - 1 (= 3) strings containing only spaces of length floor(log2(len("IANM"))) + 2 (= 4):
    [".. I", ["    ", "    ", "    "], ".- A", ["    ", "    ", "    "], "-. N", ["    ", "    ", "    "], "-- M", ["    ", "    ", "    "]]
7. Flatten that list:
    [".. I", "    ", "    ", "    ", ".- A", "    ", "    ", "    ", "-. N", "    ", "    ", "    ", "-- M", "    ", "    ", "    "]
8. That's it, we have our second column!

Code explanation

I cut the code in two. The first part is the function described above, the second part is how I use the function:

DhNR.n.e+]++.[\.sllN::.Bk\0\.\1\-\ b*]*\ +2sllNt/16lNN

DhNR                                                      # Define a function h taking N returning the rest of the code. N will be a string
      .e                                             N    # For each character b in N, let k be its index
                      .Bk                                 # Convert k to binary
                     :   \0\.                             # Replace zeros with dots (0 -> .)
                    :        \1\-                         # Replace ones with hyphens (1 -> -)
            .[\.sllN                                      # Pad to the left with dots up to floor(log2(len(N))) which is the num of bits required to represent len(N) in binary
          ++                     \ b                      # Append a space and b
         ]                                                # Make a list containing only this string. At this point we have something like [". E"] or [".. I"] or ...
        +                           *]*\ +2sllNt/16lN     # (1) Append as many strings of spaces as there are newlines separating each element vertically in the table
    .n                                                    # At this point the for each is ended. Flatten the resulting list and return it

(1): In the morse table, in the first column, there is seven lines after each line containing a letter ("E" and "T"). In the second column, it is three lines. Then one (third column), then zero (last column). That is 16 / n - 1 where n is the number of letters in the column (which is N in the code above). That what does the code at line (1):

*]*\ +2sllNt/16lN

       sllN          # Computes the num of bits required to represent len(N) in binary
     +2              # To that, add two. We now have the length of a element of the current column
  *\                 # Make a string of spaces of that length (note the trailing space)
           t/16lN    # Computes 16 / len(N) - 1
*]                   # Make a list of that length with the string of spaces (something like ["    ", "    ", ...])

Alright, now we have a nice helpful function h which basically generates a table's column out of a sequence of characters. Let's use it (note the two trailing spaces in the code below):

jmj*3\ d.t[h"ET"h"IANM"h"SURWDKGO"h"HVF L PJBXCYZQ  

           h"ET"                                        # Generate the first column
                h"IANM"                                 # Generate the second column
                       h"SURWDKGO"                      # Generate the third column
                                  h"HVF L PJBXCYZQ      # Generate the last column (note the two trailing spaces)
          [                                             # Make a list out of those columns
        .t                                              # Transpose, because we can print line by line, but not column by column
 mj*3\ d                                                # For each line, join the elements in that line on "   " (that is, concatenate the elements of the lines but insert "   " between each one)
j                                                       # Join all lines on newline

The code can still be shortened; maybe I'll come back on it later.

Jim

Posted 2017-05-23T15:29:44.220

Reputation: 1 442

0

JavaScript (ES7), 242 240 238 bytes

console.log([...'EISH000V00UF000 0ARL000 00WP000JTNDB000X00KC000Y0MGZ000Q00O 000 '].map((a,k)=>(n=>(a!='0'?(2**n+(k>>2)/2**(4-n)).toString(2).slice(-n).replace(/./g,c=>'.-'[c])+' '+a:'      '.slice(-n-2))+(n<4?'   ':'\n'))(k%4+1)).join``)

Try it online!

–2 bytes thanks to Zachary.

eush77

Posted 2017-05-23T15:29:44.220

Reputation: 1 280

Try changing a!='0' to a!=0 – Cyoce – 2017-05-23T21:21:13.467

Can you replace .join('') with .join<insert backtick here><insert backtick here> ? (<insert backtick here> being replaced with actual backticks) – Zacharý – 2017-06-18T17:37:36.537

As Cyoce said, try changing a!='0' toa!=0, that should work. – Zacharý – 2017-06-18T18:26:31.623

@ZacharyT No it doesn’t, but thanks again.

– eush77 – 2017-06-18T18:45:23.620

Sorry, forgot about the ''case. – Zacharý – 2017-06-18T19:16:28.960

0

C, 291 bytes

Try Online

char*i,*t=".aEc..aIc...aSc....aH/u...-aV/m..-aUc..-.aF/u..--/f.-aAc.-.aRc.-..aL/u.-.-/m.--aWc.--.aP/u.---aJ/-aTc-.aNc-..aDc-...aB/u-..-aX/m-.-aKc-.-.aC/u-.--aY/f--aMc--.aGc--..aZ/u--.-aQ/m---aOc---./u----";
s(n){while(n--)putchar(32);}f(){for(i=t;*i;i++)*i<97?putchar(*i-'/'?*i:10):s(*i-96);}

How it works

First I parsed the string in C, counting spaces which are less than 26 so I encoded them in small case letters a, b, .. z with this little program

for(char*i=t; *i; i++)
{
    if(*i == ' ') c++;
    else c = 0;

    if(i[1] != ' ' && c > 0) putchar('a'+c-1);
    else if(*i =='\n') putchar('/');
    else if(*i != ' ') putchar(*i);
}

Then I wrote a parser for that encoding, where / is a new line, and a small-case letter represent t[i] - 'a' spaces

int s(int n)
{
    while(n--) putchar(32);
}

f()
{
    for(char*i=t; *i; i++)
        if(*i < 'a')
            if(*i == '/') putchar('\n');
            else putchar(*i);
        else s(*i-'a'+1);
}

Khaled.K

Posted 2017-05-23T15:29:44.220

Reputation: 1 435

263 bytes – ceilingcat – 2019-04-29T21:11:18.453

0

Bash (with utilities), 254 bytes

tail -n+2 $0|uudecode|bzip2 -d;exit
begin 644 -
M0EIH.3%!6293631+'LX``&UV`%`P(`!``S____`@`(@:2!H#:@!ZFU'H@T](
MJ>H`'J``;4L>\%)R2H9TS-4WY[M(`"`@=((AJ")8HR^QFK?8RQO2B+W47&@`
M!"@$(!%Q,$'X:#+&>BI<RAC5.J53,S(%FFB!%A-*SM9TY&I8RFZJ9<D0H_B[
)DBG"A(&B6/9P
`
end

sigvaldm

Posted 2017-05-23T15:29:44.220

Reputation: 341

0

Dyalog APL, 159 bytes (non-competing)

↑{X←⍵-1⋄Y←2*⍳4⋄R←Y+(Y÷16)×⍵-1⋄3↓∊{C←R[⍵]⋄'   ',(⍵⍴(1+0=1|C)⊃'    '({⍵⊃'.-'}¨1+(4⍴2)⊤X)),' ',((1+0=1|C)⊃' '((C-1|C)⊃' ETIANMSURWDKGOHVF L PJBXCYZQ  '))}¨⍳4}¨⍳16

Locoluis

Posted 2017-05-23T15:29:44.220

Reputation: 741

Why is this non-competing? – Adám – 2017-05-28T20:36:52.300

I think you can save a lot by setting ⎕IO←0 (default on many systems) and using (commute).

– Adám – 2017-05-28T21:06:54.197