12
\$\begingroup\$

Write the shortest program or function that takes some text as input, and outputs either it or an empty line in a repeating pattern:

some text
some text

some text
some text

some text
some text

...

This must continue indefinitely, or until some unpreventable limitation occurs (stack size, memory, etc.). It must be newline separated, and you can assume the inputted text is made up of non-newline printable ASCII characters. Note that it doesn't have to follow the pattern text-text-empty, and text-empty-text would be equally valid.

The ratio of text lines and empty lines will also be specified by input. There are various ways you can do this (though you only need to support one):

  • A fraction represented as a floating point number (this can represent the fraction which do OR do not have text in them, but it must be consistent)
  • A ratio of lines with text to lines without (represented as two integer inputs)
  • A fraction of lines which do OR do not have text in them (represented as an integer numerator and denominator)

Example:

Text: Hello, world!
Ratio: 2:3

Hello, world!
Hello, world!



Hello, world!
Hello, world!



...

Text: fraction
Fraction: 1/3

fraction


fraction


fraction


...

Text: decimal decimal decimal
Input: 0.6

decimal decimal decimal
decimal decimal decimal
decimal decimal decimal


decimal decimal decimal
decimal decimal decimal
decimal decimal decimal


...

Text: example with a different pattern Fraction: 2/5

example with a different pattern

example with a different pattern


example with a different pattern

example with a different pattern


...

This is code golf, so the shortest answer in bytes, per language, wins.

\$\endgroup\$
19
  • \$\begingroup\$ Just to make sure, answers can pick one of the ways to input and do not need to support all of them, right? \$\endgroup\$ – Laikoni Aug 28 '20 at 15:46
  • \$\begingroup\$ @Laikoni Yes, they only need to support one. \$\endgroup\$ – Redwolf Programs Aug 28 '20 at 15:49
  • \$\begingroup\$ Would this answer be valid? Or do we have to strictly follow the pattern p lines with the string / q empty lines? \$\endgroup\$ – Arnauld Aug 28 '20 at 16:22
  • \$\begingroup\$ @Arnauld Yeah, that's fine. They don't have to be strictly in that order. I'll also add a test case showing that. \$\endgroup\$ – Redwolf Programs Aug 28 '20 at 16:27
  • 2
    \$\begingroup\$ @Arnauld I think if, when divided into chunks as many lines long as the fractional representation denominator, each one would need to be identical for it to be valid. \$\endgroup\$ – Redwolf Programs Aug 28 '20 at 16:50

20 Answers 20

6
\$\begingroup\$

Pip, 26 12 bytes

T0{LbPaLcPx}

-14 bytes after taking ratio as two arguments.

Explanation:

T0           Till 0 (infinite loop)
  {Lb        Loop b(second argument) number of times
     Pa      Print a(first argument) with newline
       Lc    Loop c(third argument) number of times
         Px} Print x(empty string) with newline

Try it online!

\$\endgroup\$
3
  • \$\begingroup\$ Or I should find a way to print a plain newline. I'll ask about that. \$\endgroup\$ – Razetime Aug 29 '20 at 2:41
  • \$\begingroup\$ @Dingus Fixed it. \$\endgroup\$ – Razetime Aug 29 '20 at 3:33
  • 1
    \$\begingroup\$ Very nice indeed! \$\endgroup\$ – Dingus Aug 29 '20 at 9:00
5
\$\begingroup\$

Python 2, 44 bytes

def f(t,a,b,n=0):print(n%b<a)*t;f(t,a,b,n+a)

Try it online!

Prints until exceeding max recursion depth, which the challenge seems to allow. As a program:

45 bytes

t,a,b=input()
n=0
while 1:print(n%b<a)*t;n+=a

Try it online!

The idea is to to use a counter n that cycles through values modulo b, and only print the text if this is from 0 to a-1, and otherwise print a blank line. We could also do n+=1 in place of n+=a to get a different pattern where the text and blank lines come in clumps rather than mixed throughout.

It almost works to use a float input for the density as below:

40 bytes (not working)

def f(t,p,n=0):print(n%1<p)*t;f(t,p,n+p)

Try it online!

The issue is float imprecision -- a number like 12.6 might have its decimal part be very slightly bigger or smaller than 0.6. This method would work for irrational densities as well, limited precision aside.

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

C (gcc), 67 .. 38 bytes

i;f(s,a,t){for(;puts(i++%t<a?s:""););}

Try it online!

  • Thanks to @att for 11 byte saved and to @ErikF for 7 bytes saved!

Takes input as string, number of printed lines, total lines.

We flush buffer at every iteration.

puts() returns non negative if no error occours, hope it doesn't return 0 either!

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Is fflush necessary? You also don't need to initialize i. \$\endgroup\$ – att Aug 28 '20 at 20:11
  • \$\begingroup\$ @att right! Flush not necessary at all and for initialized i I think you are right, normally a function should be reusable but since this overflows that's fine \$\endgroup\$ – AZTECCO Aug 28 '20 at 22:32
  • 1
    \$\begingroup\$ int and char* are the same size in TIO, so you don't actually need the type specifier (-7 bytes): Try it online! \$\endgroup\$ – ErikF Aug 29 '20 at 1:07
4
\$\begingroup\$

APL (Dyalog Unicode), 10 bytes (SBCS)

Full program. Prompts for text, then for ratio of lines with text to lines without (as two integers). Runs forever.

⎕←⍣≢↑⎕/⍞''

Try it online!

⍞'' prompt for text and juxtapose with an empty string

⎕/ prompt for replication factors and replicate

 stack them on top of each other

⍣≢ repeat until the value changes (i.e. never):

⎕← output

\$\endgroup\$
1
  • 3
    \$\begingroup\$ This is probably the only language where "assignment" is a function (as opposed to a syntax) and can be modified by the "repeat" higher-order function. \$\endgroup\$ – Bubbler Aug 28 '20 at 16:17
3
\$\begingroup\$

Japt, 13 bytes

Runs until the stack overflows. More golfing to follow ...

ÆOpWÃVÆOpPéß

Try it

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

J, 17 16 bytes

$:,[echo@#'',:~]

Try it online!

Note: If the empty lines cannot have spaces, then $:,[echo@>@#a:;~] works for 17 bytes.

how

Uses a kind of "fork bomb" recursion:

  • $: - calls entire verb again
  • , - then append...
  • [echo@# - the echo of the left argument applied as a line-wise multiplier to...
  • '',:~] - the right argument catted line-wise with an empty string
\$\endgroup\$
3
\$\begingroup\$

x86-16 machine code, IBM PC DOS, 34 33 bytes

Binary:

00000000: be82 00ad 2d30 3092 52fe ca7c 0956 ac3c  ....-00.R..|.V.<
00000010: 0dcd 2975 f95e b00a cd29 fece 75eb 5aeb  ..)u.^...)..u.Z.
00000020: e7                                       .

Listing:

BE 0082     MOV  SI, 82H        ; SI to command line tail 
AD          LODSW               ; load first two chars 
2D 3030     SUB  AX, '00'       ; ASCII convert          
92          XCHG AX, DX         ; DL = numerator, DH = denominator 
        PATT_LOOP: 
52          PUSH DX             ; save original numerator/denominator 
        FRAC_LOOP: 
FE CA       DEC  DL             ; decrement numerator 
7C 09       JL   LF             ; if less than 0, just display LF 
56          PUSH SI             ; save start of input string 
        CHAR_LOOP: 
AC          LODSB               ; load next char of string 
3C 0D       CMP  AL, 0DH        ; is it a CR? 
CD 29       INT  29H            ; write to console
75 F9       JNZ  CHAR_LOOP      ; if not a CR, keep looping 
5E          POP  SI             ; restore start of input string 
        LF: 
B0 0A       MOV  AL, 0AH        ; LF char 
CD 29       INT  29H            ; write to console
FE CE       DEC  DH             ; decrement denominator 
75 EB       JNZ  FRAC_LOOP      ; if not 0, keep looping 
5A          POP  DX             ; restore numerator/denominator
EB E7       JMP  PATT_LOOP      ; start over and loop indefinitely

Standalone DOS executable, input via command line. First two chars are numerator / denominator, followed by input string.

enter image description here

enter image description here

(note: program slightly altered to only repeat 3 times for screenshots)

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

Python 3.8 (pre-release), 48 47 bytes

Saved a byte thanks to Dion

def f(t,a,b):
 while 1:print((t+'\n')*a+'\n'*b)

Try it online!

t is the text to print, a:b is the ratio of lines of text to empty lines.

\$\endgroup\$
1
  • 2
    \$\begingroup\$ save a byte by removing a space in the start of the second line? \$\endgroup\$ – Dion Aug 28 '20 at 18:27
3
\$\begingroup\$

Jelly, 9 bytes

Ø.x⁹ẋṄ€1¿

A full program accepting the ratio as a list [empty, full] and the string which prints forever.

Try it online!

How?

Ø.x⁹ẋṄ€1¿ - Main Link: list of integers, ratio ([empty, full]); list of characters, text
                                e.g.: [3, 2]; "Hello, world!"
Ø.        - bits                      [0, 1]
  x       - times (ratio)             [0, 0, 0, 1, 1]
   ⁹      - chain's right argument    "Hello, world!"
    ẋ     - repeat (vecorises)        ["", "", "", "Hello, world!", "Hello, world!"]
        ¿ - while...
       1  - ...condition: 1 (always)
      €   - ...do: for each:
     Ṅ    -          print with trailing newline
\$\endgroup\$
3
\$\begingroup\$

Java (JDK), 58 bytes

(s,n,d)->{for(int i=0;;)System.out.println(i++%d<n?s:"");}

Try it online!

Credits

\$\endgroup\$
5
  • 1
    \$\begingroup\$ If you take the input as a fraction-pair (i.e. taking 2/5 as input [2,5] instead of [2,3]), you can golf the (n+b) to b (naming that variable d for denominator in that case would make more sense than b). \$\endgroup\$ – Kevin Cruijssen Aug 31 '20 at 13:56
  • \$\begingroup\$ What will happen when i is the highest positive value? Will it wrap to the negatives? Will it crash? \$\endgroup\$ – Ismael Miguel Sep 1 '20 at 9:08
  • \$\begingroup\$ @IsmaelMiguel it will go to the negatives, but who cares, this is code golf, we don't take those into account: Integer.MAX_VALUE is close enough to infinity for most purposes. \$\endgroup\$ – Olivier Grégoire Sep 1 '20 at 10:14
  • \$\begingroup\$ @OlivierGrégoire Quoting the challenge: "This must continue indefinitely, or until some unpreventable limitation occurs (stack size, memory, etc.)." If after Integer.MAX_VALUE the results are wrong, I don't know if the answer is valid. According to tio.run/… what happens is that the Integer.MAX_VALUE line repeats \$\endgroup\$ – Ismael Miguel Sep 1 '20 at 10:48
  • \$\begingroup\$ Well, an integer going back to negative is an unpreventable limitation, right? \$\endgroup\$ – Olivier Grégoire Sep 1 '20 at 11:23
2
\$\begingroup\$

SNOBOL4 (CSNOBOL4), 100 88 87 bytes

	T =INPUT
	CODE('N' DUPL(';	OUTPUT =T',INPUT) DUPL(';	OUTPUT =',INPUT) ':(N)')	:(N)
END

Try it online!

Takes input as TEXT, M, N on separate lines.

Using the CODE function, this generates an infinite loop of

N; OUTPUT =T; OUTPUT =T ...; OUTPUT =; OUTPUT =; ... :(N)

Or equivalently (with ; being replaced by newlines):

N
 OUTPUT =T
 OUTPUT =T
 ...
 OUTPUT =
 OUTPUT =
 ...
 OUTPUT =:(N)

Which it then enters with the final :(N) and never leaves.

\$\endgroup\$
2
\$\begingroup\$

Batch, 87 bytes

@set f=@for /l %%i in (1,1,
@set/ps=
:g
%f%%1)do @echo(%s%
%f%%2)do @echo(
@goto g

Takes the text and blank line counts as command line arguments and the text to repeat on standard input. Explanation:

@set f=@for /l %%i in (1,1,

Define what is effectively a macro for two very similar loops.

@set/ps=

Input the text.

:g

Begin an infinite loop.

%f%%1)do @echo(%s%

Print the text the desired number of times.

%f%%2)do @echo(

Print the desired number of blank lines.

@goto g

Rinse and repeat.

\$\endgroup\$
2
\$\begingroup\$

05AB1E, 8 bytes

[s`¶×?F=

First input is the text, second input is a pair [amount_of_nonempty_lines, amount_of_empty_lines]; outputs the empty lines before the non-empty lines.

Try it online.

Explanation:

[         # Start an infinite loop:
 s        #  Swap the two (implicit) inputs, so the pair it at the top of the stack
  `       #  Pop and push its contents to the stack
   ¶×     #  Repeat a newline character "\n" the top value amount of times as string
     ?    #  Pop and output it without trailing newline
      F   #  Pop and loop the top value amount of times:
       =  #   And output the top string with trailing newline (without popping)
\$\endgroup\$
2
\$\begingroup\$

R, 48 47 bytes

Edit: -1 byte thanks to Giuseppe

function(t,c)repeat cat(rep(c(t,''),c),sep='
')

Try it online!

Function with arguments specifying text t and vector c of counts of text & blank lines.

\$\endgroup\$
2
  • \$\begingroup\$ 47 bytes \$\endgroup\$ – Giuseppe Aug 31 '20 at 16:43
  • \$\begingroup\$ Thanks again Giuseppe! \$\endgroup\$ – Dominic van Essen Sep 1 '20 at 9:11
2
\$\begingroup\$

Husk, 8 bytes

~o¢+RøR⁰

Try it online! This program takes the string, the number of lines with text, and the number of lines without text as three separate arguments.

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

JavaScript (V8), 40 bytes

Expects (p, q)(s), where \$p/q\$ is the fraction of lines that have the string \$s\$ in them.

This runs until the call stack overflows.

(p,q,t=0)=>g=s=>print(t++%q<p?s:'')&g(s)

Try it online!

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

Assembly (MIPS, SPIM), 236 bytes, 6 * 23 = 138 assembled bytes

Full program that takes the input in the order (input string, numerator, denominator). Output is to STDOUT.

.data
m:
.text
main:li$v0,8
la$a0,m
li$a1,99
syscall
li$v0,5
syscall
move$t0,$v0
li$v0,5
syscall
move$t1,$v0
s:li$t2,0
li$v0,4
la$a0,m
l:syscall
add$t2,$t2,1
blt$t2,$t0,l
li$t2,0
li$a0,10
li$v0,11
p:syscall
add$t2,$t2,1
blt$t2,$t1,p
b s

Try it online!

Explanation

.data
msg:                            # Here's the string input buffer (dynamically allocated)

.text
main:
    li $v0, 8                   # Set syscall code 8
    la $a0, msg                 # The first operand is the input buffer
    li $a1, 99                  # The second is the maximum length of input

    syscall                     # Read a line of characters from input

    li $v0, 5                   # Set syscall code 5
    syscall                     # v0 = integer from input
    move $t0, $v0               # t0 = v0

    li $v0, 5                   # Re-set syscall code 5
    syscall                     # v0 = integer from input
    move $t1, $v0               # t1 = v0

    start:                      # Main loop:
        li $t2, 0               #     t2 = 0 (our counter)

        li $v0, 4               #     Set syscall code 4
        la $a0, msg             #     First operand: the inputted message at msg
        loop:                   #     loop:
            syscall             #         Print the message at msg
            add $t2, $t2, 1     #         Increment counter
            blt $t2, $t0, loop  #         If t2 < t0, jump back

        li $t2, 0               #     Clear counter

        li $v0, 11              #     Set syscall code 11
        li $a0, 10              #     First operand: '\n'

        lop:                    #     second loop:
            syscall             #         Print character in a0
            add $t2, $t2, 1     #         Increment counter
            blt $t2, $t1, lop   #         if t2 < t1, jump back

        b start                 #     Jump back to the main loop
\$\endgroup\$
1
\$\begingroup\$

Wolfram Language (Mathematica), 35 bytes

Do[Print@If[i>#2,#,""],∞,{i,#3}]&

Try it online!

Takes [text, num, denom], where num/denom is the ratio of lines without text.

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

SimpleTemplate 0.84, 99 bytes

Yes, it is quite long, but it works!

{@callexplode intoM":",argv.1}{@while1}{@forfrom 1toM.0}{@echolargv.0}{@/}{@forfrom 1toM.1}{@echol}

Takes input in the form of an array with the format ['text', '1:1'].


If taking input as 2 separate numbers (['text', 1, 1]) is acceptable, the code can be reduced to this (66 bytes):

{@forfrom 1toargv.1}{@echolargv.0}{@/}{@forfrom 1toargv.2}{@echol}

Ungolfed:

Below is a more readable version of the top code:

{@call explode into ratio ":", argv.0}
{@while true}
    {@for i from 1 to ratio.0}
        {@echo argv.0, EOL}
    {@/}
    {@for i from 1 to ratio.1}
        {@echo EOL}
    {@/}
{@/}

Notice that {@echol} and {@echo EOL} do the same thing: output whatever, ending with a newline.


You an try it on: http://sandbox.onlinephpfunctions.com/code/abf48bd44a808e91f130d4a390fcb8a18d6ded39

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

PHP, 52 51 bytes

for($a=$argv;;)echo($i++%$a[3]<$a[2]?$a[1]:"")."
";

Try it online!

Nothing new under the sun: PHP arguments and vars prefix eating bytes.. Will go on "forever" (until it overflows the max integer value, and starts using floats for $i, then probably the legendary precision for big floats will cause inconsistent results)

EDIT: newline replaced by.. a newline to save 1 byte

\$\endgroup\$
6
  • \$\begingroup\$ By the time it reaches to the point where it loses precision, you will be stuck on an infinite loop. It seems to be at PHP_INT_MAX, where PHP_INT_MAX + 1 == PHP_INT_MAX is true. So, it will be forever stuck here. But, depending on the execution environment, this may be a valid answer: if you read php.net/manual/en/info.configuration.php#ini.max-execution-time you will see that the default is 0 (no timeout) for the console/command line. This means that, with php -r, with a default php.ini, your code will fail after $i = PHP_MAX_INT. \$\endgroup\$ – Ismael Miguel Aug 31 '20 at 15:05
  • \$\begingroup\$ @IsmaelMiguel yes that's expected, IMO the answer falls into the "or until some unpreventable limitation occurs (stack size, memory, etc.)" case, so I guess it's allright \$\endgroup\$ – Kaddath Sep 1 '20 at 7:03
  • \$\begingroup\$ @IsmaelMiguel at least in TIO it seems to behave as I expected it would when it reaches PHP_MAX_INT \$\endgroup\$ – Kaddath Sep 1 '20 at 7:47
  • \$\begingroup\$ The problem is that at PHP_MAX_INT, it will be stuck printing the same exact line, instead of producing the expected output. At PHP_MAX_INT, whatever result is on PHP_MAX_INT%$a[3]<$a[2], it will print that line forever. Please check this example: tio.run/… \$\endgroup\$ – Ismael Miguel Sep 1 '20 at 8:49
  • \$\begingroup\$ @IsmaelMiguel yes that's exactly what I meant by "will cause inconsistent results", but I don't understand why you blame this specific answer, it's exactly what will happen for most other answers when their variables will overflow (if not a straight crash). Again, that was expected in the question with ""or until some unpreventable limitation occurs (stack size, memory, etc.)"". I even took the time to explain clearly how it would happen in my answer! \$\endgroup\$ – Kaddath Sep 1 '20 at 8:54

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.