将整数n转换为包含n次的列表


15

给定一个整数n作为输入,返回包含的列表n,重复n一次。例如,程序将把5它变成[5,5,5,5,5]。元素必须是整数,而不是字符串。不允许使用内置函数来完成任务。

这是,因此适用标准规则。


43
@BrunoE仍然无法回答原因。您是否有禁止内置的实际理由?引用xnor:通常,如果您的挑战太简单而难以引起兴趣,则不能通过禁止事物来保存它。
林恩

13
@BrunoE虽然我同意这种观点,但在ppcg,我们更倾向于客观性。不管是有效还是无效,都不应将观点纳入方程式。
Skidsdev

5
@BrunoE 必须制定规范,以便人们可以毫无疑问地决定一项是否有效。请分享您对现有答案的看法,并使规范更加客观built-in
Xcoder先生17年

6
我仍然很困惑此任务的“内置”功能。Python的*运算符可以吗?内置的不合格示例是什么?
史蒂夫·贝内特

8
令我感到惊讶的是,还没有人提到这一点,但是我们有一个挑战沙箱,您可以在发布挑战之前将其发布以获取反馈。这样,您就可以避免在其他人已经提交答案的情况下讨论挑战规则。
JAD

Answers:


32

果冻,1字节

x

在线尝试!

请注意,这不是n n内置的“重复次数”,它的功能比这更通用。例如4,5,6x1,2,3等于[4, 5, 5, 6, 6, 6]。由于只有一个参数,果冻正好用它作为左,对于提供的链接右边的参数都,但这个功能不是固有的x

如果这不算数,那么会有各种有趣的2字节替代方案:

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

等等


10
嗯,是。每个代码高尔夫答案都是完成任务的内置集合。如果x“一切顺利”,您可能会禁止使用此答案,但是最肯定的不是-链接解析和数组强制逻辑会隐式地将“ 0字节”转换成repeat([n], n),这正是其他答案做。
林恩

8
@Adám这是“重复xy次的每个元素”功能,带有2个参数。使它完成任务的是Jelly如何解析隐式参数,这与函数本身无关。
暴民埃里克(Erik the Outgolfer)'17

6
如果此答案无效,则问题的约束条件不是“没有内置答案”,而是“没有1字节答案”,这是一个极其随意的限制,在代码高尔夫中似乎适得其反。
卡米尔·德拉科里

8
我认为关于这种说法不是内置的,是果冻中还有另外两个1字节的答案也可以做同样的事情因此,答案可能是三个答案中的任何一个。“重复n n时间” 没有3个内置函数(一个希望如此),因此它们不能全部成为它的“内置”函数。
nmjcman101 '17

6
整个注释线程似乎是一个很好的论点,因为它不禁止某些主观内容如内置函数。
trichoplax


19

操作Flashpoint脚本语言, 50  46字节

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

致电:

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

输出:


您是否有递减额i--,并且+=在其中?
TheLethalCoder

3
为什么屏幕截图总是在荒芜的沙漠中?您应该为屏幕截图使用漂亮的地图:P。
魔术章鱼缸

2
@MagicOctopusUrn更好吗?
Steadybox

1
@Steadybox啊哈哈!史诗:P。那是从左往右走的小镇吗?看起来就像是您在某种程度上开始的教堂。
Magic Octopus Urn

1
我认为应将屏幕截图裁剪成较小的图像。我们不需要查看地图,它会分散实际的输出。
mbomb007 '18

12

APL(Dyalog),2个字节

五个同样简短的解决方案。最后两个由Zacharý提供


⍴⍨

在线尝试!

 周期性[R ESHAPE

 自


/⍨

在线尝试!

/ 复制

 自


\⍨

在线尝试!

\ 扩大

 自


⌿⍨

在线尝试!

 沿第一个(也是唯一一个)轴复制

 自


⍀⍨

 沿第一个(也是唯一一个)轴扩展

 自

在线尝试!


@Uriel还有一...
亚当

1
双方⌿⍨⍀⍨工作。
扎卡里

2
“自我”看起来像一张脸是故意的吗?
geokavel

1
@geokavel我不这么认为,但我也注意到它是这篇文章的打字版。使它变得漂亮的助记符,不是吗?实际上,自拍是其半官方名称之一,因此在Dyalog APL的RIDE界面中,您可以通过键入``selfie
亚当

1
@sethrin TIO对字符(和UTF-8字节,如果适用)进行计数,但是由用户决定是否使用单字节字符集(SBCS)中缺少的任何字符。有关APL,请参见此处。
阿达姆(Adám)



9

八度,12字节

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

在线尝试!


〜用八度表示是什么,因为那是我不理解的代码的唯一部分
。– Michthan

1
@Michthan抱歉,回复晚。~not将1:n转换0为大小为n 的s 的数组的 运算符 。您可以!代替它使用。
rahnema1年

9

JavaScript(ES6),19个字节

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

尝试一下

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
没有数组的数组...-接下来做什么?
尼尔

1
@Neil:甚至在我打字的时候,它还是感觉不对!:D
Shaggy


7

Haskell,13个字节

f n=n<$[1..n]

在线尝试!用法:f 5产量[5,5,5,5,5]。对于n=5[1..n]产生列表[1,2,3,4,5]n<$用替换此列表中的每个元素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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.