Hiccup a string

Your challenge is to write a program or function that hiccups a string. It should take a string as input (via any standard method), then follow these steps:

1. Generate a (not necessarily uniformly) random integer n between 1 and 10, inclusive.
2. Wait n seconds.
3. Print the initial/next n chars of the input, or the rest of the input if there are less than n chars.
4. If there is input left to print, go back to step 1.

Rules

• The input will always be a non-empty string containing only ASCII chars (32-126).
• The wait time does not have to be exactly n seconds, but it must be within 10% of n.
• You may print a trailing newline each time a section of text is printed.

Example

A space here represents 1 second. If the input is Hiccupinator!, an output might be:

   Hic     cupin a          tor!


Scoring

This is , so the shortest code in bytes wins.

• Comments are not for extended discussion; this conversation has been moved to chat. Nov 25, 2016 at 18:41
• Can we use spaces for languages that does not support waiting/do not have a notion of time ?
– THC
Nov 27, 2016 at 14:12
• I bet any language has a way to spend time without producing output, @FliiFe!
– Omar
Nov 27, 2016 at 19:00

Scratch, 16 blocks + 6 bytes

Assumes input is already defined as a list of characters (["H","e","l","l","o"," ","W","o","r","l","d"])

• Can this be golfed down in any way? Nov 29, 2016 at 1:36
• This is not a valid scoring method. See meta post. Dec 5, 2016 at 14:58
• Would you be willing to fix it based on the community consensus? Dec 5, 2016 at 15:24
• I don't have Scratch. It's your responsibility, since you posted the answer. ScratchBlocks2 even comes with a generator to create text code from a project. Dec 5, 2016 at 15:32

Pushy, 2017 16 or 13 bytes

Depending on what's allowed, there are two solutions.

16 bytes:

@$LT1U&Wm:v;O"cI  Give arguments on the command line: $ pushy hiccup.pshy 'hiccupinator'. This prints with trailing newlines after each 'hiccup'. Here's the breakdown:

                      % Implicit: input on stack as charcodes
@                     % Reverse input, so chars are pulled from start
$I % While there are items on stack: T1U % Push a random number, 1-10 &W % Wait that many seconds L m: % min(time waited, chars left) times do: v; % Pull a char from the input. O"c % Print & delete pulled chars  13 bytes: While coding the above answer I came up with this significantly shorter solution: N@$L1TU&Wm:'.


Although it does a similar thing, it prints directly off the string rather than constructing a new string, for fewer bytes. This requires the N at the beginning of the program to prevent trailing newlines, or else each character would be on a newline.

However, whilst testing this I noticed a bug - stdout is line-buffered, so the program would wait the full length, and then display the hiccuped string.

I've fixed this in the latest commit by adding a simple .flush() - this is technically not adding a new feature to the language, just fixing a bug, but I understand if you don't take this answer into account :)

The breakdown looks like this:

        % Implicit: input on stack as charcodes
N       % Set trailing newlines to False
@       % Reverse stack (so the charcodes are pulled off in order)
$% While there are items left to print: L % Push stack length 1TU % Push a random number 1-10 &W % Wait that amount of time m: % min(time waited, chars left) times do: '. % Pop and print last char  • The convention at PPCG is that languages are defined by the implementation (bugs and all). Since the commit postdates the challenge, that part is non-competining Nov 26, 2016 at 18:16 • @LuisMendo ok, thanks for the clarification :) Nov 26, 2016 at 18:16 • Nice answer BTW :-) Nov 26, 2016 at 18:17 Javascript (ES6) 91 89 Bytes f=s=>s&&setTimeout(_=>console.log(s.slice(0,n))|f(s.slice(n)),(n=1+Math.random()*10)<<10) console.log(2 + f.toString().length); f('Hello sweet world!')  saved 2 bytes thanks to @zeppelin Abuses the 10% tolerance for the wait time by waiting n<<10 === 1024*n milliseconds. Since you said that the wait time needs to be within 10% of n, I decided to save one byte and wait for 999 milliseconds rather than 1 second. I don't need the 999 millisecond silliness anymore thanks to @ETHProductions • Hmm, not sure if new Date()%10 counts for "random" by any measure. Nov 25, 2016 at 13:17 • @zeppelin Fair point, according to the standard definition it doesn't count. (meta.codegolf.stackexchange.com/a/1325/56071). I shall change it accordingly. – Lmis Nov 25, 2016 at 13:20 • You can also save a pair of bytes, by removing "|0" Nov 25, 2016 at 14:19 • You know, you can express 1000 in three bytes too: 1e3 ;-) Nov 25, 2016 at 15:01 • >(1+0.099999*10)*999 > 1997 True, but you can probably replace *999 with <<10, to work around this: (1+0.099999*10)<<10 => 1024, (1+0.99999999*10)<<10 => 10240 Nov 25, 2016 at 15:08 Python 2, 93 92 bytes import random,time def F(s): if s:n=random.randint(1,10);time.sleep(n);print s[:n];F(s[n:])  -1 byte thanks to Flp.Tkc I'm sure there is a way to shorten the random.randint and time.sleep, but from random,time import* doesn't work... • from random,time import* doesn't work because Python doesn't know from which module you want to import libraries from. Nov 24, 2016 at 17:57 • Python 3 is one byte longer. Insert a '(' between print and 'i' and a ')' before the bracket Nov 24, 2016 at 19:08 • Adapting this to minipy (Python 3): while v1:n=ri(1,10);_i("time").sleep(n);p(v1[:n]);v1=v1[n:]; (Takes input from command line args) Nov 24, 2016 at 19:20 • You can write this 1 byte shorter as a recursive function: import random,time, then def F(s): newline if s:n=random.randint(1,10);time.sleep(n);print s[:n];F(s[n:]) Nov 25, 2016 at 18:19 Perl 6, 62 bytes {$_=$^a;while$_ {sleep my \t=(1..10).roll;put s/.**{0..t}//}}


Expanded

{ # block lambda with parameter ｢$a｣$_ = $^a; # declare parameter, and store it in ｢$_｣
# ( the input is read-only by default )

while $_ { # generate random number and sleep for that many seconds sleep my \t=(1..10).roll; put s/ # substitution on ｢$_｣ ( returns matched text )
. ** { 0..t } # match at most ｢t｣ characters
//              # replace it with nothing
}
}


CJam, 28 bytes

q{Amr)__e3es+{_es>}g;2$<o>}h  Try it online! Or actually, don't. The effect doesn't really show up in any online interpreter, so try it on the Java interpreter instead. Turns out, CJam has an operator that gets the current Unix timestamp. This program waits by entering a while loop until the timestamp passes the correct value. Batch, 131 bytes @set/ps= :l @set/an=%random%%%10+1 @timeout/t>nul %n% @call echo(%%s:~0,%n%%% @call set s=%%s:~%n%%% @if not "%s%"==2" goto l  Using set/pn=<nul would have given a nicer effect except that it trims spaces. Pyth, 16 bytes Wz.d_JhOT<zJ=>zJ  You can try it online, but it doesn't work well since the online interpreter only displays the output once the program has finished. Explanation Wz While z (the input) is not empty: hOT Get a random number between 1-10 (inclusive) J Set the variable J to that number .d_ Sleep for that number of seconds <zJ Get and implicitly print the first J characters of the input >zJ Get all characters of z at and after index J = Set z to that string  MATL, 19 bytes 10YrtY.ynhX<:&)wDt  How it works Try it online! The online compiler does gradually produce the outputs with the pauses.  % Do...while loop 10Yr % Random integer from 1 to 10 tY. % Duplicate. Pause that many seconds y % Duplicate the second-top element. This is the remaining string; or it % takes the input implicitly in the first iteration n % Number of elements hX< % Minimum of the number of elements and the random number : % Range from 1 to that &) % Apply as index. Push the substring as given by the index and the % remaining substring w % Swap D % Display t % Duplicate the remaining substring. This is used as loop condition: % if non-empty execute next iteration % End loop implicitly  BaCon, 93 bytes A solution in BASIC. The RANDOM() function generates a number between 0 and n-1, therefore we have to use RANDOM(11) to get a number between 0 and 10 inclusive. INPUT s$
WHILE LEN(s$)>0 n=RANDOM(11) SLEEP n*1000 ?LEFT$(s$,n),SPC$(n);
s$=MID$(s$,n+1) WEND  Sample session, first line is the input, second the output: Hiccupinator! Hiccupi nato r!  • If what you say is true then your random function should be n=RANDOM(10)+1, your line of code will generate a number from 0-10 inclusive, not 1-10 Nov 24, 2016 at 19:26 • @Octopus It doesn't matter, since it will sleep for no time and produce no output in that case. – Neil Nov 25, 2016 at 9:34 • Fixed the typo in my explanation. Nov 27, 2016 at 18:53 Perl, 42 bytes 41 bytes code + 1 for -n. $|=$-=--$-||sleep 1+rand 10,print for/./g


I had to force Perl to flush output as it wasn't showing anything 'til the end at first, hence setting $|. We use $- to track the number of characters to print as this cannot be negative (so I can use --$- and it'll sill be falsy when it's empty) and it also floors, although since I'm using the return of sleep for this now, that doesn't really matter. Usage perl -ne '$|=$-=--$-||sleep 1+rand 10,print for/./g' <<< 'Hello, World!'
Hell      o, Wor     ld!
# spaces showing delay!


Ruby, 56 bytes

f=->s{n=sleep rand 1..10;print s.slice!0,n;f[s]if s!=""}


A recursive lambda. Call like f["Hello, World!"].

><> (Fish) 103 88 Bytes

5>:?vl1-?!v+40.    >~
1x2v
>^  0  |:!/>:?!v1-b2.
^-1}< <     |~!/:?!^1-i:1+?!;of3.


Online interpreter found here!

First attempt at this problem (not golfed).

It waits a certain amount of loops(n) as fish doesn't have a timer that is accessible (Execution in ticks).

Edit 1: Moved last line across to the top (last 2 characters and re-used the starting values. (saving of 15 bytes).

Bash, 78 bytes

As nobody has posted a Bash solution yet, here is one. Straightforward, yet small enough.

Golfed

H() { N=$(($RANDOM%10+1));sleep $N;echo${1:0:$N};S=${1:$N};[ "$S" ] && H $S;}  Test >H "It's the Hiccupinator" It's the Hiccupi n ator  PHP, 81 bytes for(;''<$s=&$argv[1];$s=$f($s,$n))echo($f=substr)($s,0,sleep($n=rand(1,10))?:$n);  use like: php -r "for(;''<$s=&$argv[1];$s=$f($s,$n))echo($f=substr)($s,0,sleep($n=rand(1,10))?:$n);" "Hiccupinator!"  C++14, 202 bytes #import<thread> void f(auto c){if(c.size()<1)return;int n=(uintptr_t(&c)%99)/10+1;std::this_thread::sleep_for(std::chrono::seconds(n));std::cout<<c.substr(0,n)<<std::endl;f(n<c.size()?c.substr(n):"");}  Requires input to be a std::string Ungolfed and usage: #include<iostream> #include<string> #import <thread> void f(auto c){ if (c.size() < 1) return; int n=(uintptr_t(&c) % 99) / 10 + 1; std::this_thread::sleep_for(std::chrono::seconds(n)); std::cout << c.substr(0,n) << std::endl; f(n < c.size() ? c.substr(n) : ""); } int main(){ std::string s="abcdefghijklmnopqrstuvwxyz"; f(s); }  • using namespace std; should save 5 bytes from all of those std::s Dec 5, 2016 at 14:25 • @AlfieGoodacre the 5th std:: is only in the usage code, in the golfed one there are only 4 Dec 5, 2016 at 17:02 • Ah so it's identical! Dec 5, 2016 at 17:02 C#, 205 bytes void X(string s){Random r=new Random();int n=r.Next(1,11);while(n<s.Length){Console.WriteLine(s.Substring(0,n));s.Remove(0,n);n*=1000;System.Threading.Thread.Sleep(n);n=r.Next(1,11);}Console.WriteLine(s);}  I'm sure this can be destroyed, I haven't really optimised it at all as it stands. Un-golfed: void X(string s) { Random r = new Random(); int n = r.Next(1,11); while(n < s.Length) { Console.WriteLine(s.Substring(0,n)); s.Remove(0,n); n *= 1000; System.Threading.Thread.Sleep(n); n = r.Next(1,11); } Console.WriteLine(s); }  PHP, 74 bytes for($s=$argv[1];$s[$p+=$n]>"";print substr($s,$p,$n))sleep($n=rand(1,10));


Run with php -r 'code' "string".

C, 149 bytes, not tested

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int f(char *s){int n;while(*s){sleep(n=rand()%10+1);for(;*s&&n--;s++)printf("%.*s",1,s);}}


int main(){f("Programming Puzzles & CodeGolf");}


then compile and execute

• The function rand is not random, it always returns numbers from the same sequence. Oct 16, 2020 at 21:36

Python 3, 99 chars

i=input()
import os,time
while len(i):n=1+ord(os.urandom(1))%10;time.sleep(n);print(i[:n]);i=i[n:]


Assembly (NASM, 32-bit, Linux), 278 bytes

The signature is void f(char* msg, int len). The standard x86 calling convetion is used. Therefore, msg is in ecx, and len is in edx. The random number is generated as time(0)%10+1.

f:push ebx
mov esi,ecx
mov edi,edx
push 0
l:mov ebx,0
mov eax,13
int 128
mov edx,0
mov ecx,10
div cx
inc dx
push edx
mov cx,0
mov ebx,esp
mov eax,162
int 128
pop edx
cmp edx,edi
cmova dx,di
mov ecx,esi
mov ebx,1
mov ax,4
int 128
sub edi,edx
jnz l
pop eax
pop ebx
ret


Try it online!

C++ (gcc), 109 bytes

#include<unistd.h>
int f(char*s){for(int n,m=0;*s;)for(sleep(m=n=(getpid()+m)%10+1);*s&&n--;)write(1,s++,1);}


Try it online!

-10 bytes thanks to ceilingcat

-8 bytes thanks to ceilingcat

C (gcc), 71 bytes

n;f(char*s){while(*s)for(sleep(n=time(0)%10+1);*s&&n--;)putchar(*s++);}


Try it online!

-1 byte thanks to ceilingcat