21
\$\begingroup\$

You should write a program or function that receives a positive integer N as input and prints out the first N characters of your code. If N is larger than the length of your code you should continue output your code cyclically.

Reading your source code in any way and reading from file, stdio, etc. are disallowed.

Examples

(assuming your code is yourcode)

Input => Output:

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

Clarification

Your program should be at least 1 byte long.

\$\endgroup\$
  • 15
    \$\begingroup\$ Congratulations on posting the 2000th code golf challenge! :) \$\endgroup\$ – Martin Ender Jan 25 '15 at 12:55
  • 3
    \$\begingroup\$ Douglas Hofstadter would love this! \$\endgroup\$ – Luis Mendo Jan 25 '15 at 17:51
  • 1
    \$\begingroup\$ @MartinBüttner Actually, there are over 300 deleted [code-golf] questions. But close enough ;) \$\endgroup\$ – Doorknob Jan 26 '15 at 2:57
  • 11
    \$\begingroup\$ @MartinBüttner Thank you. Only 48 to go until a round number! \$\endgroup\$ – randomra Jan 26 '15 at 9:29
  • 5
    \$\begingroup\$ Maybe it's time you mentioned explicitly that empty programs are invalid? \$\endgroup\$ – Martin Ender Jan 26 '15 at 20:42

32 Answers 32

16
\$\begingroup\$

Python 2, 61 bytes

def f(n):a='def f(n):a=%r;print(a%%a*n)[:n]';print(a%a*n)[:n]

Try it online!

\$\endgroup\$
10
\$\begingroup\$

><>, 49 bytes

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

Half the code is converting the input from a string to an int. If we're allowed to use the code point of a single char read from STDIN instead, then this program would be much shorter at 21 bytes:

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

Explanation

I'll use the second program for the explanation.

' starts string parsing, pushing every char until a closing quote is found. Since the rest of the line has no ' quote, every char except the initial ' is pushed onto the stack.

But ><> is a toroidal 2D language, so after the line is over the instruction pointer wraps back to the start, hitting the ' again and stops string parsing. The result is that we've pushed everything necessary except the initial quote, namely

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

' is ASCII 39, so we push the initial quote by pushing 3d* = 3*13 = 39. We then shift the stack right (}) and reverse (r), giving:

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

Now we're all set up to start printing. i reads in a char of input, but ><> chars are basically integers. In the first program, the i is replaced with a loop that converts a digit string from STDIN into an integer.

We then execute the following loop to print out the first N chars:

:?!;               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 :
\$\endgroup\$
9
\$\begingroup\$

CJam, 34 17 16 bytes

This can be golfed a lot..

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

Code expansion:

{`"_~"+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";

Finally, anything on stack gets printed to STDOUT automatically

Try it online here

\$\endgroup\$
5
\$\begingroup\$

Python 2, 117 bytes

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(")

Life protip: don't execute list(itertools.cycle(x)). For some reason, I can't imagine why, it crashes the interpreter.

\$\endgroup\$
  • 1
    \$\begingroup\$ itertools.cycle() is an infinite generator, so unless your computer has infinite memory you're going to have problems :) \$\endgroup\$ – Sp3000 Jan 26 '15 at 3:38
5
\$\begingroup\$

JavaScript (ES6), 65 52 50 47 41 39

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

Uses ES6 repeat() to clone the code, then slices down. Uses a hardcoded length.


Old version (50):

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

Creates a function q, taking a single parameter.

It stringifies the function text, and recursively calls the function if n is greater than the text's length. Otherwise, it returns a substring of the text.

Non ES6 version (65):

function q(n){return t=q+'',l=t.length,n>l?t+q(n-l):t.slice(0,n)}
\$\endgroup\$
  • 1
    \$\begingroup\$ using recursion, rather than ES6's .repeat, for the cyclic requirements was simply genius. \$\endgroup\$ – Jacob Jan 26 '15 at 8:18
  • 1
    \$\begingroup\$ Actually, it seems like using repeat() enabled me to cut it down a bunch, so i used that instead. \$\endgroup\$ – Scimonster Jan 26 '15 at 9:48
  • \$\begingroup\$ Didn't see that. Anyway - this is a very nice answer \$\endgroup\$ – Jacob Jan 26 '15 at 9:50
  • \$\begingroup\$ why the /39+1? why not just leave a long enough string? \$\endgroup\$ – l4m2 Mar 31 '18 at 4:04
  • 1
    \$\begingroup\$ q=n=>('q='+q).repeat(n).slice(0,n) works fine on firefox \$\endgroup\$ – l4m2 Apr 1 '18 at 0:24
5
\$\begingroup\$

J - 24 char

Takes a single positive integer argument and spits out a string.

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

J doesn't have any self-reference tricks, so we just do it the quine way. Explained by explosion:

  ],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)&

The dyadic $ operator in J cyclically takes items from its right argument to fit the dimensions specified on the left. When the dimension is a single number, this is a simple 1D list of characters, so we do exactly what the question asks.

Try it for yourself at tryj.tk.

\$\endgroup\$
  • \$\begingroup\$ What is the general purpose of the quote verb? \$\endgroup\$ – randomra Feb 1 '15 at 8:53
  • \$\begingroup\$ @randomra Its definition in the standard library is ''''&,@(,&'''')@(#~ >:@(=&'''')), or in English, "double any ' characters, then add one to the start and end." J uses Ada-like string literals so this escapes the string. \$\endgroup\$ – algorithmshark Feb 1 '15 at 8:59
4
\$\begingroup\$

k2 - 7 char

{x#$_f}

In English, this is a function with argument x whose definition is "x take string self".

  • Self (the noun _f) is the innermost currently executing function. Here it is the function {x#$_f}.
  • String (monadic $) converts its argument to a string. In the case of a function, it creates a string with the function's original definition.
  • Take (dyadic #) takes left-arg items form the list in right-arg. In the case of a string, the items are characters, so this is doing exactly what we want.

This will not work in the open-source Kona, because it seems to create black holes which eat all attempts to use them as arguments to anything. I am unsure of proper k3 semantics but they are probably not much kinder.

In Q, this is {x#string .z.s} and in k4 {x#2_$.z.s}. We have to use 2_ to drop two initial characters in k4, for reasons only a mother could love.

\$\endgroup\$
3
\$\begingroup\$

Ruby, 66 64 63 bytes

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

The same using a function to avoid calling gets is a bit longer (81 bytes):

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

Lambda versions of the same are 69 and 65 bytes:

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)*'')}
\$\endgroup\$
  • 1
    \$\begingroup\$ .cycle is neat, I have to remember that. :) You can probably shorten .join to *''. \$\endgroup\$ – Martin Ender Jan 25 '15 at 12:56
  • \$\begingroup\$ You can save a few chars by using String#format instead of interpolation: eval s="$><<('eval s=%p'%s).chars.cycle.take(gets.to_i)*''" \$\endgroup\$ – Ventero Jan 25 '15 at 14:12
3
\$\begingroup\$

Mathematica, 65 bytes

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

All spaces is necessary to make this a proper quine, including the trailing one. This is a pure function, which you can use as follows:

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

which prints

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

Unfortunately, applying ToString to a function doesn't yield exactly the way you entered the function, so I can't shorten this by removing whitespace, shortening #1 to # or using prefix notation for function calls.

\$\endgroup\$
  • \$\begingroup\$ "shortening # to #1"? \$\endgroup\$ – undergroundmonorail Jan 25 '15 at 19:47
  • \$\begingroup\$ @undergroundmonorail the other way round, thanks \$\endgroup\$ – Martin Ender Jan 25 '15 at 19:48
3
\$\begingroup\$

MATLAB, 319 141 characters

I managed to squeeze a few bytes from the original one:

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));
\$\endgroup\$
  • \$\begingroup\$ Great answer...! No idea how it works :-) \$\endgroup\$ – Luis Mendo Jan 31 '15 at 16:54
3
\$\begingroup\$

JavaScript, 34 bytes

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

Recursive function that repeats the code n times, then slices the result.

\$\endgroup\$
3
\$\begingroup\$

Japt, 2 bytes

îî

Try it online!

The first î is a number method that takes one parameter, and repeats it to length n. Because it is the first method, n becomes the input. The second î gets cast into a string, and gets repeated.

This transpiles to:

n.î("î") -> Repeat "î" until it reaches length n

8 byte solution

îQi"îQi"

Try it online!

îQi"îQi" transpiles to n.î(Qi"îQi")

n.î(Qi"îQi")
      "îQi"    // String "îQi"          -> îQi
    Qi         // Insert "              -> îQi"
n.î            // Repeated to length n  -> îQi"îQi"îQi"  (n=12)
\$\endgroup\$
  • 1
    \$\begingroup\$ Beautiful in its simplicity! \$\endgroup\$ – Shaggy Apr 11 '18 at 22:10
2
\$\begingroup\$

R, 203 bytes

When N = 203, the code fully print itself.

(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)

When N = 50, the code trims itself.

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

When N = 300, the code partially repeats itself.

(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 = "\
\$\endgroup\$
  • \$\begingroup\$ Give this a try: (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) \$\endgroup\$ – Thomas Jan 26 '15 at 10:30
2
\$\begingroup\$

Matlab (57)

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

The initial 1 index (instead of 0) in the last line is because Matlab's function type introduces an initial line-feed, which should be removed. Thanks to Dennis for his correction (last index) and for his suggestion (nnz shorter than numel).

\$\endgroup\$
  • \$\begingroup\$ Im afraid this does not do what I would expect (f(4) returns 'fun'), the good news is that you can fix it by saving 2 chars. (remove the -1). -- I think you can also remove the second newline and swap out numel for nnz. \$\endgroup\$ – Dennis Jaheruddin Jan 26 '15 at 15:00
  • \$\begingroup\$ @Dennis Thanks for these two ideas! I've edited to incorporate both \$\endgroup\$ – Luis Mendo Jan 26 '15 at 16:12
  • \$\begingroup\$ Hm, I don't want to be a buzzkill, but doesn't the type f part clash with the requirement Reading your source code in any way and reading from file, stdio, etc. are disallowed? \$\endgroup\$ – knedlsepp Jan 30 '15 at 22:11
  • \$\begingroup\$ @knedlsepp I think you are right. I had that suspicion too. type probably accesses the hard disk. Do you think I should remove the answer? \$\endgroup\$ – Luis Mendo Jan 31 '15 at 15:53
  • \$\begingroup\$ @LuisMendo: I don't think anyone really minds. :-) I just wanted to give this problem a go yesterday, as I had already failed to produce a quine similar to this a few times before. And of course I had to check if there already was a Matlab solution. :-) In the end this gave me enough motivation to dig deep enough into this to finally produce a solution. (I stole your mod-indexing idea by the way.) \$\endgroup\$ – knedlsepp Jan 31 '15 at 16:40
2
\$\begingroup\$

Japt, 40 28 bytes


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

First time writing a quine, so this can probably be shortened quite a bit. On the other hand, I'm quite happy I got it to work at all.

Leading newline intentional, the second line is data and the rest of it unwraps the data, then repeats the whole resulting string until it reaches length equal to the input.

Shaved off a whopping 12 bytes thanks to Oliver.

Try it online!

\$\endgroup\$
  • \$\begingroup\$ Nice :) you can replace tTU with ¯U and you can use î in place of p by moving it to the front: Try it Online \$\endgroup\$ – Oliver Apr 9 '18 at 14:24
  • \$\begingroup\$ On second thought, I don't think you need to slice it at all. îR+Q+V+Q+R+V should work just fine. \$\endgroup\$ – Oliver Apr 9 '18 at 14:31
  • \$\begingroup\$ @Oliver Oh that's clever, I didn't know about î, that's very handy. Thanks a lot! \$\endgroup\$ – Nit Apr 10 '18 at 7:30
  • \$\begingroup\$ I'm not too good with quines either but I think this should work for 24 bytes. \$\endgroup\$ – Shaggy Apr 10 '18 at 8:36
1
\$\begingroup\$

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;}

Explanation Apart from the escape character all other characters are printed out. The main method is inside the string s and inside main the full string is built and printed to stdout

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

Pyth, 15 13 14 bytes

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

Try it online!

Modified version of the standard Pyth quine.

\$\endgroup\$
  • \$\begingroup\$ @l4m2 How so? Please explain, I don't see anything wrong... \$\endgroup\$ – hakr14 Mar 31 '18 at 18:00
  • \$\begingroup\$ 29 should be <jN*Q]"<jN*Q]<jN*Q]"<jN*Q]<jN wrong? \$\endgroup\$ – l4m2 Mar 31 '18 at 18:20
  • \$\begingroup\$ @l4m2 Ah, right you are. I've fixed it. \$\endgroup\$ – hakr14 Mar 31 '18 at 18:34
  • \$\begingroup\$ <jN*Q]"<jN*Q]" seems work? \$\endgroup\$ – l4m2 Mar 31 '18 at 18:37
  • \$\begingroup\$ Yeah, I realized that. Thanks for the help btw! \$\endgroup\$ – hakr14 Mar 31 '18 at 18:39
1
\$\begingroup\$

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.

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

Jstx, 7 bytes

/£↕:1Fn

Try it online!

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

Unary(1-8 version), 23855 bytes

Takes input as unary of '1's, and the code is 23855 '1's (,[.,])

\$\endgroup\$
  • \$\begingroup\$ What brainfuck does this translate too? \$\endgroup\$ – DJMcMayhem Mar 31 '18 at 5:52
  • \$\begingroup\$ @DJMcMayhem It's a cat \$\endgroup\$ – l4m2 Mar 31 '18 at 16:53
  • \$\begingroup\$ Now find a language that unary input make sense and some 1-char program do cat \$\endgroup\$ – l4m2 Apr 2 '18 at 17:20
1
\$\begingroup\$

Perl 5 with -pa, 48 bytes

$_=q{$_=substr"\$_=q{$_}:eval"x"@F",0,"@F"};eval

Try it online!

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

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.

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

SmileBASIC, 106 66 bytes

INPUT N?MID$(("+CHR$(34))*3,23,N)INPUT N?MID$(("+CHR$(34))*N,23,N)
\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
  • \$\begingroup\$ What language is this ? Any links ? Spec ? explanation .. \$\endgroup\$ – Optimizer Jan 25 '15 at 14:42
  • \$\begingroup\$ @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. \$\endgroup\$ – KSFT Jan 25 '15 at 14:44
  • 1
    \$\begingroup\$ 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). \$\endgroup\$ – Optimizer Jan 25 '15 at 14:48
  • \$\begingroup\$ @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. \$\endgroup\$ – KSFT Jan 25 '15 at 14:50
  • 4
    \$\begingroup\$ Do you want to build a snowman? \$\endgroup\$ – flawr Jan 25 '15 at 17:19
0
\$\begingroup\$

Stax, 24 bytes

"34bLNca*]$("34bLNca*]$(

Run and debug it

Adaption of the "34bL"34bL quine.

\$\endgroup\$
0
\$\begingroup\$

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,
\$\endgroup\$
0
\$\begingroup\$

Ly, 28 bytes

"r(34)<ns>l[p&:l,s]p<[>o<,]p

Try it online!

\$\endgroup\$
  • \$\begingroup\$ Doesn't work with wrapping (input>15). \$\endgroup\$ – Weijun Zhou Apr 2 '18 at 18:39
0
\$\begingroup\$

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.
\$\endgroup\$
0
\$\begingroup\$

><>, 22 19 bytes

'rd3*$:?!;1-$:o}50.

Try it online!

Takes input through the -v flag.

\$\endgroup\$
0
\$\begingroup\$

Stax, 8 bytes

",:m",:m

Run and debug it

\$\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.