O desafio envolve simplesmente alternar uma string dentro de outra.
Explicação
Se a seqüência de alternância é uma substring da corda principal , remova todas as ocorrências da seqüência de alternância da corda principal ; caso contrário, anexe a string de alternância no final da string principal .
Regras
- Todas as strings são compostas por caracteres ASCII imprimíveis
- A função deve ter dois parâmetros: a sequência principal e a sequência de alternância .
- A cadeia principal pode estar vazia.
- A cadeia de alternância não pode estar vazia.
- O resultado deve ser uma sequência, que pode estar vazia.
- A resposta mais curta vence.
Exemplos
function toggle(main_string, toggle_string){ ... }
toggle('this string has 6 words ', 'now')
=> 'this string has 6 words now'
toggle('this string has 5 words now', ' now')
=> 'this string has 5 words'
Casos de testes
'','a' => 'a'
'a','a' => ''
'b','a' => 'ba'
'ab','a' => 'b'
'aba','a' => 'b'
'ababa', 'aba' => 'ba'
Respostas:
Geléia , 7 bytes
Experimente online!
Como funciona
fonte
Java 8,
80706534 bytesProvavelmente o meu 'codegolf' Java mais curto até agora .. xD
com alguma ajuda dos comentários ..;)
Explicação:
Experimente online.
fonte
if
para um ternário. Se nada mais, ele vai se livrar do "extra"return
.return m=m.replace(t,"")?m+t:m;
m==(m=m.replace...
MATL, 11 bytes
Experimente Online!
Todos os casos de teste
Explicação
fonte
Python 3, 38 bytes
fonte
JavaScript (ES6),
3937 bytesfonte
Pyke, 14 bytes
Experimente aqui!
Dado que Pyke não tem
else
estrutura, acho que essa é uma pontuação bastante razoávelExplicação:
fonte
CJam, 9
Experimente online. Obrigado jimmy23013 por cortar 1 byte :)
Explicação:
fonte
q~:B/2Be]
.Javascript (ECMAScript 6): 47 bytes
fonte
("a", ".")
returns""
instead of"a."
.Retina,
3831 bytesByte count assumes ISO 8859-1 encoding.
The trailing linefeed is significant. Input format is both strings separated with a linefeed.
Try it online! The first line allows running several test cases at once (for the test suite, use
;
to separate the strings and linefeeds to separate test cases; the first line takes care of the conversion).Explanation
In this first step we replace all occurrences of the toggle string in the main string with
·
. We need to insert these markers so that we can determine afterwards if any substitution happened.This is another substitution which removes a
·
marker, or the second line (including the separating linefeed). However, the1>
is a limit which means that only matches after the first are considered. Hence, if the toggle string did not occur in the main string, we won't have inserted any·
, so the second line will be the first match and won't be removed. Otherwise, we remove the second line along with all but the first marker.While this uses a transliteration stage, it's also used simply for removing characters. In particular, we move both
·
and linefeeds. We need the first one, in case there was a match (because then the first·
will have been left behind by the previous stage) and we need the second one in case there wasn't a match (to join the two lines together and thereby append the toggle string to the main string).fonte
Python (3.4):
55544744 BytesTesting:
The Test output
Using a def would be longer because you have to use a return statement, if it were possible without return it would save 2 BytesSince explicit declaration of the function is not needed (sorry I didn't know that) 7 Bytes were saved.fonte
toggle=
.toggle=
the Tests worktoggle
is needed to test it. But you only need to count fromlambda m,t:
on.m+''+t
tom+t
to save 3 bytes, if I'm not mistaken.m+' '+t
to enter a space between them, but after reading the description again I deleted the whitespace but not the '' and the +C#, 63
Better than Java :)
Test code:
Output:
fonte
Pyth,
131110 bytesTest suite.
Input format: first string in quotes, second string without quotes.
This is also 10 bytes:
Test suite.
This is 11 bytes:
Test suite.
Previous 13-byte solution:
Test suite.
fonte
?}zQ:Qzk+Qz
Jolf, 12 bytes
Ou, se precisarmos incluir caracteres sensíveis a expressões regulares:
Experimente aqui!
Explicação
fonte
JavaScript (ES6), 37 bytes
Um pouco menor do que a resposta do @ nobe4, aproveitando a divisão e a junção
fonte
Raquete, 70 bytes
Bem direto.
fonte
Scala,
7270 bytesOnline interpreter: www.tryscala.com
fonte
if(r==m)
.Oracle SQL 11.2, 66 bytes
fonte
Perl,
3730 bytesExpressões regulares dentro da cadeia de alternância não são avaliadas devido à citação com
\Q
...\E
.sub F
e\E
são removidos de acordo com o comentário por msh210.Não é totalmente livre de efeitos colaterais por causa da configuração
$_
. O uso de uma variável local custará seis bytes adicionais:Por outro lado, com os parâmetros de entrada comutados, dois bytes podem ser salvos usando em
pop
vez deshift
(28 bytes):Arquivo de teste:
Resultado do teste:
fonte
sub F
from your byte count. Also, you should be able to usepop
instead ofshift
(by reversing the order of the inputs, natch), saving two bytes. (Untested.) Finally, you should be able to omit the\E
, saving two more bytes. (Also untested.)pop
instead ofshift
can help, because$_
should be the first argument to avoid$_[1]=~s/.../
. The order of input arguments is fixed by the question AFAIK.C# (58 bytes)
string F(string s,string t)=>s==(s=s.Replace(t,""))?s+t:s;
It uses an inline assignment to shave a few bytes off
fonte
var s,t
orvar s,var t
instead ofstring
?var
can only be used in places where the type is known at compile time, so it can't be used in method signatures. You could usedynamic
, but it's 1 character longer thatstring
var F(string s, string t
? That can be inferred...bash + sed, 28 bytes
The script lives in a toggle-string.bash file, which we call with
bash toggle-string.bash mainstring togglestring
.s/$2//g
removes the toggle string from the main stringt
jumps to the end if the previous substitution was successful (ie. the main string contained the toggle string)/$/$2/
adds the toggle string at the end ($
), if we didn't jump to the endbash is required for the herestring
fonte
Julia,
3331 bytesTry it online!
fonte
PowerShell v2+, 47 bytes
Takes input
$a,$b
and then uses a pseudo-ternary(... , ...)[...]
statement to perform an if/else. The inner parts are evaluated first to form an array of two elements. The 0th is$a
with all occurrences of$b
-replace
d with nothing, which is stored into$c
. The 1st is just a string concatenation of$a
and$b
.If
$c
is-eq
ual to$a
, meaning that$b
wasn't found, that's Boolean$true
or1
, and so the 1st element of the array (the concatenation) is chosen. Else, it's Boolean$false
, so we output$c
, the 0th element.Note that
-replace
is greedy, so it will replace from the left first, meaning theababa / aba
test case will properly returnba
.fonte
Java 8, 65 bytes
The same logic as the Java 7 solution, written with a lambda.
Try it here
fonte
Ruby,
33 bytes27 bytes (28 if using global subtitution)definitely 28 bytesfonte
Mathematica, 45 bytes
Anonymous function that takes the main string and the toggle string (in that order) and returns the result. Explanation:
fonte
TSQL,
143129121 BytesReadable:
Live Demo
114 Bytes with strictly 1 character input
fonte
TSQL(Sqlserver 2012), 49 bytes
Try it online!
fonte
Ruby,
353728 bytesHooray for string interpolation! It even works in regexes. The rest is simple: if the string in
t
matches tom
, replacet
with''
, else returnm+t
.Edit: Fixed a bug.
Edit: I applied Kevin Lau's suggestion, but it appears that I have reached the same algorithm as the one used in Luis Masuelli's answer.
fonte
("a", ".")
returns"a"
instead of"a."
.m[t]
is much shorter thanm.include?(t)
and still checks for inclusion within strings.k (23 bytes)
Examples:
fonte
Kotlin, 61 Bytes
This is would be shorter if assignment was an expression in Kotlin,and parameters were mutable,and there was a ternary conditional operator, sadly this isn't the case :(
Try it Online!
UnGolfed
fonte