18
\$\begingroup\$

Boustrophedon is a type of bi-directional text where successive lines alternate between reading left-to-right and right-to-left. Character direction was also mirrored with respect to reading direction. In reverse boustrophedon writing systems, characters were rotated 180 instead of mirrored.

Challenge

Write a program/function that accepts a string of text and a number of columns, and outputs the string formatted into the specified number of columns with alternating lines flipped upside down.

Input

Your program should accept two arguments:

  • S, the string of text to format
  • N, the number of columns

Output

Your program should output S wrapped in N columns with alternating lines flipped 180 degrees.

  • The reading direction of the first line is always left-to-right.
  • Don't worry about where to place line breaks, lines can be split at any character, no hypenation of words required.
  • You may assume input string will not contain any line breaks.

Here are the characters your program should support with their flipped counterparts:

Uppercase:
ABCDEFGHIJKLMNOPQRSTUVWXYZ
∀qƆpƎℲפHIſʞ˥WNOԀQɹS┴∩ΛMX⅄Z

Lowercase:
abcdefghijklmnopqrstuvwxyz
ɐqɔpǝɟƃɥᴉɾʞlɯuodbɹsʇnʌʍxʎz

Punctuation:
&_?!"'.,
⅋‾¿¡„,˙'

Test Cases

S: The quick brown fox jumps over the lazy dog.
N: 30
Output:
The quick brown fox jumps over
                ˙ƃop ʎzɐl ǝɥʇ 

S: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vel libero arcu. Nunc dictum elementum lectus nec aliquet. Donec dolor nunc, sodales at dolor rhoncus, hendrerit scelerisque purus. Pellentesque vel sagittis libero, et rutrum leo. Nullam vulputate enim et massa dictum, vitae venenatis augue lobortis. Fusce sollicitudin ultrices consequat. Vestibulum quis nunc non tortor eleifend facilisis. In at nunc elit. Aliquam pellentesque, lectus quis aliquam posuere, quam lectus sagittis metus, ut auctor sem quam a neque. Integer rhoncus lobortis nisl. Pellentesque mi dui, laoreet in metus quis, mollis accumsan est. Nunc dignissim tortor ac eleifend tempus. Ut ut tellus aliquam, luctus nulla quis, consectetur nunc. Suspendisse viverra molestie condimentum. Curabitur et hendrerit augue.
N: 50
Output:
Lorem ipsum dolor sit amet, consectetur adipiscing
uǝɯǝlǝ ɯnʇɔᴉp ɔunN ˙nɔɹɐ oɹǝqᴉl lǝʌ ǝnbsᴉnQ ˙ʇᴉlǝ 
tum lectus nec aliquet. Donec dolor nunc, sodales 
lǝԀ ˙snɹnd ǝnbsᴉɹǝlǝɔs ʇᴉɹǝɹpuǝɥ 'snɔuoɥɹ ɹolop ʇɐ
lentesque vel sagittis libero, et rutrum leo. Null
sᴉʇɐuǝuǝʌ ǝɐʇᴉʌ 'ɯnʇɔᴉp ɐssɐɯ ʇǝ ɯᴉuǝ ǝʇɐʇndlnʌ ɯɐ
 augue lobortis. Fusce sollicitudin ultrices conse
ɔɐɟ puǝɟᴉǝlǝ ɹoʇɹoʇ uou ɔunu sᴉnb ɯnlnqᴉʇsǝΛ ˙ʇɐnb
ilisis. In at nunc elit. Aliquam pellentesque, lec
ʇǝɯ sᴉʇʇᴉƃɐs snʇɔǝl ɯɐnb 'ǝɹǝnsod ɯɐnbᴉlɐ sᴉnb snʇ
us, ut auctor sem quam a neque. Integer rhoncus lo
snʇǝɯ uᴉ ʇǝǝɹoɐl 'ᴉnp ᴉɯ ǝnbsǝʇuǝllǝԀ ˙lsᴉu sᴉʇɹoq
 quis, mollis accumsan est. Nunc dignissim tortor 
u snʇɔnl 'ɯɐnbᴉlɐ snllǝʇ ʇn ʇ∩ ˙sndɯǝʇ puǝɟᴉǝlǝ ɔɐ
ulla quis, consectetur nunc. Suspendisse viverra m
˙ǝnƃnɐ ʇᴉɹǝɹpuǝɥ ʇǝ ɹnʇᴉqɐɹnƆ ˙ɯnʇuǝɯᴉpuoɔ ǝᴉʇsǝlo
\$\endgroup\$
4
\$\begingroup\$

Bash + GNU utilities, 204

fold -$1|sed 2~2{s/.\\+/printf\ %$1's "`echo "&"|rev`"/e
y/'`printf %s {A..Z} {a..z}`"&_?!\"'.,/∀qƆpƎℲפHIſʞ˥WNOԀQɹS┴∩ΛMX⅄Zɐqɔpǝɟƃɥᴉɾʞlɯuodbɹsʇnʌʍxʎz⅋‾¿¡„,˙'/
}"

N is given on the command line and S is given via STDIN:

$ echo "The quick brown fox jumps over the lazy dog." | ./boustrophedon.sh 30
The quick brown fox jumps over
                ˙ƃop ʎzɐl ǝɥʇ 
$ 

Explanation

  • fold -N splits the input into lines of length N.
  • The rest of the processing is done by sed, line-by-line:
    • 2~2 matches every other line, starting at line 2
    • s/.+/printf %'N's "`echo "&"|rev`"/e uses GNU Sed's exec feature to call a shell to reverse the line and left-pad it with up to N spaces
    • y/ABC.../∀qƆ.../ transform characters

Note ABC... is generated using a bash expansion and printf. Also some fancy quoting for all the different characters.

\$\endgroup\$
  • \$\begingroup\$ Thanks @isaacg - I thought I tried double backticks, but I guess I missed that. \$\endgroup\$ – Digital Trauma Nov 20 '15 at 6:37
3
\$\begingroup\$

Japt, 182 179 bytes

Japt is a shortened version of JavaScript. Interpreter

Ur'.+".?"pV-1 ,@A++%2?SpV-Xl)+Xw m@"„\xA1⅋,'˙¿∀qƆpƎℲפHIſʞ˥WNOԀQɹS┴∩ΛMX⅄Z[\\]^‾`ɐqɔpǝɟƃɥᴉɾʞlɯuodbɹsʇnʌʍxʎz"g(Q+"!&',.?"+65o124 m@Xd)a)bX)||X +R:X+R

How it works

             // Implicit: U = input string, V = input number, A = 10
Ur           // Take U and replace each group X of:
'.+".?"pV-1  //  at least one char, followed by up to V-1 other chars
             //   literally: RegExp("." + ".?".repeat(V-1))
@            // with: (@ is compiled to (X,Y,Z)=>)
A++%2?       //  If we're on an odd row:
SpV-Xl)+     //   Pad it with spaces, then concatenate it with
Xw m@        //   X reversed, with each character X mapped to:
"..."g       //   The character at position N in the string, where N is:
(Q+"!&',.?"  //    Build a string from a quote mark and these chars,
65o124 m@Xd)a) //   and all chars from A..z.
bX)          //    Return the index of X in this string.
||X          //   or if this number is outside the string, default to the original char.
+R           //   Either way, add a newline.
:X+R         //  Otherwise, return the original row text plus a newline.
             // Implicit: output last expression

There are a couple of problems, but they shouldn't affect the validity of the program:

  1. User @Vɪʜᴀɴ has recently helped me implement Unicode Shortcuts, or single characters in the range 00A1-00FF that stand in for commonly-used several-char sequences. The problem with this is that it currently replaces inside strings, so we can't use ¡ directly in the string for now. The safe alternative, \xA1, is three bytes longer.
  2. It's currently impossible to input a double-quote character. This will be fixed shortly.

Perhaps there's a way to shorten the string. Suggestions are welcome!

\$\endgroup\$
  • \$\begingroup\$ Nice! I wanted to try to convert my solution to Japt later, but this takes the cake. \$\endgroup\$ – Scott Nov 20 '15 at 1:36
2
\$\begingroup\$

CJam, 152

l~_q/\f{Se]}2/{)26,'Af+_el+"&_?!'.,"`+"∀qƆpƎℲפHIſʞ˥WNOԀQɹS┴∩ΛMX⅄Zɐqɔpǝɟƃɥᴉɾʞlɯuodbɹsʇnʌʍxʎz„⅋‾¿¡,˙'"erW%}%N*

Test it here.

I guess I should look into compressing that Unicode string a bit...

\$\endgroup\$
  • \$\begingroup\$ Compressing that Unicode string is hard - the code points are all over the place. As an experiment, I tried 'zopfli'ing my entire entry (including sed bits) and ended up bigger. I'll be watching with interest to see how you tackle it :) \$\endgroup\$ – Digital Trauma Nov 19 '15 at 22:55
2
\$\begingroup\$

Javascript (ES6), 407 400 366 360 353 bytes

I'm counting only the first two "lines" in this snippet as the total count, as the rest of it is code to run it.

s=`ABCDEFGHIJKLMNOPQRSTUVWXYZ∀qƆpƎℲפHIſʞ˥WNOԀQɹS┴∩ΛMX⅄Zabcdefghijklmnopqrstuvwxyzɐqɔpǝɟƃɥᴉɾʞlɯuodbɹsʇnʌʍxʎz&_?!"'.,⅋‾¿¡„,˙'`,f=(i,w)=>(i=i.match(RegExp(`.{1,${w}}`,"g")),i.map((c,x)=>x%2?" ".repeat(w-c.length)+[...c].reverse().map(b=>(d=s.indexOf(b),"A"<=b&&"z">=b?s[d+26]:" "==b?b:s[d+8])).join``:c).join`
`)

let input = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vel libero arcu. Nunc dictum elementum lectus nec aliquet. Donec dolor nunc, sodales at dolor rhoncus, hendrerit scelerisque purus. Pellentesque vel sagittis libero, et rutrum leo. Nullam vulputate enim et massa dictum, vitae venenatis augue lobortis. Fusce sollicitudin ultrices consequat. Vestibulum quis nunc non tortor eleifend facilisis. In at nunc elit. Aliquam pellentesque, lectus quis aliquam posuere, quam lectus sagittis metus, ut auctor sem quam a neque. Integer rhoncus lobortis nisl. Pellentesque mi dui, laoreet in metus quis, mollis accumsan est. Nunc dignissim tortor ac eleifend tempus. Ut ut tellus aliquam, luctus nulla quis, consectetur nunc. Suspendisse viverra molestie condimentum. Curabitur et hendrerit augue.";
console.log(f(input, 50));

Explanation

s=`A∀ .. ZZaɐ .. &⅋ ..`,                            //Character translation "map"
f=(i,w)=>                                           //Create a function named "f" that takes an (i)nput string and (w)idth
    (                                               //Implicitly return
        i=i.match(RegExp(`.{1,${w}}`,"g")),         //Cut string into arrays every w-th match of anything
        i.map((c,x)=>                               //Loop through each element in array by (c)ut at inde(x)
            x%2                                     //If the index is odd
                ?" ".repeat(w-c.length)                 //Output spaces for padding
                    +[...c].reverse()                   //Split this cut into each character, and read it backwards
                    .map((b,d)=>(                       //Translate each character
                        d=s.indexOf(b),                 //Save where this character appears in the mapping
                        "A"<=b&&"z">=b                  //If the character is a-zA-Z
                        ?s[d+26]                            //Print the flipped character by looking 26 characters ahead of where this character is found
                        :" "==b                             //Else, if it's a space
                            ?b                              //Output the space
                            :s[d+8]))                   //Else, print the flipped punctuation character (only 8 of these)
                    .join``                         //Join everything back into a continuous string
                :c                                  //Else just output the whole cut
            ).join`                                 
`)                                                  //Finally join each cut by a newline

  • Thanks to Dendrobium for -6 bytes!
  • Thanks to the Closure Compiler for -34 bytes!
  • Thanks to ןnɟuɐɯɹɐןoɯ for -7 bytes!
\$\endgroup\$
  • 1
    \$\begingroup\$ You can reduce all your .split("")'s and .join("")'s to .split`` and .join`` to shave off a few bytes. The .join("\n") can also be rewritten like the above with a literal newline instead of \n. \$\endgroup\$ – Dendrobium Nov 19 '15 at 18:50
  • \$\begingroup\$ Great tips, thank you very much! \$\endgroup\$ – Scott Nov 19 '15 at 19:05
  • 1
    \$\begingroup\$ You can take out the new keyword for the regex. Also use exec instead of match. Oh yeah, use [...c] instead of c.split``. \$\endgroup\$ – Mama Fun Roll Nov 20 '15 at 2:39
  • \$\begingroup\$ @ןnɟuɐɯɹɐןoɯ Nice, thank you! I couldn't figure out how to use exec and keep it short though, since exec needs to be looped over to get all matches. \$\endgroup\$ – Scott Nov 20 '15 at 3:01
  • \$\begingroup\$ Oh, nevermind about exec... \$\endgroup\$ – Mama Fun Roll Nov 20 '15 at 3:49
1
\$\begingroup\$

Pyth, 141 bytes

FNrZlKczQI%N2X.[" "Q_@KN++GrG1"&_?!\"'.,""ɐqɔpǝɟƃɥᴉɾʞlɯuodbɹsʇnʌʍxʎz∀qƆpƎℲפHIſʞ˥WNOԀQɹS┴∩ΛMX⅄Z⅋‾¿¡„,˙'")E@KN

Tested with an online Pyth Compiler.

How it Works

FNrZlKczQI%N2X.[" "Q_@KN)E@KN    █
                                 █
FN                               █ For N in 
  r                              █  ├ Range
   Z                             █  |  ・Start: 0 
                                 █  |  ・End: 
    l                            █  |     Length of
     K                           █  |      └─K = 
      c                          █  |         Split
       z                         █  |           ・String z
        Q                        █  |           ・By input int Q
         I%N2                    █  └─If divisible by 2
             X                   █     └─Translate
                                 █         ├─Source:
              .[                 █         | ├─Pad left
                " "              █         | |   ・With spaces
                   Q             █         | |   ・Until input int Q
                    _            █         | └──Reverse
                     @KN         █         |     ・Nth line of K
                        ++GrG1...█         ├─From: Normal  (See below)
                        "ɐqɔpǝ...█         └─To:   Flipped (See below)
                        )E@KN    █     Else print Nth line of K

Map

Normal

++                               █ Append:
  G                              █  1) a to z
   rG1                           █  2) A to Z
      "&_?!\"'.,"                █  3) Punctuation

Flipped (Nothing fancy)

"ɐqɔpǝɟƃɥᴉɾʞlɯuodbɹsʇnʌʍxʎz∀qƆpƎℲפHIſʞ˥WNOԀQɹS┴∩ΛMX⅄Z⅋‾¿¡„,˙'"
\$\endgroup\$
  • \$\begingroup\$ This is 108 characters long; however, the default way to measure the length of code-golf programs is in bytes. According to this page, the length of this answer is 141 bytes. \$\endgroup\$ – ETHproductions Nov 20 '15 at 23:16
  • \$\begingroup\$ @ETHproductions Thanks. Changed. \$\endgroup\$ – Helix Quar Nov 20 '15 at 23:32
0
\$\begingroup\$

Python, 453 363 bytes

s,n=input()
o="""ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz&_?!"'.,"""
p="""∀qƆpƎℲפHIſʞ˥WNOԀQɹS┴∩ΛMX⅄Zɐqɔpǝɟƃɥᴉɾʞlɯuodbɹsʇnʌʍxʎz⅋‾¿¡„,˙'""".decode('utf8')
s=map(''.join,zip(*[iter(s+' '*(n-1))]*n))
for i in range(len(s)):
 if i%2:s[i]=''.join(p[o.find(c)].encode('utf8')for c in s[i][::-1])
for l in s:print l
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.