17
\$\begingroup\$

Many people know what a truth machine in programming is. But is time we kick things up a notch. Introducing, the extended truth machine! An extended truth machine takes two things as input, a integer n and a nonempty string s. It outputs s n times with optional trailing whitespace. However, if n is equal to 0, you must output s until the program is manually stopped i.e. it should never terminate.

Also, if n is a negative number, then the string needs to be reversed. For example with s=hello and n=-1, output would be olleh.

Standard methods of input, any kind of output as long as it can handle infinite. If you have an answer that does not handle infinite, feel free to post it if it is interesting or in a language that cannot handle infinite output.

Test Cases

n, s, output

5, "hello world", "hello worldhello worldhello worldhello worldhello world"
0, "PPCG", "PPCGPPCGPPCGPPCG..."
-2, "truThY", "YhTurtYhTurt"
2000, "o", "oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo"

This is , so shortest code wins!

Here is the original Sandbox post. Edits have been made to it. Thanks go to @ComradeSparklePony for creating the idea of this challenge

\$\endgroup\$

15 Answers 15

3
\$\begingroup\$

Haskell, 57 54 bytes

f 0=cycle
f n|n<0=f(-n).reverse|n>0=concat.replicate n

Explanation:

f 0           -- If n=0 ..
 =cycle       -- infinitely repeat the input
f n|n<0       -- Otherwise, if n<0 ..
 =f(-n)       -- call f with the negative of n ..
 .reverse     -- and the reverse of the input
 |n>0         -- Finally, if n>0 ..
 concat       -- concatenate the result of ..
 .replicate n -- repeating the input n times

-3 bytes thanks to @nimi

\$\endgroup\$
  • \$\begingroup\$ You can use -n instead of abs n. \$\endgroup\$ – nimi Jun 4 '17 at 0:18
2
\$\begingroup\$

PHP>=7.1, 67 Bytes

for([,$x,$y]=$argv,$z=$x<=>0;!$z||$x;$x-=$z)echo$x<0?strrev($y):$y;

Version with list(,$x,$y) instead of [,$x,$y] Try it online!

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

MATL, 37 bytes

jXJiXI0=?`1wtwDw]}I0>?I:"t]x}PI|:"t]x

Try it online!

Explanation:

j            % input string
XJ           % copy to clipboard J
i            % input
XI           % copy to clipboard I
0            % number literal
=            % is equal? (element-wise, singleton expansion)
?            % if
  `          % do...while
    1        % number literal
    w        % swap elements in stack
    t        % duplicate elements
    w        % swap elements in stack
    D        % convert to string and display / string representation
    w        % swap elements in stack
  ]          % end
}            % else
  I          % paste from clipboard I
  0          % number literal
  >          % is greater than? (element-wise, singleton expansion)
  ?          % if
    I        % paste from clipboard I
    :        % range; vector of equally spaced values
    "        % for
      t      % duplicate elements
    ]        % end
    x        % delete
  }          % else
    P        % flip the order of elements
    I        % paste from clipboard I
    |        % absolute value / norm / determinant
    :        % range; vector of equally spaced values
    "        % for
      t      % duplicate elements
    ]        % end
    x        % delete
             % (implicit) end
             % (implicit) end
             % (implicit) convert to string and display
\$\endgroup\$
1
\$\begingroup\$

Python 3, 71 bytes

def f(n,s,k=1):
 if n<0:s=s[::-1];n=-n
 while n|k:print(end=s);n-=1;k=0

Try it online!

The variable k guarantees the loop is always run at least once. This means that if n=0, then n will be negative on the next iteration of the loop, so the loop will continue to be run forever.

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

Matlab, 87 bytes

n=input('')
s=input('','s')
a=repmat(s,1,abs(n))
while~n s=[s s]
end
if n<0,flip(a)
end

My first attempt at code-golf! Any suggestions for golfing are welcome.

\$\endgroup\$
  • \$\begingroup\$ Welcome to the site! :) \$\endgroup\$ – DJMcMayhem Jun 4 '17 at 18:22
1
\$\begingroup\$

05AB1E, 17 16 14 bytes

0‹iR}¹Ä×¹_i[²?

Try it online!

Explanation:

0‹iR}¹Ä×¹_i[²?
0‹             Is the input negative?
  iR}          If so, reverse the second input.
     ¹Ä        Get the absolute value of the first input.
       ×       Repeat the string that many times.
        ¹_     Boolean NOT the first input. (Is the first input 0?)
          i    If so...
           [   Do forever...
            ²? Print the second input without a newline.

Saved 2 bytes thanks to @EriktheOutgolfer

\$\endgroup\$
  • \$\begingroup\$ You can replace '-å with 0‹ and 0Q with _. \$\endgroup\$ – Erik the Outgolfer Jun 4 '17 at 12:34
  • \$\begingroup\$ @EriktheOutgolfer Thanks, edited. \$\endgroup\$ – Comrade SparklePony Jun 4 '17 at 22:57
1
\$\begingroup\$

Cubix, 41 Forty four 45 bytes

Takes input as <N> <String>

.uq.sB.p$IA;p?;ouu(..!q/o()uq?..@<w?q<<_)

Try it online!

Cubified:

      . u q
      . s B
      . p $
I A ; p ? ; o u u ( . .
! q / o ( ) u q ? . . @
< w ? q < < _ ) . . . .
      . . .
      . . .
      . . .

Watch it running

There is still an amount of no-ops in the code which I might be able to get a few more bytes out of, but wanted to get this up before I break it.

Basic procedure is

  • I get counter from input
  • A take the rest of input in as characters
  • ;p? remove the space, bring the number up and test it
    • psuqB$) if the counter is negative, reverse the stack. This involves handling the input number and EOI marker(-1). Increment the counter.
    • ;p;ouqu if the counter is zero, remove the counter and EOI marker and start perpetual output loop.
    • ( if positive decrement the counter
  • <<q?/o()u the output loop. This will output each character of the stack until the EOI marker (-1) is reached.
  • ... _ ... ?wq! on end EOI marker, go around the cube and reflect back to the ?, change lane, drop the EOI marker to the bottom and test the counter.
  • @ if zero, halt
  • ?u( if positive u-turn and decrement, thie ends up hitting the beginning of the loop
  • ? ... <) if negative, go around the cube to the otherside, redirect to the beginning of the loop while passing over a increment.
  • /)< if negative increment and carry on to output loop
\$\endgroup\$
  • \$\begingroup\$ doesn't this fail to work if the string starts with a number? \$\endgroup\$ – Destructible Lemon Jun 22 '17 at 23:48
  • \$\begingroup\$ @DestructibleLemon fixed \$\endgroup\$ – MickyT Jun 23 '17 at 0:04
0
\$\begingroup\$

JavaScript (ES6), 79 bytes

 f=(n,s)=>n<0?f(-n,[...s].reverse().join``):(alert(!n?s:s.repeat(n)),!n&&f(n,s))

Snippet:

f=(n,s)=>n<0?f(-n,[...s].reverse().join``):(alert(!n?s:s.repeat(n)),!n&&f(n,s))

f(5, "hello world")
//f(0, "PPCG")  //uncomment this at your peril!!!
f(-2, "truThY")
f(2000, "o")

\$\endgroup\$
  • \$\begingroup\$ I was trying to do something recursive like this, but I didn't think of !n&& for looping infinitely. However, will this hit a StackOverflow eventually? it should never terminate. \$\endgroup\$ – Stephen Jun 3 '17 at 17:07
  • \$\begingroup\$ It will alert the string PPCG repeatedly. In Chrome (at least), I have to kill the browser to stop it. \$\endgroup\$ – Rick Hitchcock Jun 3 '17 at 17:15
  • \$\begingroup\$ I understand your point. I think my code would take advantage of tail call recursion optimization in browsers that support it. \$\endgroup\$ – Rick Hitchcock Jun 3 '17 at 17:26
  • \$\begingroup\$ Test it with console.log. I get an error. \$\endgroup\$ – Stephen Jun 3 '17 at 18:36
  • \$\begingroup\$ Hmm, you're absolutely correct : ( \$\endgroup\$ – Rick Hitchcock Jun 3 '17 at 18:38
0
\$\begingroup\$

JavaScript (ES6), 98 94 91 83 bytes

n=>s=>{s=n<0?[...s].reverse().join``:s;while(!n)l(s);l(s.repeat(n<0?-n:n))}

-4, -5 bytes thanks to Arjun

-3 bytes thanks to Rick Hitchcock

Started out different than the Java answer, but quickly became very similar after golfing. Alert is infinite, but if you want it to look nice, switch to console.log. l=alert; and writing out alert are the same length, but if you switch to console.log it's shorter to redefine it.

\$\endgroup\$
  • 1
    \$\begingroup\$ while(!n)l(s) instead of if(!n)for(;;)l(s). \$\endgroup\$ – Arjun Jun 3 '17 at 16:15
  • 2
    \$\begingroup\$ [...s].reverse() instead of s.split''.reverse() \$\endgroup\$ – Rick Hitchcock Jun 3 '17 at 16:19
  • \$\begingroup\$ @RickHitchcock I always forget about that :( \$\endgroup\$ – Stephen Jun 3 '17 at 16:27
  • \$\begingroup\$ l(s.repeat(Math.abs(n))) instead of for loop at last. \$\endgroup\$ – Arjun Jun 3 '17 at 16:31
0
\$\begingroup\$

QBIC, 36 bytes

Lot ging on here, and QBIC/QBasic just doesn't have the syntax to deal with such conditions elegantly.

~:<0|;=_fA}[abs(a)|Z=Z+A]~a|_X}{?A';

Explanation:

~:<0|       IF cmd line arg 'a' is negative
  ;=_fA         Make cmd line arg A$ into its reverse
}           Close the IF (this eliminates the need for a | fuction terminator on _f)
[abs(a)|    FOR b = 1 to (abs(a) (hammering out negatives)
  Z=Z+A         Add A$ to Z$ (on exit, Z$ is printed explicitly)
]           NEXT
~a|_X       IF a is non-zero, terminate the program
}           END IF
{?A';       If we're here, just start a DO-loop and keep on printing the input.
\$\endgroup\$
0
\$\begingroup\$

Java (OpenJDK 8), 137 bytes

void f(String[] a){for(long n=Long.valueOf(a[0]),i=0;n==0|i++<Math.abs(n);)System.out.print(n<0?new StringBuilder(a[1]).reverse():a[1]);}

Try it online!

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

str, 30 bytes

I#Lbd0<[_u_][d0='e'u#?]#?xo;db

Try it online!

Explanation

I#Lbd0<[_u_][d0='e'u#?]#?xo;db
...........................;      preamble
I                                 read number
 #L                               read rest of STDIN
   b                              buffer the STDIN
    d                             duplicate number
     0<[   ]           #?         if the number is less than zero
        _                         negate that number
         u_                       and reverse STDIN from buffer
            [         ]           otherwise
             d0='e  #?            if its 0, push the empty string
                  'u              otherwise, push the unbuffered STDIN untouched
                         x        repeat STDIN by the TOS
                          o       and output
                           ;..    main program (only activates when input = 0)
                            d     duplicate the implicitly unbuffered STDIN
                             b    and rebuffer it
                                  implicitly displayed
\$\endgroup\$
0
\$\begingroup\$

C (gcc), 115 112 109 107 104 bytes

f(n,s,l,p,d)char*s;{d=n<0?-1:1;do for(l=1,p=0;p>=0;p+=l)s[p]?d==l&&putchar(s[p]):l--;while(!n||(n-=d));}

Try it online!

Who said, we need strlen?

C (gcc), 115 bytes (134 with #include<string.h> in front)

#include<string.h>
f(n,s)char*s;{int l=strlen(s),d=n<0?0:2,m=d--,p;do for(p=m?0:l-1;p!=(m?l:-1);p+=d)putchar(s[p]);while(!n||(n-=d));}

Try it online!

Without #include<string.h> we get an implicit prototype for strlen that returns int, but strlen is size_t (at least nowadays, not perfectly sure about k&r or c89, but I believe, it returned int in the old days).

The missing #include <stdio.h> isn't a problem, because due to integer promotion, the default prototype will be int putchar(int) which is exactly what we want.

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

Retina, 49 bytes

/¶-/&V`^.+
/¶0/&//+>G0`
~`(.+)¶-*(\d+)
.-$2+>K`$1

Input format: takes in the string, followed by a newline, followed by the number.

Try it online!

Explanation:

/¶-/&V`^.+

The /¶-/& runs this line only if the number is negative. V is the reverse stage, and it reverses ^.+, which matches the string (. matches every character apart from newlines).

/¶0/&//+>G0`

The /¶0/& runs this line only if the number is 0. //+> starts an infinite loop, which prints the working string after each iteration. G0 takes the string and discards the number; it does this infinitely, printing every time.

~`...

This marks code that will generate a string; the program evaluates the string as Retina code after.

(.+)¶-*(\d+)
.-$2+>K`$1

(.+)¶-*(\d+) matches the whole string and puts the string in capturing group 1 and the number in capturing group 2. .-$2+>K` $1 generates the Retina code to be run: . turns implicit output off (otherwise the string would be printed n+1 times), -$2+ sets a repeat loop that repeats for {capturing group 2} times. The minus at the beginning turns the number into a negative number, as this disables the convergence functionality in the loop, which would stop it after the 1st iteration. > sets this loop to print after each iteration. The rest of the code is just to print the string.

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

Perl 6, 44 bytes

{[$^s.flip,$s,$s Zxx-$^n,Inf,$n][$n.sign+1]}

Try it online!

Anonymous code block that takes a number and a string and returns a (possibly infinite) list

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