Alternesting , es el acto de tomar una cuerda y anidarla entre corchetes. Así es como alternes una cuerda.
Para una cadena de longitud N , tome los caracteres N centrales y rodeelos entre paréntesis. Entonces, si nuestra cadena era
Hello world!
(12 caracteres), terminaremos con(Hello world!)
Luego, tome los
n-2
caracteres centrales restantes y enciérrelos entre corchetes. En este caso, los 10 caracteres centrales sonello world
, por lo que la siguiente iteración es:(H[ello world]!)
Mientras queden más de dos caracteres en el medio de la cadena, repita los últimos dos pasos, alternando entre
()
y[]
. Aquí están los últimos pasos:(Hello world!) (H[ello world]!) (H[e(llo worl)d]!) (H[e(l[l(o[ w]o)r]l)d]!)
Como solo quedan dos caracteres en el medio en la última iteración, nos detenemos. Nuestra cadena final es
(H[e(l[l(o[ w]o)r]l)d]!)
Observe cómo hay dos caracteres en los corchetes del medio. Esto sucede cuando la entrada tiene una longitud par. Si la entrada
Hello, world!
tuviera una longitud impar (por ejemplo, con una coma agregada), tendríamos solo un carácter en el medio:(H[e(l[l(o[,( )w]o)r]l)d]!)
Para el desafío de hoy, debe escribir un programa o función que tome una cadena como entrada y la alterne, generando la nueva cadena. Puede tomar entrada y salida en cualquier formato razonable que desee. La entrada siempre tendrá al menos un carácter y solo contendrá ASCII imprimible. También puede suponer que la entrada no contendrá paréntesis ni corchetes. Para los idiomas tradicionales, esto no debería importar demasiado, pero podría facilitarlo para algunos idiomas esotéricos.
Como de costumbre, esta es una competencia de código de golf , así que trate de hacer la respuesta más corta posible en el idioma que elija. ¡Que te diviertas!
Prueba IO
#Input #Output
"Alternesting is fun!" --> (A[l(t[e(r[n(e[s(t[in]g) ]i)s] )f]u)n]!)
"PPCG" --> (P[PC]G)
"Code-golf" --> (C[o(d[e(-)g]o)l]f)
"4 8 15 16 23 42" --> (4[ (8[ (1[5( [1]6) ]2)3] )4]2)
"a" --> (a)
"ab" --> (ab)
"abc" --> (a[b]c)
fuente
()
) or can we start with brackets ([]
)?()
HelloWorld
.Respuestas:
Python 3,
706965 bytes-1 byte thanks to @Uriel
-4 bytes thanks to @xnor
Try it online!
fuente
C,
143137135 bytesTry it online!
Explanation:
fuente
0
. Thus, you shouldn't need thek=i=0,
. I might be wrong. See this SO answerRetina, 52 bytes
Try it online! The first stage inserts pairs of parentheses between each pair of input characters, while the second and third stages correct alternate parentheses to brackets.
fuente
Sed, 78
Score includes +1 for
-r
option passed to sed.Try it online.
fuente
JavaScript (ES6),
6968 bytesTest cases
Show code snippet
fuente
V,
252625 bytes12 bytes off thanks to @DJMcMayhemTry it online!
Borrowed some of @udioca's ideas.
Also finally used the surround plugin included in V for an answer, although it may not have been the best way, who knows.The plugin does NOT want to be used.Hexdump:
Explanation:
fuente
;
instead of the lastf)
Try it online!()
and[]
is a byte shorter but way less coolHaskell,
9691817977 bytesTry it online!
fuente
(x:y)
and(init y)
.k==""=""
is shorter ask==""=k
.cycle["()","[]"]
to just"()[]"
: Try it online!cycle
is even shorter. You can still remove the parenthesis around(init y)
.k==""=k
to the end and change it to0<1=k
.Ruby,
7977 bytes-2 bytes thanks to @Value Ink
Try it online!
fuente
s.insert k=i*2,'(['[i%2];s[~k]+=')]'[i%2]
to save 2 bytes. Try it online!Javascript(ES6)
110105 bytesThanks to @powelles for reminding me about
x%y<1
.Thanks @Luke for
a-b?y:x
Show code snippet
The first thing in understanding this beast is ungolfing it:
Almost every line is a part of the golfed version, so stepping through:
Line 1: The function statement becomes an arrow function, renaming
input
toi
. Becomesi=>
.Line 2:
Array.from
is the new, proper way of converting a string into an array, and what we use in on this line. However along with it, the spread operator is a cheaper way than the old.split('')
way, to do it, which is what is used in the golfed version. Ends up as[...i]
.Line 3:
.map
loops through an array, giving you three arguments:item
(a
in the golfed),index
; golfed asb
, andbaseArray
orc
. While we only care aboutitem
andindex
, we keptbaseArray
(see line 4 for why). Golfs to.map((a,b,c,...)=>...
.Line 4: The variable
middle
, the or the argumentd
in the golfed version is created to save a few bytes when it is repeated. The argumentc
had to be kept for argumentd
to be created. Is converted to(...,d=i.length/2-1,...)
.Line 5: The variable
alternate
, or argumente
is used to check what character it was on "(" or "[" or if it was past the middle, ")" and "]".b%2<1
is equal tob%2==0
because it can't be anything less than 1, but 0 in this case. Equals(...,e=b%2<1)
.Line 6: A helper variable to allow me to convert the
ternary operators
toif
statements. Isn't anything in the actual codegolf.Lines 7-8: If the index is less than the middle of the string set the symbol to an alternation of "[" and "(". Equates to
d>b?e?'[':'(':...
.Lines 9-12: Else (if index is greater than middle), check if middle is a whole number, if so switch the alternation. Then set the symbol to an alternation of ')' and ']'. Obfuscated to
(d%1==0?!e:e)?')':']'
.Lines 13-15:If the in the middle set the symbol to an empty string. This doesn't apply to odd alternesters, because middle has a decimal. Becomes:
d==b?'':...
.Line 16: Joins the character array back into a string. Equates to
.join``
.Line 17: Returns the starting symbol "(" and the result. Correlates to
'('+...
.fuente
%2==0
to%2<1
and use[...i]
instead ofi.split
[..i] idea
, but I forgot about%2<1
thanks.b%2<1
could be replaced by!b%2
d==b?x:y
could becomed-b?y:x
andd%1==0
could become!d%1
.!d%1
only works with parentheses:!(d%1)
, and it doesn't shave off any bytes. I forgot that 0 was the only falsy number, for some reason I thought -1 was the falsy one. Correct me if I'm getting something wrong about the second one.Jelly,
2321 bytesTry it online!
-2 bytes thanks to @EricTheOutgolfer
fuente
ị
to the helper link for -2, like this:LHĊRị¶ç⁾)]żUFUż@ç⁾([$
SCALA,
140138 chars,140138 bytesI'm sorry I couldn't do better ... I'm sure there are many ways to improve it. Still:
Try it online!
Thanks for this challenge, that was quite hard for me.
EDIT : -2 bytes thanks to Mar Dev.
PS : I will ask something though. I understand why THIS CODE keeps duplicating the central char of my string if I have an odd length (I just don't check and add it twice, in both
l
andr
strings). But why do I get a pair of parenthesis when I try correcting it like THAT? I don't understand at all.fuente
i%2==0
toi%2<1
to save two bytes.Perl,
7774 (73 + 1) bytesRegular expressions are glorious things. Run with the
-p
command line flag.fuente
05AB1E, 31 bytes
Try it online!
Explanation
With examples for input:
abcd
/abcde
fuente
C++ 14,
154145 bytes[Recursive]
C++ 14, 177 bytes
[Iterative]
fuente
Pyth, 42 (!) bytes
Test it online! The input must be quoted.
Explanations
So basically I progressively remove the head and end of H (being the input string in the beginning) while concatenating the parentheses/brackets. G is just a boolean which remembers if I must use brackets or parentheses.
fuente
05AB1E,
4942 bytesTry it online!
fuente
PowerShell,
125119111 bytesTry it online!
Previous version*
*Thanks @Digital Trauma.
fuente
QuadR, 82 bytes
(81 bytes +1 for
≡
flag)Try it online!
fuente
AWK, 118 bytes
Tested with gawk, but it should work with any compliant awk interpreters
fuente
JavaScript, 101 bytes
Not a winner, but it was interesting to try the
replace
approach. This could definitely be improved, but it got out of hand quick...fuente
Java (OpenJDK 8), 124 bytes
Try it online!
Credits
fuente