Напишите программу или функцию, которая будет выводить данную строку в виде лестницы, записывая каждую часть слова, которая начинается с гласной на одну строку ниже предыдущей части.
Например:
Input: Programming Puzzles and Code Golf
Output: Pr P C G
ogr uzzl and od olf
amm es e
ing
вход
Строка, содержащая только буквы и пробелы.
Строка может быть передана через STDIN
аргументы функции или аргументы или что-нибудь эквивалентное
Буквы могут быть строчными или прописными.
Предполагается, что входы всегда следуют этим правилам, вам не нужно проверять правильность входных данных.
Выход
Каждый раз , когда гласный (т.е. a
, e
, i
, o
, u
или y
) встречается в слове, вы должны выводить остальные слова на следующей строке (встречается гласный включен), в правильном горизонтальном положении. Это правило является рекурсивным, что означает, что если в слове n гласных, оно будет записано в n + 1 строках.
Гласный должен быть написан в начале следующей строки, а не в конце предыдущей строки, когда он встречается.
Каждое слово начинается с первой строки и поэтому должно быть отформатировано независимо от других слов. Два слова разделены пробелом.
Если слово начинается с гласного, вы должны написать его, начиная со второй строки.
Контрольные примеры
- Входные данные:
Programming Puzzles and Code Golf
Выход:
Pr P C G
ogr uzzl and od olf
amm es e
ing
- Входные данные:
The quick brown fox jumps over the lazy dog
Выход:
Th q br f j th l d
e u own ox umps ov e az og
ick er y
- Входные данные:
aeiouy
Выход:
a
e
i
o
u
y
- Входные данные:
YEAh UppErcAsE VOwEls
Выход:
V
Y Upp Ow
E Erc Els
Ah As
E
- Входные данные:
If you only knew the power of the Dark Side
Выход:
kn th p th D S
If y onl ew e ow of e ark id
o y er e
u
счет
Это код-гольф , поэтому выигрывает самый короткий код.
The vowel should be written at the beginning of the next line, and not at the end of the previous line when one is encountered.
Подумав немного, я понимаю, что это означает, что переход к следующей строке должен произойти до того, как будет напечатана гласная, а не после, но, возможно, стоило бы сформулировать это так, чтобы это было понятно сразу - это заняло у меня некоторое время.Ответы:
Retina,
504434(+10)3230 bytesThanks to Dennis for saving 14 bytes by using actual control characters.
Based on this answer, I'm using ANSI escape codes to move the terminal cursor vertically. The
<ESC>
should be replaced with the control character 0x1B, and<VT>
with the vertical tab0x0B
. For simpler testing, you can also replace<ESC>
with\e
,<VT>
with\v
and feed the output throughprintf
.For counting purposes, each line goes in a separate file. However, for convenience it's simpler to just paste the code into a single file and invoke Retina with the
-s
option.The first replacement surrounds each vowel in
\v...#
, where the\v
shifts the cursor downward and the#
is a marker for the second step. Thei`
is Retina's notation for case-insensitive matching.The second step then repeatedly (
+`
) removes a#
from a word and puts ae\[A
at the end of the word which shifts the cursor upward. This stops once the string stops changing, i.e. when there are no more#
markers in the string.источник
printf
. Just replace\e
with the ESC byte (0x1b).CJam,
3936 bytesThe above is a reversible xxd dump, since the source code contains the unprintable character VT (code point 0x0b) and ESC (code point 0x1b).
Like this answer, it uses vertical tabs and ANSI escape sequences.
This requires a supporting video text terminal, which includes most non-Windows terminal emulators.
Test run
Before executing the actual code, we'll disable the prompt and clear the screen.
This makes sure the output is shown properly.
To restore the prompt, execute this:
How it works
We insert a vertical tab before each vowel to move the cursor down and sufficient copies of the byte sequence 1b 5b 41 (
"\e[A"
) after each space to move the cursor back to the first row.источник
unset PS1save
afterwards.Java, 428 bytes
I know, it's horrible. There's probably some chars that can be shaved of, but I'm too lazy to do that.
источник
int
variables (namelyi
,r
,p
,o
, andx
) where you initializel
andm
since they'll be given values later. You can also doString v="...",a[]=...;
and do the same as above forString u
. That should lower your score quite a bit.x++-~-p
Perl, 31 bytes
The above is a reversible xxd dump, since the source code contains the unprintable character VT (code point 0x0b) and ESC (code point 0x1b).
The code is 27 bytes long and requires the switches
040p
(4 bytes).The program requires a video text terminal that supports vertical tabs and ANSI escape sequences, which includes most non-Windows terminal emulators.
Test run
Before executing the actual code, we'll disable the prompt and clear the screen.
This makes sure the output is shown properly.
To restore the prompt, execute this:
How it works
perl -040p
automatically reads the input as space-separated tokens (-040
), saves each token in$_
(-p
) and executes the program.s/[aeiouy]/.$&/gi
performs a global, case-insensitive search in$_
for vowels and replaces each vowel by the control character VT (moves the cursor down), followed by the vowel itself.s
returns the number of replacements it made, so$\=".[A"x s...
saves multiple copies of the byte sequence 1b 5b 41 (moves the cursor up) in$\
, one for each vowel.At the end of the program, Perl automatically prints
"$_$\"
, because of the-p
switch.источник
C,
200190 bytesUngolfed:
It allocates a rectangular buffer (actually square), fills it with spaces and newlines, then traverses the given string. At the end it adds a null character to prevent trailing newlines.
Technically it's not a function since it contains globals; in fact it can't be called more than once (
j
andl
must be 0 at the start). To comply,i,j,k,l,M;
could be moved toint i,j=0,k,l=0,M;
at the start of the function.источник
char*t=malloc(M*M);
-->char t[M*M];
andfor(i=0;i<M*M;++i)
-->for(;i<M*M;++i)
char t[M*M]
?CJam, 47
Yeah, it's a bit long, but it's not "cheating" with ANSI codes :)
Try it online
The idea is to calculate a line number for each character (starting at 0, incrementing at vowels and jumping back to 0 at space), and then for each line, repeat the string but replace the characters that have a different line number with a space.
источник
K,
81727066 bytesWell, it's a start:
Usage Examples:
Edit 1:
Better. Made some surface level improvements:
Notably, I inverted the arguments for
?
when I perform the vowel search and thus eliminated the need for a lambda, did the same inversion with_
where I split words on whitespace, and I realized that~{" "?x}'x
is a really silly, overcomplicated way of saying" "=x
.Edit 2:
Another surface level tweak- negate
s
before applying it to the lambda, saving parens inside:Edit 3:
OK, let's take a different approach to calculating the offset for each character. Instead of splitting the sequence at spaces and calculating a running sum (
+\
) of the positions of vowels, we can operate on the whole input string in one pass, multiplying the running sum by 0 whenever we encounter a space. I need the negation of this sequence, so I can subtract instead of adding as I scan and use number-of-distinct (#?
) instead of max (|/
) when I calculate the amount of vertical padding.That saves another 4 characters. Phew!
источник
Ruby:
135131124115112 charactersSample run:
источник
/(?=[aeiouy ])/i
.C, 192 bytes
This iterates through the string, blanking characters as it prints them. It repeats until there are no non-space characters left to print. It's portable C, making no assumptions about character encoding.
Readable version
источник
' '
-->32
andf(char*s){int l=0,r=1,v,c;
-->l,r=1,v,c;f(char*s){
' '
may be32
, but it depends on the character encoding, and as I said, I made this portable C. Dropping the explicitint
is great, though - not sure why I forgot that!Python 3,
265207202185177 charactersThis is terrible and I'm not proud. I know this can be made shorter, but I thought I'd post anyway.
Inspired by the C version, it creates a list which is then filled while traversing the input string.
источник
GNU Sed, 151 + 1
(+1 as it needs the
-r
flag)I thought that sed would be the tool for this job, but found it surprisingly hard.
Readable version:
источник
p
, so it outputs nothing. A small issue is that outputs starts with an extra space. A huge issue is that first piece of text starting with vowel disappears.c
, due to the line just beforetx
. I've reinstated an earlier version with its similar loop, and I'll have another attempt later.Python 2,
145142 BytesProbably isn't as competitive as some other methods, but I thought this was a cool way of using regex.
The regex
(?!([^aeiouy ]*[aeiouy]){N}[^aeiouy]* ).
matches any single character not within the N-th group of letters from the end of a word. Since it counts from the end of the world I reverse the string before and afterward, and I also have to add a space at the end, but after that it becomes a simple matter of usingre.sub
to replace every instance of these characters with a space. It does this for every value of N until the string is empty.источник
re.I
, you can save 3 bytes by substituting the appropriate flag value, i.e.2
.Octave,
132129 charactersTest
Input:
"YEAh UppErcAsE VOwEls"
Output:
источник
Gema:
5348 charactersNote that
^[
(x1b) and^K
(x0b) are single characters. (In the below sample run I use their copy-paste friendly\e
and\v
equivalents, in case you want to try it out.)Sample run:
источник
Jelly, 42 bytes (non-competing?)
Try it online!
Why Jelly, why? :-(
источник