63
\$\begingroup\$

Super simple challenge today, or is it?

I feel like we've heard a fair bit about double speak recently, well let's define it in a codable way...

Double speak is when each and every character in a string of text is immediately repeated. For example:

"DDoouubbllee  ssppeeaakk!!"

The Rules

  • Write code which accepts one argument, a string.
  • It will modify this string, duplicating every character.
  • Then it will return the double speak version of the string.
  • It's code golf, try to achieve this in the smallest number of bytes.
  • Please include a link to an online interpreter for your code.
  • Input strings will only contain characters in the printable ASCII range. Reference: http://www.asciitable.com/mobile/

Leaderboards

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

var QUESTION_ID=188988;
var OVERRIDE_USER=53748;
var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(d){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+d+"&pagesize=100&order=asc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(d,e){return"https://api.stackexchange.com/2.2/answers/"+e.join(";")+"/comments?page="+d+"&pagesize=100&order=asc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){answers.push.apply(answers,d.items),answers_hash=[],answer_ids=[],d.items.forEach(function(e){e.comments=[];var f=+e.share_link.match(/\d+/);answer_ids.push(f),answers_hash[f]=e}),d.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){d.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),d.has_more?getComments():more_answers?getAnswers():process()}})}getAnswers();var SCORE_REG=function(){var d=String.raw`h\d`,e=String.raw`\-?\d+\.?\d*`,f=String.raw`[^\n<>]*`,g=String.raw`<s>${f}</s>|<strike>${f}</strike>|<del>${f}</del>`,h=String.raw`[^\n\d<>]*`,j=String.raw`<[^\n<>]+>`;return new RegExp(String.raw`<${d}>`+String.raw`\s*([^\n,]*[^\s,]),.*?`+String.raw`(${e})`+String.raw`(?=`+String.raw`${h}`+String.raw`(?:(?:${g}|${j})${h})*`+String.raw`</${d}>`+String.raw`)`)}(),OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(d){return d.owner.display_name}function process(){var d=[];answers.forEach(function(n){var o=n.body;n.comments.forEach(function(q){OVERRIDE_REG.test(q.body)&&(o="<h1>"+q.body.replace(OVERRIDE_REG,"")+"</h1>")});var p=o.match(SCORE_REG);p&&d.push({user:getAuthorName(n),size:+p[2],language:p[1],link:n.share_link})}),d.sort(function(n,o){var p=n.size,q=o.size;return p-q});var e={},f=1,g=null,h=1;d.forEach(function(n){n.size!=g&&(h=f),g=n.size,++f;var o=jQuery("#answer-template").html();o=o.replace("{{PLACE}}",h+".").replace("{{NAME}}",n.user).replace("{{LANGUAGE}}",n.language).replace("{{SIZE}}",n.size).replace("{{LINK}}",n.link),o=jQuery(o),jQuery("#answers").append(o);var p=n.language;p=jQuery("<i>"+n.language+"</i>").text().toLowerCase(),e[p]=e[p]||{lang:n.language,user:n.user,size:n.size,link:n.link,uniq:p}});var j=[];for(var k in e)e.hasOwnProperty(k)&&j.push(e[k]);j.sort(function(n,o){return n.uniq>o.uniq?1:n.uniq<o.uniq?-1:0});for(var l=0;l<j.length;++l){var m=jQuery("#language-template").html(),k=j[l];m=m.replace("{{LANGUAGE}}",k.lang).replace("{{NAME}}",k.user).replace("{{SIZE}}",k.size).replace("{{LINK}}",k.link),m=jQuery(m),jQuery("#languages").append(m)}}
body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;float:left}table thead{font-weight:700}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="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654"> <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><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><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> 

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

# Language Name, [Other information] N bytes

where N is the size of your submission. Other information may include flags set and if you've improved your score (usually a struck out number like <s>M</s>). N should be the right-most number in this heading, and everything before the first , is the name of the language you've used. The language name and the word bytes may be links.

For example:

# [><>](http://esolangs.org/wiki/Fish), <s>162</s> 121 [bytes](https://esolangs.org/wiki/Fish#Instructions)
\$\endgroup\$
  • 1
    \$\begingroup\$ It will modify this string. Are you intentionally requiring pass-by-reference and modify in-place? And then return a copy or reference to that modified string? If so, languages like asm or C would need to accept an explicit-length string (pointer + length) where the length is either the current string length (with the buffer being twice that size), or it's the total size and you need to duplicate the low half. Thus you need to start from the end and work backwards, or allocate scratch space and then copy back. But there are answers in C and 8086 asm that totally violate all that. \$\endgroup\$ – Peter Cordes Aug 3 '19 at 1:49
  • 3
    \$\begingroup\$ @PeterCordes I do not care if it modifies the same object or builds a new one. \$\endgroup\$ – AJFaraday Aug 3 '19 at 5:08
  • 2
    \$\begingroup\$ I'd suggest wording it as "modify (or produce a modified copy) of the string" to explicitly allow answers that do or don't modify in-place. Simplifying the wording to "return a string that's twice as long, with each character repeated" would be nice but then it's not clear if void foo(char *c, size_t len) is legal that takes one input/output buffer and a length, and doesn't have any return value, just a side-effect on the object it has a pointer to. \$\endgroup\$ – Peter Cordes Aug 3 '19 at 5:16
  • \$\begingroup\$ Can the string be empty? \$\endgroup\$ – cschultz2048 Aug 6 '19 at 19:58
  • 1
    \$\begingroup\$ @cschultz2048 it says the string will only contain printable ascii characters, so that implies that they’ll always be populated. I’d expect that any code for this challenge would leave an empty string empty... anyway, I don’t think it’s a test case that I’d use for this. \$\endgroup\$ – AJFaraday Aug 6 '19 at 22:36

145 Answers 145

2
\$\begingroup\$

PHP, 59 bytes

-1 bytes by @manatwork

function($g){foreach(str_split($g)as$v)$e.=$v.$v;return$e;}

Try it online!

Full program , 44 bytes

foreach(str_split(readline())as$v)echo$v.$v;

Try it online!

\$\endgroup\$
  • \$\begingroup\$ No need for the braces around foreach's block. \$\endgroup\$ – manatwork Aug 2 '19 at 10:28
  • \$\begingroup\$ If you are submitting as a function you do have to include the function declaration (anonymous is fine) in your byte count: 65 bytes. \$\endgroup\$ – 640KB Aug 4 '19 at 17:27
  • \$\begingroup\$ Though errors and notices are fine so you don't really need to initialize $e: 59 bytes. \$\endgroup\$ – 640KB Aug 4 '19 at 17:30
  • \$\begingroup\$ Oh, welcome to PPCG by the way! \$\endgroup\$ – 640KB Aug 4 '19 at 17:31
  • \$\begingroup\$ Thanks, I'm fixing my answer \$\endgroup\$ – Micio Informatico Aug 4 '19 at 17:33
2
\$\begingroup\$

Matlab >= r2015a, 16 bytes

@(x)repelem(x,2)

Credits to Giuseppe

Note: I haven't found an online interpreter for MATLAB; this answer correctly works with MATLAB r2015a.

Matlab <= r2014b, 23 bytes

@(x)char(kron(x,[1,1]))

Note: I haven't found an online interpreter for MATLAB; this answer correctly works with MATLAB r2014b.

\$\endgroup\$
2
\$\begingroup\$

Cubix, 9 bytes

oU;?Av/@o

Try it online!

Mapped onto a cube

    o U
    ; ?
A v / @ o . . .
. . . . . . . .
    . .
    . .

Watch it run

  • A Put all the input onto the stack
  • v Redirect around the cube and start of the print loop
  • o? Output the character for the stack value and test value
  • @ If test is negative (EOI), halt
  • Uo;/ If test is positive, u-turn to the left, output character again, pop from stack and reflect onto the start of the print loop.
\$\endgroup\$
2
\$\begingroup\$

Octave, 32 25 bytes

@(x)char(kron(x+0,[1,1]))

Try it online!

-7 bytes thanks to Giuseppe

\$\endgroup\$
2
\$\begingroup\$

Pip, 17 16 13 bytes

Fi,#a{L2Oa@i}

Try it online!

\$\endgroup\$
  • \$\begingroup\$ (belatedly) You can save two more bytes by getting rid of the curly braces. \$\endgroup\$ – DLosc Dec 21 '19 at 9:00
2
\$\begingroup\$

Fortran (GFortran), 100 bytes

Another demonstration of fortran's concise and elegant string handling capabilities... not!!

Summary: declare S as a 99 character string. read S in string format '(A)'. iterate over the trimmed string length. print the i'th character a couple of times without a newline (TIL).

Try it Online!

character(99)S;read(*,'(A)')S;do i=1,len_trim(S)
write(*,'(A)',advance="no")S(i:i)//S(i:i);enddo;end
\$\endgroup\$
2
\$\begingroup\$

Pepe, 19 bytes

REEerEErReEeReEeree

Try it online!

Explanation:

REEe # Input as str -> (R)
rEE # Create loop labelled 0 -> (r)
  rReEe # Output as char -> (R)
        # r flag: don't pop
  ReEe # Output as char and pop -> (R)
ree # Loop while (R) != 0
\$\endgroup\$
2
\$\begingroup\$

K (ngn/k), 5 bytes

,/2#'

Try it online!


the above is an expression that will take (#) 2 copies of each (') letter and return a list where each element is a 2-char list, e.g.

("DD";"oo";"uu";"bb";"ll";"ee";"  ";"ss";"pp";"ee";"aa";"kk";"!!")

,/ is "join over", and flattens the list. we read the expression as "join over 2 take each string". with the string passed right-side we get:

  ,/2#'"Double speak!"
"DDoouubbllee  ssppeeaakk!!"
\$\endgroup\$
  • \$\begingroup\$ {2}# works too. see other answers \$\endgroup\$ – ngn Aug 20 '19 at 15:18
2
\$\begingroup\$

Perl 6, 13 11 bytes

{S:g{.}x=2}

Try it online!

Anonymous code block that takes a string and returns a string by replacing each character with twice of itself.

\$\endgroup\$
2
\$\begingroup\$

Forth (gforth), 39 bytes

: f bounds ?do i 1 type i 1 type loop ;

Try it online!

Beats NieDzejkob's submission by one byte. If we don't care empty strings, we can safely remove the ? in ?do, making it 38 bytes.

A function that takes a string in the standard representation (addr, length), and prints the result to the console.

How it works

gforth documentation about bounds

: f ( addr len -- )
  bounds ?do        \ Iterate through char addresses..
    i 1 type        \   Print one char at the address
    i 1 type        \   One more time
  loop ;            \ End loop
\$\endgroup\$
2
\$\begingroup\$

Backhand, 5 bytes

i}o: 

Try it online!

(note the trailing space) This should be the optimal answer, since all of io: are needed, 4 bytes needs at two movement modifiers to avoid getting stuck in two instruction loops, and no three byte permutation works.

Explanation:

i       Input
   :    Dupe
  o     Output
 }      Move back to output
  o     Output
   :    Unnecessary dupe
i       Beginning of loop again

Of course, for a suboptimal but ironic answer you could do:

vvii::oooo22jj

Try it online!

Which doubles up on every character.

\$\endgroup\$
2
\$\begingroup\$

SWI-Prolog, 87 bytes

I did not see any Prolog attempt, so I tried to make one.

d([A|X],[A,A|Y]):-d(X,Y). d([],[]). p(X,W):-string_codes(X,Y),d(Y,Z),string_codes(W,Z).

The predicate to be called is p:

?- p("Hello world!", X)

It produces (in SWI-Prolog online interpreter):

X = "HHeelllloo wwoorrlldd!!";

Explanation

The code uses two different predicates: the first one (d) works with a list and duplicates every element in it.

d([A|X], [A,A|Y]) :- d(X, Y).
d([],[]).

As most of Prolog's predicates, it uses recursion to implement iteration over elements: the first line is the recursive step, while the second is the base step. Duplication is obtained by forcing the head of the first argument to be equal to the "2-elements-head" of the second argument.

Unluckily, this is not enough to work with strings: in fact, predicate p serves as converter between strings and lists.

p(X,W) :- string_codes(X,Y), d(Y,Z), string_codes(W,Z).

Due to library names, this second predicate extends the solution by at least 22 unnecessary characters... So, if anyone could suggest me a way to get rid of those, or any general solution improvement, I'd be very grateful ^^

Note that you can still use d in a sort of "raw-mode", reducing the solution length to 35 bytes. However, the input is technically not a string.

?- d(['H','e','l','l','o',' ','w','o','r','l','d','!'],X)

Try it online!

\$\endgroup\$
2
\$\begingroup\$

R, 61 bytes

function(x){paste0(rep(strsplit(x,"")[[1]],e=2),collapse="")}

Try it online!

\$\endgroup\$
2
\$\begingroup\$

MIT-Scheme 10.*, 52 bytes

(lambda(x)(string-map(lambda(y)(make-string 2 y))x))

MIT-Scheme 10.* apparently has the new string-map which simplifies my earlier approach listed below. The only difference is that make-string is used to convert the character argument into a string and duplicate it.

74 bytes

This is the older solution for MIT-Scheme 9.* before string-map was introduced.

(lambda(x)(list->string(append-map(lambda(k)(list k k))(string->list x))))

This is an anonymous lambda that takes the input as a string, converts it to a list so that it can be mapped (I don't know of another way to do the same), replicating each character and joining it together in one list, after which it is converted back into a string.

\$\endgroup\$
2
\$\begingroup\$

Acc!!, 42 bytes

N
Count i while _/32 {
Write _
Write _
N
}

Try it online!

Reads one character at a time into the accumulator and outputs the accumulator twice for each character. Loops until it encounters something with an ASCII code less than 32 (newline or EOF).

\$\endgroup\$
2
\$\begingroup\$

W j, 5 2 bytes

+M

If you want to specify your input, you need to split your input into a list of individual characters before you do your job. (If that disobeys the rules, I will implement a flag that does this job for the writer. (Flags don't count in bytecount.))

Say your input is abcdef. Find imps.py and change those variables:

read = [["a","b","c","d","e","f"]]

prog = '+M'

Explanation

Lots of implicit stuff here. Expanded program:

aaa+M

The + requires 2 inputs and M only provides a single input. Therefore two 'a''s are prepended.

The M only has 1 input required left, so a single 'a' is prepended.
a     % The Implicit input
    M % Map every item of this input with...
 aa   % This every item with this every item...
   +  % Concatenated together

% Implicit Output
j % Join the output without a separator

Wren, 24 bytes

Fn.new{|s|s.map{|n|n+n}}

Try it online!

For every item in the list, return every item concatenated with itself.

\$\endgroup\$
2
\$\begingroup\$

Forth, (GForth) 55 bytes

: d pad 80 accept 0 do pad i + c@ dup emit emit loop ;

Usage: d [enter]

This text will be doubled. [enter]

Online Forth interpreter

'accept' takes a line of up to 80 chars into pad, then the do loop fetches chars from the pad, duplicates them and emits them to the terminal.

\$\endgroup\$
2
\$\begingroup\$

Rexx (Regina), 41 bytes

I just realized the rules specifically state "It will modify this string, duplicating every character." Since the newline is part of the string, I will now leave it in the string and duplicate it, thus reducing my code size to 42 bytes (according to ls -l, TIO says 41).

b=''
DO 80
a=CHARIN()
b=b||a||a
END
SAY b

Try it online!

Old 60 byte version which strips newlines (or CRs depending on your OS.)

b=''
DO 80
a=CHARIN()
b=b||a||a
END
SAY LEFT(b,LENGTH(b)-2)

Alternate last line (same number of bytes):

SAY STRIP(b,,X2C('0a'))

Do 80 iterations, read a char into var a, concatenate two a's onto the end of b during each loop, output the string minus the two newlines or CRs (need to modify for AmigaOS/AROS because it uses CR-LF for line terminators.)

62 byte original version:

DO 80
a=CHARIN()
x=CHAROUT(,a)CHAROUT(,a)
END

Read up to 80 chars from stdin into string var a, write 'a' to stdout twice for each char read in.

\$\endgroup\$
1
\$\begingroup\$

Python 2, 31 bytes

Realised I was beaten to it already.

lambda s:''.join(c*2for c in s)
\$\endgroup\$
1
\$\begingroup\$

Ruby, 16 bytes

gsub /./m,'\0\0'

Requires -p.

Try it online!

Alternatively:

gsub(/./m){$&*2}

Try it online!

\$\endgroup\$
1
\$\begingroup\$

SNOBOL4 (CSNOBOL4), 69 bytes

	I =INPUT
S	I LEN(1) . X REM . I	:F(O)
	O =O X X	:(S)
O	OUTPUT =O
END

Try it online!

Prints with a single trailing newline.

\$\endgroup\$
1
\$\begingroup\$

kavod, 16 bytes

*>1+8?99.1-#<#0.

Try it online!

I picked up a random tarpit and decided this would be a nice challenge to solve

Explanation:

*     Take a byte of input and push to stack
>     Push to the register stack without popping from normal stack
1+    Add one to the input
8?    Go to the eighth character in the program if the top of the stack is nonzero (not EOF)
99.   Go to the 99th character in the program (terminating the program). This will be skipped over if input is not EOF
1-    Decrement TOS
#     Print with popping
<#    Get input back from register stack and print it
0.    Go back to the start of the program.
\$\endgroup\$
1
\$\begingroup\$

Charcoal, 5 bytes

⭆S⁺ιι

Try it online! Link is to verbose version of code. Explanation:

 S      Input string
⭆       Map over characters and join
   ι    Current character
  ⁺     Plus
    ι   Current character
        Implicitly print
\$\endgroup\$
1
\$\begingroup\$

PHP, 74 bytes

function doubleSpeaker ($s) {
    return preg_replace('/(.)/', '$1$1', $s);
}

Try it online!

\$\endgroup\$
  • 14
    \$\begingroup\$ Welcome to CGCC! The winning criteria for this challenge is code-golf which means submissions should attempt to have the smallest amount of bytes. This submission seems to have a lot of excess whitespace and unnecessarily long variable names. Additionally, you should add the language name and score to the header of your submission. \$\endgroup\$ – Jo King Jul 31 '19 at 23:48
  • 3
    \$\begingroup\$ Just in a few seconds, your solution was lowered to 41 bytes: Try it online! Nice RegEx idea by the way. \$\endgroup\$ – Night2 Aug 1 '19 at 9:23
  • 3
    \$\begingroup\$ Capturing is pointless. Try it online! \$\endgroup\$ – manatwork Aug 1 '19 at 9:30
  • 1
    \$\begingroup\$ Same idea as in my Lua answer btw, just implemented in PHP. \$\endgroup\$ – val says Reinstate Monica Aug 1 '19 at 9:39
  • 5
    \$\begingroup\$ Using @manatwork's update and $argn: Try it online! 36 bytes. \$\endgroup\$ – Night2 Aug 1 '19 at 9:48
1
\$\begingroup\$

Kotlin, 47 bytes

{(0..it.length-1).fold(""){s,c->s+it[c]+it[c]}}

Try it online!

\$\endgroup\$
1
\$\begingroup\$

3var, 10 bytes

k'>|[PP'>]

Try it online!

\$\endgroup\$
1
\$\begingroup\$

JavaScript (V8), 28 bytes

s=>[...s].map(n=>n+n).join``

Try it online!

\$\endgroup\$
1
\$\begingroup\$

4, 21 bytes

3.6000180070050050094

Try it online!

Explanation

3.          Start the program
6 00 01     Set memory cell 00 to 1 (BF +)
8 00        Start a loop while memory cell 00 is non-zero
7 00        Feed input to memory cell 00 (BF ,)
5 00 5 00   Print input 2 times ("a" -> "aa")
9           Jump to the corresponding 8       
\$\endgroup\$
1
\$\begingroup\$

Agda, 110 Bytes

Sorry, no online interpreter available because this is more of a proof checker.

So this was quite annoying since I tried not to use the standard library and thus had to explicitly define lists. Chars also don't exist by now, but the function is polymorphic, so it would work in this case.

data L(A : Set): Set where
 N : L A
 C : A → L A → L A
d :{A : _}→ L A → L A
d N = N
d(C x y) = C x(C x(d y))
\$\endgroup\$
1
\$\begingroup\$

SimpleTemplate, 23 bytes

This answer is for a language I wrote, which was supposed to be for templates but hasn't seen many updates.

This is the basic "split, loop, output twice", but without the splitting.

{@eachargv.0}{@echo_,_}

And now, ungolfed:

{@each argv.0 as char}
    {@echo char, char}
{@/}

And an explanation:

  • {@each argv.0 as char}
    Loops over each value in argv.0, which is the first argument given when calling the render() method.
    Due to this, you can pass an array of characters or a simple string, and it will loop through it.
    The as char is optional and the default variable name is _.
    Whitespace is optional

  • {@echo char, char}
    Outputs char. Twice.
    Whitespace is optional

  • {@/}
    Closes the scope of the {@each ... }.
    This is optional, as the language was written to keep track of how many scopes were open and automatically closes all at the end.

Pretty simple, right?

You can try it on: http://sandbox.onlinephpfunctions.com/code/d008a116a051df131edf02533182c5305cf8e834
When trying, you can go to line 906 and change the variable between $golfed and $ungolfed to try both versions.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.