打印代码的前N个字符


21

您应该编写一个程序或函数,该程序或函数接收一个正整数N作为输入并打印出N代码的第一个字符。如果N大于代码长度,则应继续循环输出代码。

禁止以任何方式读取源代码以及从文件,stdio等中进行读取。

例子

(假设您的代码是yourcode)

输入=>输出:

5=> yourc
10=> yourcodeyo
22=>yourcodeyourcodeyour

澄清度

您的程序应至少为1个字节长。


15
恭喜您发布了第2000码高尔夫挑战赛!:)
— 马丁·恩德


1
@MartinBüttner实际上,有超过300个已删除的[code-golf]问题。但足够接近;)
— 门把手

11
@MartinBüttner谢谢。直到四舍五入才48!
— randomra

5
也许是时候您明确提到空程序无效了吗?
— 马丁·恩德

Answers:



10

> <>,49个字节

'3d*}r0ff+0i:&0(?.~~a*&"0"-+60.&~:?!;1-&:o}&" "0.

一半的代码将输入从字符串转换为int。如果允许我们使用从STDIN读取的单个char的代码点代替,那么此程序将缩短21个字节:

'3d*}ri:?!;1-&:o}&60.

说明

我将使用第二个程序进行解释。

'开始字符串解析,推送每个字符,直到找到结束引号。由于该行的其余部分没有'引号,因此除首字母之外的每个字符都'被压入堆栈。

但是> <>是2D环形语言,因此,在该行结束之后,指令指针会回绕到起点,'再次击中并停止字符串解析。结果是我们将除了引号外的所有必要内容都推送了,即

3d*}ri:0=?;1-&:o}&60.

'是ASCII 39,因此我们通过按来推送初始引号3d* = 3*13 = 39。然后,我们将堆栈右移(})和反转(r),得到:

.06&}o:&-1;?=0:ir}*d3'

现在我们都准备开始打印。i读取输入的一个字符,但> <>字符基本上是整数。在第一个程序中,i替换为一个循环,该循环将数字字符串从STDIN转换为整数。

然后,我们执行以下循环以打印出前N个字符:

:?!;               If the top of the stack (N) is 0, then terminate
                   Otherwise...
1-                 Subtract 1 from N
&                  Move N to the register temporarily
:o                 Output the next char in the program
}                  Shift the stack right
&                  Put N back on the stack
60.                Repeat loop by jumping back to the first :

9

CJam,34 17 16字节

这可以打很多球。

{`"_~"+ri_@*<}_~

代码扩展:

{`"_~"+ri_@*<}_~
{            }_~      "Put this code block on stack, take a copy and execute the copy";
 `                    "When executed, this block will the top element on stack to a string";
  "_~"                "Then put this string on stack";
      +               "Concat it to the the previous string on stack which ` created";
       ri             "Read an integer from STDIN";
         _@           "Copy the integer and put the concatinated string on top of stack";
           *          "Repeat the string input number of times";
            <         "Take the first input number of characters from the repeated string";

最后,堆栈上的所有内容都会自动打印到STDOUT

在这里在线尝试


5

Python 2,117字节

b=input();a=lambda x:(b*(2*(x+chr(34))+')'))[:b];print a("b=input();a=lambda x:(b*(2*(x+chr(34))+')'))[:b];print a(")

生活提示:不要执行list(itertools.cycle(x))。由于某种原因,我无法想象为什么,它使解释器崩溃。


1
itertools.cycle()是无限生成器,因此除非您的计算机具有无限内存,否则您将遇到问题:)
— Sp3000 2015年

5

JavaScript(ES6),65 52 50 47 41 39

q=n=>('q='+q).repeat(n/39+1).slice(0,n)

使用ES6 repeat()克隆代码,然后切片。使用硬编码的长度。


旧版本(50):

q=n=>n>(l=(t='q='+q).length)?t+q(n-l):t.slice(0,n)

创建一个q带有单个参数的函数。

它对函数文本进行字符串化,如果n大于文本的长度,则以递归方式调用函数。否则,它将返回文本的子字符串。

非ES6版本(65):

function q(n){return t=q+'',l=t.length,n>l?t+q(n-l):t.slice(0,n)}

1
.repeat对于循环需求,使用递归而不是ES6 只是天才。
— 雅各布

1
实际上,似乎使用可以repeat()使我减少一堆,所以我改用了它。
— Scimonster

没看到。无论如何-这是一个非常不错的答案
— Jacob

为什么/39+1呢?为什么不只留下足够长的字符串?
— l4m2

1
q=n=>('q='+q).repeat(n).slice(0,n)在Firefox上工作正常
— l4m2 '18

5

J-24个字符

接受一个正整数参数,然后输出一个字符串。

($],quote)&'($],quote)&'

J没有任何自引用技巧,因此我们只是采用奎因方式。爆炸解释:

  ],quote                 NB. right arg prepended to quotation of right arg (quine)
 $                        NB. cyclically take left-arg characters from that
(        )&'($],quote)&'  NB. preload right arg with  ($],quote)&

$J中的二元运算符循环地从其右参数获取项目以适合左侧指定的尺寸。当维是单个数字时,这是一个简单的一维字符列表,因此我们完全按照问题的要求进行操作。

在tryj.tk上尝试一下。


quote动词的一般目的是什么?
— randomra'2

@randomra在标准库中的定义为''''&,@(,&'''')@(#~ >:@(=&'''')),或用英语定义,“将任何'字符加倍,然后在开头和结尾添加一个”。J使用类似Ada的字符串文字,因此可以对字符串进行转义。
— algorithmhark

4

k2-7个字符

{x#$_f}

用英语来说,这是一个带有参数x的函数,其定义为“ xtake string self”。

  • 自我(名词_f)是当前执行的最内部功能。这是功能{x#$_f}。
  • 字符串(一元$)将其参数转换为字符串。对于函数,它将创建具有函数原始定义的字符串。
  • Take(dyadic #)将right-arg中的左参数项从列表中取出。对于字符串,项目是字符,因此这正是我们想要的。

这不会在开源科纳工作,因为它似乎会产生黑洞,它们专吃所有试图使用它们作为参数传递给任何东西。我不确定正确的k3语义,但它们可能不太友善。

在Q中,这是{x#string .z.s}和在k4中{x#2_$.z.s}。我们不得不使用2_k4中的两个初始字符,原因是只有一位母亲会喜欢。


3

Ruby,66 64 63字节

eval s=%q(puts"eval s=%q(#{s})".chars.cycle.take(gets.to_i)*'')

使用避免调用函数的函数要gets长一些(81个字节):

def f(i);eval s=%q(puts"def f(i);eval s=%q(#{s});end".chars.cycle.take(i)*'');end

相同的Lambda版本分别为69和65字节:

l=->i{eval s=%q(puts"l=->i{eval s=%q(#{s})}".chars.cycle.take(i)*'')}
->i{eval s=%q(puts"->i{eval s=%q(#{s})}".chars.cycle.take(i)*'')}

1
.cycle很整洁,我必须记住这一点。:)您可以缩短.join为*''。
— 马丁·恩德

您可以使用String#format而不是插值来保存一些字符:eval s="$><<('eval s=%p'%s).chars.cycle.take(gets.to_i)*''"
— Ventero 2015年

3

Mathematica,65个字节

Print[StringTake[StringJoin @@ Table[ToString[#0], {#1}], #1]] & 

为了使它成为合适的包装盒,需要所有空格,包括结尾的包装盒。这是一个纯函数,可以按以下方式使用:

Print[StringTake[StringJoin @@ Table[ToString[#0], {#1}], #1]] & [75]

哪个打印

Print[StringTake[StringJoin @@ Table[ToString[#0], {#1}], #1]] & Print[Stri

不幸的是,应用ToString的功能不会产生正是你输入函数的方式,所以我不能缩短这个通过删除空白,缩短#1到#或使用前缀符号函数调用。


“简称#为#1”?
— Undergroundmonorail

@undergroundmonorail相反,谢谢
— Martin Ender

3

MATLAB, 319141个字符

我设法从原始字节压缩了几个字节:

function d=g(n);d='gvodujpo!e>h)o*<e>(<e>\e)2;2:*.2-e-e)2:;foe*.2^<e>e)2,npe)1;o.2-252**<';d=[d(1:19)-1,d,d(19:end)-1];d=d(1+mod(0:n-1,141));

好答案...!不知道它是如何工作的:-)
— 路易斯·门多

3

JavaScript,34个字节

f=n=>n&&('f='+f+f(n-1)).slice(0,n)

递归函数,它重复编码n时间,然后对结果进行切片。


3

Japt,2个字节

îî

在线尝试!

第一种î是采用一个参数并将其重复为length的数字方法n。因为它是第一种方法,所以n成为输入。第二个î被转换为字符串,然后重复。

这会转换为:

n.î("î")->重复"î"直到达到长度n

8字节解决方案

îQi"îQi"

在线尝试!

îQi"îQi" 转换为 n.î(Qi"îQi")

n.î(Qi"îQi")
      "îQi"    // String "îQi"          -> îQi
    Qi         // Insert "              -> îQi"
n.î            // Repeated to length n  -> îQi"îQi"îQi"  (n=12)

1
简单而美丽!
— 毛茸茸的

2

R,203字节

当N = 203时,代码将完全打印自己。

(f <- function(N){
str <- paste0("(f <- function(N)", paste0(as.character(body(f)), collapse = "\n"), ")}(", N, ")")
cat(rep(str, floor(N/nchar(str))), sep = "")
cat(substr(str, 1, N%%nchar(str)))})(203)

当N = 50时,代码会自动修剪。

(f <- function(N){
str <- paste0("(f <- function(N

当N = 300时,代码会部分重复。

(f <- function(N){
str <- paste0("(f <- function(N)", paste0(as.character(body(f)), collapse = "\n"), ")}(", N, ")")
cat(rep(str, floor(N/nchar(str))), sep = "")
cat(substr(str, 1, N%%nchar(str))))}(300)(f <- function(N){
str <- paste0("(f <- function(N)", paste0(as.character(body(f)), collapse = "\

试试看:(f=function(N){s=paste0("(f=",paste0(capture.output(f),collapse=""),")");cat(rep(s,N%/%nchar(s)),substr(s,1,N%%nchar(s)),sep="")})(200)
— Thomas

2

Matlab(57)

function s=f(n);s=evalc('type f');s=s(mod(1:n,nnz(s))+1);

最后一行的初始1索引(而不是0)是因为Matlab的函数type引入了初始换行,应将其删除。感谢Dennis的修正(最后一个索引)和他的建议(nnz比短numel)。


恐怕这没有达到我的期望(f(4)返回“ fun”),好消息是您可以通过节省2个字符来解决它。(删除-1)。-我想你也可以删除第二个换行符和换出numel了nnz。
— Dennis Jaheruddin

@Dennis感谢您的两个想法!我已经编辑到二者结合
— 路易斯Mendo

嗯,我并不想成为一个buzzkill,但不将type f与部分要求冲突阅读源代码以任何方式和文件,标准输入输出等读书是不允许的?
— knedlsepp 2015年

@knedlsepp我认为你是对的。我也有这种怀疑。type可能访问硬盘。您认为我应该删除答案吗?
— 路易斯·门多

@LuisMendo:我认为没有人真正介意。:-)我只是想昨天解决这个问题,因为我之前几次都没​​有产生过类似的奎因。当然,我必须检查是否已经有Matlab解决方案。:-)最后,这给了我足够的动力去深入研究这个问题,最终产生解决方案。(mod顺便说一句,我偷了您的-indexing想法。)
— knedlsepp


2

Japt,40 28字节


"îR+Q+V+Q+R+V"
îR+Q+V+Q+R+V

第一次写一个quine,所以可以将其缩短很多。另一方面,我很高兴我完全可以使用它。

故意换行,第二行是数据,其余行解包数据,然后重复整个结果字符串,直到其长度等于输入。

多亏了Oliver,减少了12个字节。

在线尝试!


尼斯:)您可以替换tTU为¯U,也可以通过将其移到前面来î代替p:在线试用
— Oliver

再次考虑,我根本不需要切片。îR+Q+V+Q+R+V应该工作正常。
— 奥利弗

@Oliver哦,这很聪明,我不知道î,这非常方便。非常感谢!
— Nit

我也不太喜欢藜,但是我认为 这应该适合24个字节。
— 毛茸茸的

1

C ++,305

int L=305;string s="int main(){string t=\"string s=\";int n;cin>>n;t+=s;t+=\"\";\";t+=s;while(n>0){if(n>L){cout<<t;n-=L;}else{cout<<t.substr(0,n);}return 0;}";
int main(){string t="int L=305;string s=\"";int n;cin>>n;t+=s;t+="\";";t+=s;while(n>0){if(n>L){cout<<t;}else{cout<<t.substr(0,n);}n-=L;}return 0;}

解释 除了转义字符,其他所有字符也被打印出来。main方法在字符串s内,在main内部建立完整的字符串并打印到stdout


1

Pyth, 15 13 14 bytes

<jN*Q]"<jN*Q]"

Try it online!

Modified version of the standard Pyth quine.


@l4m2 How so? Please explain, I don't see anything wrong...
— hakr14

29 should be <jN*Q]"<jN*Q]<jN*Q]"<jN*Q]<jN wrong?
— l4m2

@l4m2 Ah, right you are. I've fixed it.
— hakr14

<jN*Q]"<jN*Q]" seems work?
— l4m2

Yeah, I realized that. Thanks for the help btw!
— hakr14

1

Hoon, 185 bytes

=/(f "=/(f k |=(n=@ =+((trim 5 f) `tape`(scag n `tape`(zing (reap n :(weld p <f> (slag 1 q))))))))" |=(n=@ =+((trim 5 f) `tape`(scag n `tape`(zing (reap n :(weld p <f> (slag 1 q))))))))

Set f to the program's code as a tape, but with "k" for itself. Split the tape at character 5, setting variables [p=left q=right]. Weld together the strings p, the original string f, and everything after the 1st character of q. Repeat that string n times, then return the first n characters of it.

Doing this was slightly hampered by Hoon's stdlib not having a format function or find-and-replace...Also, I'm not sure why we need another cast after the scag, since it should keep type information. So it goes.




1

Gol><>, 12 bytes

"r2ssIFLko|;

Try it online!

How it works

"r2ssIFLko|;

"..."   Push the chars in reverse order
r2ss    Reverse the stack, then push `"`
IF...|  Input n, and repeat the following n times...
  L     Push the loop counter (0 to n-1)
   k    Pop x and copy x-th from the top
    o   Pop and print as char
;       Halt

k can wrap any number of times, so we don't need to duplicate the whole stack depending on the input.


1

SmileBASIC, 106 66 bytes

INPUT N?MID$(("+CHR$(34))*3,23,N)INPUT N?MID$(("+CHR$(34))*N,23,N)

0

KSFTgolf - 4 chars, 6 bytes

KSFTgolf if a language I've been attempting to design for code golf. I've been changing it a lot, so this probably shouldn't actually count.

☃\@2

What language is this ? Any links ? Spec ? explanation ..
— Optimizer

@Optimizer Ah, right. I forgot about that. It's a language I've been designing for code golf. This is finally a challenge where (if I fix all the bugs) it could actually win.
— KSFT

1
Moreover, as far as I can see, the language was created like 10 minutes back, so technically, this is a non-competing answer :) . Also, I suppose this is the block corresponding to your ☃ code, which totally looks like something that has been specifically done for this challenge (as there are no other unicode based code blocks in your whole file).
— Optimizer

@Optimizer That instruction was actually in the language before (although a commit that changed it slightly was pushed after the challenge was posted), which was created a few days ago. Because I don't think this would work in the version of the language that was public when the challenge was posted, though, I don't think this answer should actually count, as I stated in my answer.
— KSFT

4
Do you want to build a snowman?
— flawr


0

J, 41 Bytes

Now that was a brain teaser!

((,quote,')$~'"_)'((,quote,'')$~''"_)')$~

Explanation:

((,quote,')$~'"_)'((,quote,'')$~''"_)')$~  | Expression taking 1 argument
                                       $~  | Reshape left argument to fit right, taking cyclically.
(                                     )    | One large expression that evaluates to a string
                 '((,quote,'')$~''"_)'     | String literal containing the code to the left of it
 (,quote,'$)~'"_)                          | A 4-Hook:
         '$)~'"_                           | The string '$)~'
   quote,                                  | Appended to the quoted version of the string
  ,                                        | Appended to the raw string

Examples:

   ((,quote,')$~'"_)'((,quote,'')$~''"_)')$~ 10
((,quote,'

   ((,quote,')$~'"_)'((,quote,'')$~''"_)')$~ 20
((,quote,')$~'"_)'((

   ((,quote,')$~'"_)'((,quote,'')$~''"_)')$~ 30
((,quote,')$~'"_)'((,quote,'')

   ((,quote,')$~'"_)'((,quote,'')$~''"_)')$~ 41
((,quote,')$~'"_)'((,quote,'')$~''"_)')$~

   ((,quote,')$~'"_)'((,quote,'')$~''"_)')$~ 50
((,quote,')$~'"_)'((,quote,'')$~''"_)')$~((,quote,


0

Java 10, 193 176 bytes

n->{var s="n->{var s=%c%s%1$c;s=s.format(s,34,s);for(int i=n;i>0;i/=176)s+=s;return s.substring(0,n);}";s=s.format(s,34,s);for(int i=n;i>0;i/=176)s+=s;return s.substring(0,n);}

Explanation:

Try it online.

n->{                       // Method with integer parameter and String return-type
  var s="n->{var s=%c%s%1$c;s=s.format(s,34,s);for(int i=n;i>0;i/=176)s+=s;return s.substring(0,n);}";
                           //  Unformatted source code
  s=s.format(s,34,s);      //  Create the formatted quine
  for(int i=n;i>0;         //  Loop `i` as long as it's not 0
      ;                    //    After every iteration:
       i/=176)             //     int-divide `i` by the hardcoded length of the source code
    s+=s;                  //   Exponentially enlarge the source code
  return s.substring(0,n);}//  Return the first `n` characters of the source code

-part:

  • The var s contains the unformatted source code.
  • %s is used to input this String into itself with the s.format(...).
  • %c, %1$c and the 34 are used to format the double-quotes.
  • s.format(s,34,s) puts it all together.

Challenge part:

  • for(int i=n;i>n;i/=176) loops ceil(n/176) times, where 176 is the length of the source code.
  • s+=s; exponentially increases the size of the source code String. (ab becomes abab; abab becomes abababab; abababab becomes abababababababab; etc.)
  • s.subtring(0,n); takes the first n characters of the String.


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.