19
\$\begingroup\$

Given a string, reverse it interleavingly. Here's how to do it for abcdefghi and abcdefghij, 0-indexed:

  1. Separate the chars at even indices from the chars at odd indices:
    a c e g i
     b d f h
    a c e g i b d f h j
  2. Reverse the chars at odd indices:
    a c e g i
     h f d b
    a c e g i j h f d b
  3. Interleave into one string again:
    ahcfedgbi
    ajchefgdib

Rules

  • You must support both even-length and odd-length strings.
  • 0-index-wise, you must reverse the chars at odd indices, not even.
  • 1-index-wise, of course, you must reverse the chars at even indices, not odd.
  • Input will consist of printable ASCII (code points 32-126), no newlines.
  • You can take input either as a string or as a list of chars (NOT 1-char strings). E.g. String/char[] or char* are allowed, but String[]/char[][] or char** aren't.

Test cases

Input
Output

Hello, World!
HdlroW ,olle!

Hello World!
H!llooW rlde

ABCDEFGHIJKLMNOPQRSTUVWXYZ
AZCXEVGTIRKPMNOLQJSHUFWDYB

 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
 }"{$y&w(u*s,q.o0m2k4i6g8e:c<a>_@]B[DYFWHUJSLQNOPMRKTIVGXEZC\A^?`=b;d9f7h5j3l1n/p-r+t)v'x%z#|!~

P
P

AB
AB

xyz
xyz

For the empty string, return the empty string itself.

\$\endgroup\$
  • 1
    \$\begingroup\$ Related. \$\endgroup\$ – Martin Ender May 27 '17 at 10:10
  • \$\begingroup\$ I remember this being a type of "secret code" (kind of like Pig Latin) that we learned as kids in 80's or 90's, something to do with the word "fence" or something, but my memory's a bit fuzzy. My friends and I would use this to encode secret messages, and I don't think the adults that found our letters ever did figure them out... \$\endgroup\$ – phyrfox May 28 '17 at 2:45
  • \$\begingroup\$ @phyrfox you may be thinking of the rail fence cipher, which is similar to this. \$\endgroup\$ – Carmeister May 29 '17 at 6:32
  • \$\begingroup\$ Ah I remember doing that. \$\endgroup\$ – 12Me21 Oct 13 '17 at 18:03

32 Answers 32

1
2
0
\$\begingroup\$

Jq 1.5, 84 bytes

[_nwise(2)|[_nwise(1)]]|transpose|map(map(values))|.[1]|=reverse|[transpose[][]]|add

Expanded

   [_nwise(2)|[_nwise(1)]] # make list of two character lists
 | transpose               # convert to list of two lists of characters
 | map(map(values))        # discard null
 | .[1] |= reverse         # reverse second list
 | [transpose[][]]         # transpose back to two lists and flatten
 | add                     # convert back to string

Try it online!

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Perl, 27 bytes

Includes +5 for -F lp

perl -F -lpe 's/.\K./$F[@F%-2-pos]/g' <<< "abcdefghi"

If you give STDIN without newline you can drop the l option

| improve this answer | |
\$\endgroup\$
1
2

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.