Escreva um programa ou função que duplique letras em uma palavra, para que todas as letras duplicadas organizadas da esquerda para a direita na palavra formem a matriz de entrada.
Por exemplo:
input: chameleon, [c,a,l,n]
output: cchaamelleonn
Entrada
- A palavra inicial (por exemplo
chameleon
)
- Uma matriz de caracteres (
[c,a,l,n]
) ou uma sequência para representar uma matriz ( caln
) ou algo semelhante
- A entrada pode ser feita através de parâmetros de função, STDIN ou equivalentes de idioma
- Todas as entradas serão minúsculas (az)
Saída
A palavra mudada
Se houver várias soluções, qualquer uma pode ser impressa
input: banana [n,a]
possible outputs: bannaana, banannaa
|-|---------|-|--->[n,a]
Você pode assumir que a palavra de entrada (não necessariamente a matriz) terá as letras na matriz (em ordem)
Você também pode assumir que as entradas não possuem letras consecutivas iguais (NÃO maçã, geek, verde, vidro, porta ...)
Exemplos
input: abcdefghij, [a,b,c]
output: aabbccdefghij
input: lizard, [i,a,r,d]
output: liizaarrdd
input: coconut, [c,o]
ouput: ccooconut or coccoonut or ccocoonut
input: onomatopoeia, [o,o,a,o,o]
output: oonoomaatoopooeia
input: onomatopoeia, [o,a,o]
output: oonomaatoopoeia or onoomaatoopoeia or oonomaatopooeia etc.
O programa mais curto vence!
Classificação (obrigado a Martin Büttner pelo trecho)
/* Configuration */
var QUESTION_ID = 51984; // Obtain this from the url
// It will be like http://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
/* App */
var answers = [], page = 1;
function answersUrl(index) {
return "http://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}
function getAnswers() {
jQuery.ajax({
url: answersUrl(page++),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
answers.push.apply(answers, data.items);
if (data.has_more) getAnswers();
else process();
}
});
}
getAnswers();
var SIZE_REG = /\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/;
var NUMBER_REG = /\d+/;
var LANGUAGE_REG = /^#*\s*([^,]+)/;
function shouldHaveHeading(a) {
var pass = false;
var lines = a.body_markdown.split("\n");
try {
pass |= /^#/.test(a.body_markdown);
pass |= ["-", "="]
.indexOf(lines[1][0]) > -1;
pass &= LANGUAGE_REG.test(a.body_markdown);
} catch (ex) {}
return pass;
}
function shouldHaveScore(a) {
var pass = false;
try {
pass |= SIZE_REG.test(a.body_markdown.split("\n")[0]);
} catch (ex) {}
return pass;
}
function getAuthorName(a) {
return a.owner.display_name;
}
function process() {
answers = answers.filter(shouldHaveScore)
.filter(shouldHaveHeading);
answers.sort(function (a, b) {
var aB = +(a.body_markdown.split("\n")[0].match(SIZE_REG) || [Infinity])[0],
bB = +(b.body_markdown.split("\n")[0].match(SIZE_REG) || [Infinity])[0];
return aB - bB
});
var languages = {};
var place = 1;
var lastSize = null;
var lastPlace = 1;
answers.forEach(function (a) {
var headline = a.body_markdown.split("\n")[0];
//console.log(a);
var answer = jQuery("#answer-template").html();
var num = headline.match(NUMBER_REG)[0];
var size = (headline.match(SIZE_REG)||[0])[0];
var language = headline.match(LANGUAGE_REG)[1];
var user = getAuthorName(a);
if (size != lastSize)
lastPlace = place;
lastSize = size;
++place;
answer = answer.replace("{{PLACE}}", lastPlace + ".")
.replace("{{NAME}}", user)
.replace("{{LANGUAGE}}", language)
.replace("{{SIZE}}", size)
.replace("{{LINK}}", a.share_link);
answer = jQuery(answer)
jQuery("#answers").append(answer);
languages[language] = languages[language] || {lang: language, user: user, size: size, link: a.share_link};
});
var langs = [];
for (var lang in languages)
if (languages.hasOwnProperty(lang))
langs.push(languages[lang]);
langs.sort(function (a, b) {
if (a.lang > b.lang) return 1;
if (a.lang < b.lang) return -1;
return 0;
});
for (var i = 0; i < langs.length; ++i)
{
var language = jQuery("#language-template").html();
var lang = langs[i];
language = language.replace("{{LANGUAGE}}", lang.lang)
.replace("{{NAME}}", lang.user)
.replace("{{SIZE}}", lang.size)
.replace("{{LINK}}", lang.link);
language = jQuery(language);
jQuery("#languages").append(language);
}
}
body { text-align: left !important}
#answer-list {
padding: 10px;
width: 50%;
float: left;
}
#language-list {
padding: 10px;
width: 50%px;
float: left;
}
table thead {
font-weight: bold;
}
table td {
padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="answer-list">
<h2>Leaderboard</h2>
<table class="answer-list">
<thead>
<tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
</thead>
<tbody id="answers">
</tbody>
</table>
</div>
<div id="language-list">
<h2>Winners by Language</h2>
<table class="language-list">
<thead>
<tr><td>Language</td><td>User</td><td>Score</td></tr>
</thead>
<tbody id="languages">
</tbody>
</table>
</div>
<table style="display: none">
<tbody id="answer-template">
<tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
</tbody>
</table>
<table style="display: none">
<tbody id="language-template">
<tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
</tbody>
</table>
[c,o,c,o]
, e não[c,o]
.#answer-list
e#language-list
largura50%
para evitar a sobreposição de colunas no seu snippet.bash
+sed
resposta): É ilegal parabanana, na
=>baannana
? Eu acreditava que "Você pode assumir que todas as entradas terão as letras na matriz (em ordem)" deve permitir , mas não exigir , respostas para processar as duas listas sequencialmente, mas o @manatwork a interpretou de maneira diferente.Respostas:
Pitão, 14 bytes
Demonstração.
Estilo de entrada:
Explicação:
fonte
Brainfuck,
4645 (63 com caracteres imprimíveis na entrada)Compatível com Alex Pankratov bff (intérprete brainfuck usado em SPOJ e ideone) e de Thomas Cort BFI (usado em Anarchy Golf).
A versão imprimível leva a matriz primeiro como uma sequência, seguida por uma guia, seguida pela sequência inicial sem uma nova linha à direita.
Demonstração em ideone.
Podemos salvar alguns bytes usando
\x00
como separador em vez de tab:fonte
CJam, 15 bytes
Experimente online.
Como funciona
fonte
C, 62 bytes
Well, this is surprisingly competetive.
We define a function
f(char*, char*)
that takes the string as its first input and the array of characters to duplicate as its second input.Some testing code:
Which prints:
Try it online!
If it is acceptable to submit a macro rather than a function, the following
#define g(s,c)
is just 58 bytes, but requiress
andc
to be actual pointers:fonte
CJam, 15 bytes
An alternative CJam approach. Try it online
Explanation
For each character in the second string, we do two things.
Split the current suffix of the string by the character, e.g.
"beeper" "e" -> ["b" "" "p" "r"]
Uncons the first string in the array, insert two of the character, then rejoin the rest of the array with the character, e.g.
"b" "ee" "eper"
. The last string is the new suffix.fonte
Retina, 33 bytes
More information about Retina.
This expects the two strings on STDIN, separated by a newline.
For counting purposes, each line goes into a separate file,
\n
should be replaced with an actual newline character (0x0A). If you actually want to test this, it's more convenient to put this in a single file where\n
remains as it is and then invoke Retina with the-s
option before passing the file.Explanation
(Outdated... I managed to get rid of the marker... I'll update this later.)
Each pair of lines is a regex substitution (first line the pattern, second line the substitution).
This puts a
#
as a marker at the start of the input string.This finds the first letter in the input (after the marker) corresponding to the next letter to be duplicated, duplicates that letter, moves the marker behind it, and drops the first character of the second string. The
+`
at the front tells Retina to do this repeatedly until the string stops changing (in this case, because the second string is empty and all required letters have been duplicated).Finally, we clean up the string by dropping the marker.
fonte
Python, 61
A greedy recursive solution. Saves to
b
whether the first letter of the strings
is the first letter of the stringl
of letters to double. If so, take one of that letter and prepend it to the recursive call with the rest ofs
, removing the first element froml
. If notb
, do the same but don't double the letter and don't remove froml
.The code checks
s[:1]==l[:1]
rather thans[0]==l[0]
to avoid an index-out-of-bounds error whens
orl
is empty.fonte
Prolog,
95837956 bytesExample:
returns
Edit: Saved 4 bytes thanks to Oliphaunt
Edit2: Saved 20 bytes using the deprecated
put/1
SWI-Prolog predicate instead ofwritef
. Saved one byte replacing the recursion end predicated([],_).
tod(_,_).
. Won't work if the ordering of the two definitions ofd
is swapped though, but we don't care about that in golfed code. Saved another 2 bytes removing the parenthesis aroundH=[A|T],put(A),d(S,T)
fonte
H=[A|T]
. Also, why not make it a little more readable by replacing the spaces with newlines?Python 2,
83747265 BytesNo real special tricks here.
x
is the string,y
is the array of characters that are duplicated.To clarify if this doesn't copy properly, the first indentation level is a space, the next is a tab.Edit 1: Saved 9 bytes by using string manipulation instead of pop().
Edit 2: Saved 2 bytes by using
-~
to incrementg
by 1.Edit 3: Saved 7 bytes by using
y[:1]
trick, thanks to xnor for this!Check it out here.
Properly formatted and explained:
fonte
y[:1]
.y=y[g:]
, so "quite a few" is quite an exaggeration.y[:1]==c
. Does that work?Excel VBA, 110 bytes
This is my first entry to CodeGolf so I hope this is ok.
You enter the input word in A1 and then the letters to be replaced in B1 and the resulting word is displayed in a message box.
fonte
Haskell, 42 bytes
Usage example:
How it works:
If one string is empty, the result is the first string. Else: if the first characters of the strings match, take it two times and append a recursive call with the tails of the strings. If the characters don't match, take the first character of the first string and append a recursive call with the tail of the first string and the same second string.
fonte
Pyth,
1817 bytesLive demo.
Saved 1 byte thanks to @Jakube.
Explanation:
Original version:
Live demo for original.
fonte
Javascript, 47 bytes
Taking advantage of some ES6 features.
fonte
onomatopoeia
,oao
?b.indexOf(d)==0
, try~b.search(d)
search
is only applicable on strings. Had to change b to an arrayPyth, 16 bytes
Try it online: Demonstration
This is quite hacky. Stack-based languages might have an advantage here.
Explanation
fonte
JavaScript ES6, 47 bytes
Assumes
s
is an array["c","a","l","n"]
fonte
><> (Fish),
6834 BytesYou can run it at http://fishlanguage.com/playground inputting the string as the initial stack (with " marks, i.e. "chameleon") and the array of extra letters as the input stack (no " marks i.e. caln).
Don't forget to press the Give button to seed the input stack.
EDIT: Halved it! :)
fonte
R, 119
Based on @Alex's answer, this one is a couple of bytes shorter:
Ungolfed:
fonte
Perl,
73625956Entirely new approach yields much better results. Still, I bet it can be shorter.
Call as
f('coconut', ['c','o'])
.For each character in the array, find the first occurrence and duplicate it, and turn everything up to it to uppercase. Then return the entire string, converted to lowercase.
EDIT: shaved a couple of more characters by getting rid of
shift
andpop
.The previous version:
fonte
foreach
keyword is actually a synonym for thefor
keyword, so you can use either.” – Foreach Loops.)for
hint. It's actually shorter now.Ruby,
5247 bytesSolution:
f=->(s,a){s.chars.map{|c|c==a[0]?a.shift*2:c}.join}
Example:
p f.call('banana', ['n','a']) # => "bannaana"
Explanation:
Proc form of a method which takes a string as the first argument, and an array of characters as the second argument. Maps a block onto an array of the characters in the string argument, which checks each character against first element of the comparison array, and if there is a match, removes the first element of the comparison array, and doubles it.
update
f=->s,a{s.chars.map{|c|c==a[0]?a.shift*2:c}*''}
fonte
s,a
. And*''
is equivalent to.join
. That's 5 bytes saved, but I still beat you by one (for now) :DPerl, 51 bytes
Input is provided via STDIN. First input is the starting word (e.g.
chameleon
), second input is the letters as a single string (e.g.caln
).The above is just an obfuscated (read "prettier") way of doing the following:
As we go through each letter, we replace from the start of the word up to the letter in the source word with just the new letter, and append the match (stored in
$&
) to our result. Since the match includes the letter and then gets replaced with the letter, each letter ends up appearing twice.Because STDIN appends a new line character to both of our inputs, we're guaranteed to capture the remnants of the full word on the last match, i.e. the new line character.
fonte
REGXY, 24 bytes
Uses REGXY, a regex substitution based language. Input is assumed to be the starting word and the array, space separated (e.g. "chameleon caln").
The program works by matching a character in the first string with the first character after a space. If this matches, the character is repeated in the substitution and the character in the array is removed (well, not appended back into the string). Processing moves on to the second line, which is just a pointer back to the first line, which causes processing to repeat on the result of the previous substitution. Eventually, there will be no characters after the space, at which point the second branch of the alternation will match, removing the trailing space from the result. The regex will then fail to match, processing is completed and the result is returned.
If it helps, the iterative steps of execution are as follows:
The program compiles and executes correctly with the sample interpreter in the link above, but the solution is perhaps a bit cheeky as it relies on an assumption in the vagueness of the language specification. The spec states that the first token on each line (before the /) acts as a label, but the assumption is that a null label-pointer will point back to the first command in the file with a null label (or in other words, that 'null' is a valid label). A less cheeky solution would be:
Which amounts to 27 bytes
fonte
JavaScript ES6, 72 bytes
This is an anonymous function that takes 2 parameters: the starting word as a string and the characters to stretch as an array. Ungolfed code that uses ES5 and test UI below.
fonte
Python 2, 77
Call as:
I may have got the byte count horribly wrong... Uses a mixture of spaces and tabs.
fonte
rs, 39 bytes
More information about rs.
There's already a Retina answer, but I think this one uses a slightly different approach. They were also created separately: when I began working on this one, that answer hadn't been posted.
Besides, this one is 6 bytes longer anyway. :)
Live demo and test suite.
fonte
JavaScript, 92 characters
Unobfuscated version:
fonte
R,
136128122 bytesThis creates an unnamed function that accepts a string and a character vector as input and prints a string to STDOUT. To call it, give it a name.
Ungolfed + explanation:
Examples:
Saved 8 bytes thanks to MickeyT and another 3 thanks to jja!
fonte
cat(p,sep='')
to output straight to STDOUT for a couplemessage(p)
is shorter.message
, that's awesome! Thanks! Edited to use your suggestion.Bash+sed, 51
Input from stdin; characters to be doubled as a single argument:
This works by constructing a sed program from
$2
and then executing it against$1
. The sed program replaces the first occurrence of each replacement letter with two copies of its uppercase version, and downcases the whole lot at the end. For the example above, the generated sed program ispretty-printed:
I use the uppercase to mark characters processed so far; this avoids re-doubling characters that have already been doubled, or applying a doubling earlier than the previous one.
Earlier version, before clarification that order of replacement list is significant (44 chars):
fonte
strtech na <<< banana
outputs “baannana”, but first an occurrence on “n” should be doubled, only after that an occurrence of “a”.Python,
5392 bytesFound my solution to be the same length in both Python 2 and 3.
EDIT: Man, fixing that case when doing multiple replaces of the same letter (while still using the same method) took a bit of work.
Python 2:
Try it here
Python 3:
fonte
Mathematica, 66 bytes
Example:
fonte
Lua,
767876755853 bytesNew, completely reworked solution with help from wieselkatze and SquidDev! come on guys, we can beat brainfuck :P
Explanation coming tommorow. Try it here.
Original solution: Saved 2 bytes thanks to @kirbyfan64sos!
Lua is a pretty terrible language to golf in, so I think I did pretty good for this one.
Code explanation, along with ungolfed version:
Try it here. (Outdated code but same concept, just less golfed, will update tommorow)
fonte
function f(x,y)
and afterprint(x)
, saving you two bytes.