# Turn an integer n into a list containing it n times [closed]

Given an integer n as input, return a list containing n, repeated n times. For example, the program would take 5 and turn it into [5,5,5,5,5]. The elements need to be integers, not strings. No built-in functions that accomplish the task are allowed.

This is , so standard rules apply.

• @BrunoE That still doesn’t answer the why. Do you have an actual reason to ban built-ins? To quote xnor: In general, if your challenge is too simple to be interesting, it won't be saved by banning things.
– lynn
Commented Aug 21, 2017 at 10:52
• @BrunoE while I agree with the sentiment, we prefer objectivity here at ppcg. Either something is or is not valid, opinions shouldn't come into the equation. Commented Aug 21, 2017 at 11:57
• @BrunoE The specs must be made such that one can indisputably decide whether an entry is valid or not. Please share your thoughts on the existing answers and make the specs more objective when it comes to built-in. Commented Aug 21, 2017 at 12:42
• I'm still confused what counts as a "built-in" for this task. Is Python's * operator ok? What's an example of a built-in that isn't ok? Commented Aug 22, 2017 at 7:14
• I am suprised nobody has mentioned this yet, but we have a sandbox for challenges where you can post them to get feedback on them, before they go live. This way you might've prevented discussing the rules of the challenge while others already submitted their answers.
Commented Aug 23, 2017 at 6:34

# Jelly, 1 byte

x


Try it online!

Note that this is not the “repeat n n times” built-in — its function is more general than that. For example 4,5,6x1,2,3 equals [4, 5, 5, 6, 6, 6]. Given only one argument, Jelly just happens to use it as both the left and right argument for the supplied link, but this functionality is not inherent to x.

If this doesn’t count, there are various fun 2-byte alternatives:

x ṁ Ra Rị R» a€ oR oḶ oṬ oẊ Ḷị Ḷ» Ṭị Ṭ» Ẋị Ẋ» ị€ ṛ€ ȧ€ »€


etc.

• Well, yes. Every code golf answer is a collection of built-ins that accomplish the task. You might ban this answer if x did “all the work”, but it most certainly doesn’t — there’s an implicit “0 bytes” of link-parsing and array-coercion logic going on to turn this into repeat([n], n), which is exactly what other answers do.
– lynn
Commented Aug 21, 2017 at 10:48
• @Adám This is the "repeat each element of x y times" function, taking 2 arguments. What makes it accomplish the task is how Jelly parses implicit arguments, which has nothing to do with the function itself. Commented Aug 21, 2017 at 12:07
• If this answer is invalid then the constraint of the question is not "No builtins" it is "No 1 byte answers", which is an extremely arbitrary limitation that seems counterproductive in code golf. Commented Aug 21, 2017 at 13:44
• I think an argument towards this not being a built-in is that there are two other 1 byte answers in Jelly that do the same thing ṁ and ẋ so this answer could be any one of the three. There aren't 3 built-ins (one would hope) for "repeat n n times", so they can't ALL be a "built-in" for it. Commented Aug 21, 2017 at 14:03
• This whole comment thread seems a good argument for not banning something as subjective as builtins. Commented Aug 26, 2017 at 20:35

# Python 3, 14 bytes

lambda k:[k]*k


Try it online!

• What's wrong with just [n]*n?
– user56228
Commented Aug 23, 2017 at 3:19
• @paxdiablo That is a snippet. We can create either full programs or functions as per the meta consensus. Commented Aug 23, 2017 at 6:50

# Operation Flashpoint scripting language,  50  46 bytes

f={a=[];t=_this;while{count a<t}do{a=a+[t]};a}


Call with:

hint format["%1", 5 call f]


Output:

• Do you have post decrement, i--, and += in this? Commented Aug 21, 2017 at 13:51
• Why are the screenshots for this always in a barren desert? You should use a cool map for your screenshots :P. Commented Aug 21, 2017 at 15:42
• @MagicOctopusUrn Is that better? Commented Aug 21, 2017 at 15:53
• @Steadybox ahaha! Epic :P. Is that the town from left for dead? That looks like the church you start in kinda. Commented Aug 21, 2017 at 16:07
• I think the screenshots should be posted cropped to a smaller image. We don't need to see the map, and it distracts from the actual output. Commented May 10, 2018 at 20:13

# APL (Dyalog), 2 bytes

Five equally short solutions. Last two are courtesy of Zacharý.

⍴⍨


Try it online!

⍴ cyclically reshape

⍨ self

/⍨


Try it online!

/ replicate

⍨ self

\⍨


Try it online!

\ expand

⍨ self

⌿⍨


Try it online!

⌿ replicate along first (and only) axis

⍨ self

⍀⍨


⍀ expand along first (and only) axis

⍨ self

Try it online!

• @Uriel There's one more…
Commented Aug 21, 2017 at 11:12
• Both ⌿⍨ and ⍀⍨ work. Commented Aug 21, 2017 at 14:11
• Was it intentional that 'self' looks like a face? Commented Aug 21, 2017 at 16:12
• @geokavel I don't think so, but I also noticed it as a typed this post. Makes it pretty mnemonic, no? In fact, selfie is one of its semi-official names, so in the RIDE interface to Dyalog APL, you can insert ⍨ by typing selfie.
Commented Aug 21, 2017 at 18:18
• @sethrin TIO counts characters (and UTF-8 bytes where applicable), but it is up to the user to ensure that they do not use any characters that are missing from a single-byte character set (SBCS). For APLs, see here.
Commented Aug 22, 2017 at 19:20

# Mathematica, 10 bytes

#~Table~#&


# Proton, 8 bytes

n=>[n]*n


Try it online!

• This combines the best of the python answer and the javascript answer, I love it! Commented Aug 21, 2017 at 10:48

# Octave, 12 bytes

@(n)~(1:n)+n


Try it online!

• What does the ~ in octave, because that's the only part of your code I don't understand.. Commented Aug 24, 2017 at 10:57
• @Michthan Sorry for late reply. ~ is the not operator that converts 1:n to an array of 0s of size n. You can use ! instead of it. Commented Aug 24, 2017 at 13:42

# JavaScript (ES6), 19 bytes

n=>Array(n).fill(n)


## Try it

o.innerText=(f=
n=>Array(n).fill(n)
)(i.value=8);oninput=_=>o.innerText=f(+i.value)
<input id=i type=number><pre id=o>

• An array without ... - whatever next?!
– Neil
Commented Aug 21, 2017 at 12:11
• @Neil: it felt wrong even as I was typing it! :D Commented Aug 21, 2017 at 17:05

# Pyth, 2 bytes

*]


Test suite.

*]QQ - Full program with implicit input

]   - Turn the input into a list.
*    - Repeat it a number of times equal to the input.


f n=n<$[1..n]  Try it online! Usage: f 5 yields [5,5,5,5,5]. For n=5, [1..n] yields the list [1,2,3,4,5]. n<$ replaces each element of this list with n.

• Mine's a bit longer, but I like it anyway: join replicate Commented Aug 23, 2017 at 0:13
• @amalloy This would indeed be the clean Haskell way to do it. However, join is not part of Prelude and thus requiers a lengthy import Control.Monad, which rarely makes it useful for golfing. Commented Aug 23, 2017 at 8:42

# R, 18 bytes

array(n<-scan(),n)


Try it online!

• Is rep(n<-scan(),n) too close to a builtin? Commented Aug 21, 2017 at 16:37
• @RobinGertenbach Maybe you should post it as a separate answer. Commented Mar 24, 2018 at 22:05

# 05AB1E, 2 bytes

Fˆ


Try it online!

• Nice, better than .D). Commented Aug 21, 2017 at 15:40
• @MagicOctopusUrn: Yeah, that was my first thought. Commented Aug 21, 2017 at 15:53

# Dodos, 76 bytes

	f f r 2
2

r
r d
f s t f
d
dip f s t
f
t
dot f
dot
s
s dip
f
dab


Try it online!

# Explanation:

f is an alias for dab (tail).

s is subtraction, as explained on the wiki: (x, y) → (0, y−x) when x ≤ y.

t maps (a, b, c…) to (b+c+…, a+b+c+…).

f s t maps (a, b, c…) to a. This is our “head” function.

d dips only the head of its argument: (a, b, c…) → (|a−1|, b, c…)

r is the main repetition logic. We map (a, b) to (*r(|a−1|, b), b).

For example, r(4, 7) will evaluate as

  r(4, 7)
= r(3, 7), 7
= r(2, 7), 7, 7
= r(1, 7), 7, 7, 7
= r(0, 7), 7, 7, 7, 7
→ This would call r(1, 7), but (1, 7) ≥ (0, 7), so surrender!
= 0, 7, 7, 7, 7, 7.


Finally, we define 2, which maps n → (n, n), and define main as f f r 2, computing r(n, n) and chopping off the first two elements.

# Japt, 2 bytes

ÆU


Test it

## Explanation

Implicit input of integer U. Generate an array of integers from 0 to U-1. Fill it with U. Implicit output of resulting array.

# TeX, 81 bytes

\newcommand{\f}[1]{#1\count0=2\loop,#1\advance\count0 by1\ifnum\count0<#1\repeat}


## Usage

\documentclass[12pt,a4paper]{article}
\begin{document}

\f{5}

\f{10}
\end{document}


• That's actually LaTeX. In Tex it'd be much shorter. Commented Sep 8, 2017 at 5:22

# Husk, 2 bytes

´R


Try it online!

´    -- Apply next function twice to same argument
R   -- given an integer n and some element, replicate the element n-times


### Polite alternative (3 bytes)

ṠIR


Try it online!

replicate>>=id


Thanks to @nimi, I don't need any import anymore. Yay!

It's a function that takes an integer argument; for example, the following returns [5,5,5,5,5]:

(replicate>>=id) 5

• Why not id=<<replicate? It's also 14 bytes but doesn't need the import.
– nimi
Commented Aug 21, 2017 at 22:44
• @nimi Very good point! Overlooked that possibility. (I really need to dive into the arrow monad more...) Commented Aug 22, 2017 at 7:31

# Java (OpenJDK 8), 50 48 bytes

n->java.util.Arrays.stream(new int[n]).map(i->n)


Try it online!

-2 bytes thanks to @Jakob

Inspired by the comments in @OlivierGrégoire's post, and optimized a little further. Takes an integer input, creates an IntStream of n elements, then maps each element to n and returns it.

• You can save 2 bytes by starting with java.util.Arrays.stream(new int[n]). Commented Aug 21, 2017 at 19:23

# Perl 5, 18 14 bytes

-4 bytes thanks to @DomHastings

sub{(@_)x"@_"}


Try it online!

Is x a builtin that does the entire task? Sort of? Not really? Rules unclear?

Edit: Yeah, probably it's fine.

• Had pretty much the same, but you can change the first $_[0] to @_! Also the second can be"@_" I think... Commented Aug 21, 2017 at 13:10 • I would say it doesn't count as a built-in because you have to work around the fact that it takes two inputs instead of one. Commented Aug 21, 2017 at 16:07 • Why not $_=$_ x$_ with perl -pe?
– Thor
Commented Aug 22, 2017 at 6:45
• @Thor x does string repetition, not list repetition, unless the left operand is in parentheses (or is a qw operator) and the x is evaluated in list context. And of course $_ is a scalar, not a list. Commented Aug 22, 2017 at 23:24 • @Thor I wouldn't count that as satisfying "return a list". Commented Aug 23, 2017 at 22:54 # J, 2 bytes $~


Same as the APL answer: reflexively shape the input. In other words:

$~ y y$ y
NB. y copies of y


# Brainbash, 39 bytes

>-[-[-<]>>+<]>->#[->+>+<<]>>[-<;<<.>>>]


Try it online!

Prints N N times. Works by generating 32, taking input, then duplicating the input twice, then output the first for each 1 in the second.

# C (gcc), 55 bytes

int*f(k){int*r=malloc(k*4),a=k;for(;a-->0;)r[a]=k;k=r;}


Try it online!

Returns a list of k integers.

• Yay "long arrow operator". Also, I didn't think gcc would ever use register eax for locals. Go figure. Commented Aug 21, 2017 at 12:22
• You can save 2 bytes by removing a comparison to 0 in for cycle, unless I've overlooked something. Commented Aug 21, 2017 at 15:45
• Suggest *f(k){int r[k], instead of int*f(k){int*r=malloc(k*4), Commented Aug 22, 2017 at 20:39

# Röda, 10 bytes

{[[_]*_1]}


Try it online!

Explanation:

{[[_]*_1]}
{        } /* Anonymous function   */
_       /* The input (_1)       */
[ ]      /* As a list            */
*_1   /* Repeated _1 times    */
[      ]  /* Pushed to the stream */

• Why can you leave off the 1 in the first input but not the second? Commented Aug 21, 2017 at 22:20
• @ConorO'Brien Each underscore without a number has a number that is one larger than the previous: [_]*_ = [_1]*_2. Because the first underscore is the first, it has automatically the number 1. Commented Aug 22, 2017 at 5:29

# Groovy, 9 bytes

{[it]*it}


Try it online!

Perhaps the most competitive groovy answer I've done to date.

# brainfuck, 16 bytes

[->+>+<<]>[->.<]


Try it online!

## The breakdown:

[->+>+<<]          Duplicate 'n' into the next 2 cells to the right
>         Move to the first duplicate
[->.<]   Print 'n', 'n' times


As I'm sure you're aware, brainfuck takes input and output values as ASCII characters. So a ! is represented as the value 33.

• Your program doesn't take input, I don't think. Unless you're talking about a value left on the tape Commented Aug 21, 2017 at 22:26
• @ConorO'Brien The ladder. Think of it as a function more than a program. Commented Aug 21, 2017 at 22:27

# Coreutils, sed, 14 bytes

yes $1|sed$1q


As a zsh function, 20 19 bytes:

f(){yes $1|sed$1q}


Try it online!

• I don't think this answer is valid, since it doesn't take input. Commented Aug 21, 2017 at 13:14
• @DJMcMayhem: used it in a function
– Thor
Commented Aug 21, 2017 at 14:08
• Why not just make it a program yes $1|sed$1q? Commented Aug 21, 2017 at 20:54
• Good point @DigitalTrauma, updated
– Thor
Commented Aug 22, 2017 at 6:39
• The rules say it has to be integer elements, not string elements. To satisfy that, a bash/zsh answer would need to use declare -i integer variables. But it also has to be an array. I'm not sure bash even supports an integer array (like eval declare -ia "\$1" to use the first function arg as the name of an array return value.) I upvoted this because it follows the spirit of the question; I doubt the question meant to exclude languages that don't really have integer lists / arrays. Commented Aug 23, 2017 at 21:05

# Ruby, 10 characters

->n{[n]*n}


Sample run:

irb(main):001:0> ->n{[n]*n}[5]
=> [5, 5, 5, 5, 5]


Try it online!

### Ruby, 18 characters

->n{Array.new n,n}


Sample run:

irb(main):001:0> ->n{Array.new n,n}[5]
=> [5, 5, 5, 5, 5]


Try it online!

# MATL, 4 3 bytes

tY"


Try it online!

Explanation:

t       % duplicate elements
Y"      % replicate elements of array
% (implicit) convert to string and display


# Java (OpenJDK 8), 58 56 bytes

n->{int a[]=new int[n],i=n;for(;i-->0;)a[i]=n;return a;}


Try it online!

-2 bytes thanks to @KevinCruijssen

• Two bytes shorter: n->{int a[]=new int[n],i=n;for(;i-->0;)a[i]=n;return a;} Commented Aug 21, 2017 at 11:15
• @KevinCruijssen Ouch, it hurts I didn't think about that... Thanks! Commented Aug 21, 2017 at 11:58
• Happens to the best of us. ;) If you look in my answer history you'll probably also find some answers where I add something along the lines of "bytes saved thanks to ... due to a stupid mistake by myself / something obvious I forgot.." :) Commented Aug 21, 2017 at 12:01
• I thought about an answer like IntStream.generate(() -> n).limit(n) but decided it wasn't worth typing up and upvoted this instead :) Commented Aug 21, 2017 at 12:42
• @JollyJoker You could do it! It's indeed two bytes shorter and would easily beat my answer ;-) Commented Aug 21, 2017 at 12:57

# cQuents v0, 3 bytes

::n


Try it online!

## Explanation

::    Mode: sequence 2. Given input n, output the sequence n times
n   Each item in the sequence is n

• Note current version uses & instead of :: Commented Feb 1, 2019 at 4:51