Ubah bilangan bulat n menjadi daftar yang memuatnya n kali


15

Diberikan bilangan bulat nsebagai input, kembalikan daftar yang berisi n, nwaktu yang diulang . Misalnya, program akan mengambil 5dan mengubahnya menjadi[5,5,5,5,5] . Elemen-elemen harus bilangan bulat, bukan string. Tidak ada fungsi bawaan yang menyelesaikan tugas diizinkan.

Ini adalah , jadi aturan standar berlaku.


43
@ Bruno Itu masih belum menjawab alasannya . Apakah Anda memiliki alasan sebenarnya untuk melarang built-in? Mengutip xnor: Secara umum, jika tantangan Anda terlalu sederhana untuk menarik, itu tidak akan diselamatkan dengan melarang sesuatu.
Lynn

13
@ BrunoE sementara saya setuju dengan sentimen, kami lebih suka objektivitas di sini di ppcg. Entah ada sesuatu yang valid atau tidak, pendapat tidak boleh masuk ke dalam persamaan.
Skidsdev

5
@BrunoE Spesifikasi harus dibuat sedemikian rupa sehingga seseorang dapat memutuskan apakah entri itu sah atau tidak. Silakan bagikan pemikiran Anda tentang jawaban yang ada dan buat spesifikasi lebih objektif ketika datang ke built-in.
Tn. Xcoder

6
Saya masih bingung apa yang dianggap sebagai "built-in" untuk tugas ini. Apakah *operator Python baik- baik saja? Apa contoh built-in yang tidak ok?
Steve Bennett

8
Saya terkejut tidak ada yang menyebutkan ini, tetapi kami memiliki kotak pasir untuk tantangan di mana Anda dapat mempostingnya untuk mendapatkan umpan balik tentang mereka, sebelum mereka ditayangkan. Dengan cara ini Anda mungkin telah mencegah mendiskusikan aturan tantangan sementara yang lain sudah mengirimkan jawaban mereka.
JAD

Jawaban:


32

Jelly , 1 byte

x

Cobalah online!

Perhatikan bahwa ini bukann n built-in "repeat times" - fungsinya lebih umum dari itu. Misalnya 4,5,6x1,2,3sama dengan [4, 5, 5, 6, 6, 6]. Diberi hanya satu argumen, Jelly kebetulan menggunakannya sebagai argumen kiri dan kanan untuk tautan yang disediakan, tetapi fungsi ini tidak melekat padax .

Jika ini tidak masuk hitungan, ada berbagai alternatif 2 byte yang menyenangkan:

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

dll.


10
Baiklah. Setiap jawaban kode golf adalah kumpulan bawaan yang menyelesaikan tugas. Anda mungkin mencekal jawaban ini jika xmelakukan "semua pekerjaan", tetapi tentu saja tidak - ada "0 byte" implisit dari tautan-parsing dan array-paksaan logika untuk mengubah ini menjadi repeat([n], n), yang merupakan jawaban lain melakukan.
Lynn

8
@ Adám Ini adalah fungsi "ulangi setiap elemen xy kali", dengan mengambil 2 argumen. Apa yang membuatnya menyelesaikan tugas adalah bagaimana Jelly mem-parsing argumen implisit, yang tidak ada hubungannya dengan fungsi itu sendiri.
Erik the Outgolfer

6
Jika jawaban ini tidak valid maka kendala dari pertanyaan ini bukan "No builtins" itu adalah "No 1 byte Answers", yang merupakan batasan yang sangat sewenang-wenang yang tampaknya kontraproduktif dalam kode golf.
Kamil Drakari

8
Saya pikir argumen terhadap ini tidak menjadi built-in adalah bahwa ada dua jawaban 1 byte lain di Jelly yang melakukan hal yang sama dan jadi jawaban ini bisa salah satu dari ketiganya. Tidak ada 3 built-in (orang akan berharap) untuk "repeat n ntimes", jadi mereka tidak bisa SEMUA menjadi "built-in" untuk itu.
nmjcman101

6
This whole comment thread seems a good argument for not banning something as subjective as builtins.
trichoplax


19

Operasi 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]

Keluaran:


Apakah Anda memiliki post decrement i--,, dan +=dalam hal ini?
TheLethalCoder

3
Why are the screenshots for this always in a barren desert? You should use a cool map for your screenshots :P.
Magic Octopus Urn

2
@MagicOctopusUrn Is that better?
Steadybox

1
@Steadybox ahaha! Epic :P. Is that the town from left for dead? That looks like the church you start in kinda.
Magic Octopus Urn

1
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.
mbomb007

12

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…
Adám

1
Both ⌿⍨ and ⍀⍨ work.
Zacharý

2
Was it intentional that 'self' looks like a face?
geokavel

1
@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.
Adám

1
@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.
Adám



9

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..
Michthan

1
@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.
rahnema1

9

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>


3
An array without ... - whatever next?!
Neil

1
@Neil: it felt wrong even as I was typing it! :D
Shaggy

7

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. 

7

Haskell, 13 bytes

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.


3
Mine's a bit longer, but I like it anyway: join replicate
amalloy

@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.
Laikoni



5

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.


4

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.


4

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}
\newcommand{\f}[1]{#1\count0=2\loop,#1\advance\count0 by1\ifnum\count0<#1\repeat}

\f{5}

\f{10}
\end{document}

enter image description here


That's actually LaTeX. In Tex it'd be much shorter.
A Gold Man


4

Haskell (14 bytes)

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

1
Why not id=<<replicate? It's also 14 bytes but doesn't need the import.
nimi

@nimi Very good point! Overlooked that possibility. (I really need to dive into the arrow monad more...)
tomsmeding

4

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]).
Jakob

4

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...
Dom Hastings

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.
Brad Gilbert b2gills

Why not $_=$_ x$_ with perl -pe?
Thor

@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.
aschepler

1
@Thor I wouldn't count that as satisfying "return a list".
aschepler

3

J, 2 bytes

$~

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

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

3

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.


3

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.


1
Yay "long arrow operator". Also, I didn't think gcc would ever use register eax for locals. Go figure.
aschepler

2
You can save 2 bytes by removing a comparison to 0 in for cycle, unless I've overlooked something.
Jasmes

Suggest *f(k){int r[k], instead of int*f(k){int*r=malloc(k*4),
ceilingcat

3

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 */

1
Why can you leave off the 1 in the first input but not the second?
Conor O'Brien

1
@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.
fergusq


3

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
Conor O'Brien

@ConorO'Brien The ladder. Think of it as a function more than a program.
Graviton

3

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.
DJMcMayhem

@DJMcMayhem: used it in a function
Thor

Why not just make it a program yes $1|sed $1q?
Digital Trauma

Good point @DigitalTrauma, updated
Thor

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.
Peter Cordes

3

MATL, 4 3 bytes

tY"

Try it online!

Explanation:

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

2

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


1
Two bytes shorter: n->{int a[]=new int[n],i=n;for(;i-->0;)a[i]=n;return a;}
Kevin Cruijssen

@KevinCruijssen Ouch, it hurts I didn't think about that... Thanks!
Olivier Grégoire

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.." :)
Kevin Cruijssen

I thought about an answer like IntStream.generate(() -> n).limit(n) but decided it wasn't worth typing up and upvoted this instead :)
JollyJoker

1
@JollyJoker You could do it! It's indeed two bytes shorter and would easily beat my answer ;-)
Olivier Grégoire

2

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 ::
Stephen

Dengan menggunakan situs kami, Anda mengakui telah membaca dan memahami Kebijakan Cookie dan Kebijakan Privasi kami.
Licensed under cc by-sa 3.0 with attribution required.