Given a string, your task is to collapse it into a zigzag-like structure as described below.
Folding into a Zigzag
We'll take the string "Mississippi"
as an example:
First, output the longest prefix consisting of unique characters only:
Mis
When you reach the first duplicate character C, ignore it, and output the longest prefix consisting of unique characters of the remaining string (
issippi
) vertically, below the first occurrence of C:Mis i s
Repeat the process, alternating between horizontal and vertical continuation. But now be careful (at step 1) to continue outputting horizontally from latest occurrence of the duplicate character, which is not necessarily the last one, as in this case:
Mis i sip ----- Mis i sip i
Rules
- The string will only contain printable ASCII characters, but won't contain any kind of whitespace.
- You can compete in any programming language and can take input and provide output through any standard method and in any reasonable format1, while taking note that these loopholes are forbidden by default. This is code-golf, so the shortest submission (in bytes) for every language wins.
- 1 Input: String / List of characters / whatever else your language uses to represent strings. Output: Multiline string, list of strings representing lines or list of lists of characters/length-1 strings, but please include a pretty-print version of your code in your answer, if possible.
- Regarding additional spaces, the output may contain:
- Leading / trailing newlines
- Trailing spaces on each line / at the end
- A consistent number of leading spaces on each line
- You must begin to output horizontally, you may not start vertically.
Test cases
Inputs:
"Perfect" "Mississippi" "Oddities" "Trivialities" "Cthulhu" "PPCG" "pOpOpOpOpOpOp" "ABCCCE" "ABCCCECCEEEEC" "abcdcebffg" "abca" "AAAAAAAA"
Corresponding outputs:
Perf c t
Mis i sip i
Od ies t
Triv a l ies t
Cthul u
P C G
pO OpO pOp p
ABC C E
ABC CCE E EC
abcd e b fg
abc
A AA A
b
, as you should only consider duplicates in the remaining string, that is, after "branching". Once you reach the secondc
, you output the longest prefix of unique chars of the remaining string, which isebffg
(thus outputtingebf
vertically and continuing horizontally after that), so you don't have to worry about the characters from the part of the string that was already outputted before switching orientation. If it still feels unclear to you, I'll make another step-by-step example with this test case. \$\endgroup\$ABCcde
\$\endgroup\$"A" ≠ "a"
. The output forABCcde
would just beABCcde
\$\endgroup\$AAAAAAAA
\$\endgroup\$