text:
C.U.S.R.S - The Completely Useless String Refactoring System!
Introduction
I'm a real big fan of the SBU (Short But Unique) challenges that crop up on PPCG all of the time. The CUSRS is a system designed to refactor strings, a CUSRS function takes 2 parameters and outputs 1 String.
Challenge
Produce a program, function, lambda or acceptable alternative to do the following:
Given String input and String refactor (as examples), refactor input using refactor as follows:
The refactor String will be in the format of ((\+|\-)\w* *)+ (regex), for example:
+Code -Golf -lf +al

Each section is a refactoring action to perform on input. Each program also has a pointer.
+ Will insert it's suffix (without the plus) at the pointers current location in the String and then reset the pointer to 0.
Each operation should be applied to the input String and the result should be returned.
Example:
input:
Golf +Code //pointer location: 0

output:
CodeGolf //pointer location: 0

- Will increment the pointer through the String until it finds the suffix. The suffix will be removed from the String and the pointer will be left on the left side of the removed text.  If no suffix is found the pointer will simply progress to the end of the String and be left there.
input:
Golf -lf //pointer location 0

output:
Go //pointer location 2

Examples
input:
"Simple" "-impl +nip -e +er"

output:
"Sniper"

input:
"Function" "-F +Conj"

output:
"Conjunction"

input:
"Goal" "+Code -al +lf"

output:
"CodeGolf"

input:
"Chocolate" "Chocolate"

output:
"Chocolate" //Nothing happens...

input:
"Hello" "-lo+p        +Please" //Spaces are irrelevant

output:
"PleaseHelp"

input:
"Mississippi" "-s-s-i-ppi+ng" //Operations can be in any order

output:
"Missing"

input:
"abcb" "-c -b +d"

output:
"abd"

input:
"1+1=2" "-1+22-=2+=23"

outut:
"22+1=23"

Example Code
The example is Java, it's not golfed at all.
public static String refactor(String input, String swap) {
    int pointer = 0;
    String[] commands = swap.replace(" ", "").split("(?=[-+])");

    for (String s : commands) {
        if (s.startsWith("+")) {
            input = input.substring(0, pointer) + s.substring(1) + input.substring(pointer, input.length());
            pointer = 0;
        } else {
            if (s.startsWith("-")) {
                String remove = s.substring(1);
                for (int i = pointer; i < input.length(); i++) {
                    if (input.substring(i, i + remove.length() > input.length() ? input.length() : i + remove.length()).equals(remove)) {
                        pointer = i;
                        input = input.substring(0, i) + input.substring(i + remove.length(), input.length());
                        break;
                    }
                }
            }
        }
    }

    return input;
}

Rules

Standard Loopholes Apply
Shortest code, in bytes, wins

Related

What should be the output for aaa -a?

|aa with the pipe being the pointer.

@Emigna Upon looking at the question in question, I believe the implementation of mine would be much different.

What happens with - if the suffix isn't found?

aaa -b +b would result with aaab because the pointer would go all the way to the end.

Can we assume input without spaces...

Your example is abit confusing, You should seperate what is the input and what is the refractor string to make it more clear

@Zgarb Nothing.

Python 3 (164 194 186 181 168 165 bytes)
p=0
w,*x=input().split()
for i in x:
 if '-'>i:w,p=w[:p]+i[1:]+w[p:],0
 else:
  try:p=w.index(i[1:],p)
  except:p=len(w)
  w=w[:p]+w[p:].replace(i[1:],'',1)
print(w)

Example demonstrating the pointer moving to the end if it doesn't find a substring:
Input: HelloThere -x +Friend
Output: HelloThereFriend

Special thanks to Artyer for saving me 13 bytes.
Another thanks to Artyer for saving me another 3 bytes via the beg parameter of index.
Old answer:
p=0
x=input().split()
w=x[0]
for i in x[1:]:
 if i[0]=='+':
  w=w[:p]+i[1:]+w[p:]
  p=0
 else:
  p=w[p:].index(i[1:])+p
  w=w[:p]+w[p:].replace(i[1:],'',1)
print(w)

Example demonstrating the pointer works (all the examples in the Q work even if you don't factor in the pointer and simply replace on first occurence):
Input: HelloThereCowboy -r -e -y +ySays +Oh
Output: OhHelloTheCowboySays

Edit: Since 2 minutes ago my answer is now invalid according to a comment by the asker.

aaa -b +b would result with aaab because the pointer would go all the
  way to the end.

Edit2: Fixed.

w,*x=input().split(), and if'-'>i: instead of if i[0]=='+':and tab character for 2 indents instead of 2 spaces will save some bytes

If I try to mix tabs and spaces I get TabError: inconsistent use of tabs and spaces in indentation. Thanks for the suggestions, I didn't know about those features! I'll begin adding them immediately.

@redstartcoder I guess the tab trick only works in Python 2. My bad

I could absolutely be wrong here, but I think strings have a find method which will return -1 if it can't find the substring. Since -1 points to the back of the string, all you would need to do is take a modulus of p by the length of w which should mean you don't need a try-except.

I'll look into implementing it (I guess I'm not allowed to edit that comment?)

-1%0 produces ZeroDivisionError, but find definitely works and I think is promising...

You would do -1%len(str) to get the index at the end of string. str.index and str.find also take a start parameter, so I assume you can replace w[p:].index(i[1:]) with w.index(i[1:],p). Overall, it would be else:p=(w.find(i[1:],p)+p)%len(p);w=w[:p]+w[p:].replace(i[1:],'',1).

Your code doesn't work as-is (even with len(p) to len(w)), I'll look into why when I wake up a bit more.

GolfScript, 97 Bytes
" "%(:s;0:p;{("-"0=={.s p>\?.-1={;;s,:p;}{:p;,:l;s p<s p l+>+:s;}if}{s p<\+s p>+:s;0:p;}if}/"\n"s

Test: golfscript.tryitonline.net

Welcome to PPCG! You can use the interpreter on Try it online, which does support input.

APL, 91 90 bytes
{s l←⍵0⋄s⊣{g←1↓⍵⋄'+'=⊃⍵:+s∘←(l↑s),g,l↓s⋄l∘←¯1+1⍳⍨g⍷s⋄+s∘←(l↑s),s↓⍨l+⍴g}¨{1↓¨⍵⊂⍨⍵=⊃⍵}' ',⍺}

This takes the string as its right argument, and the commands as its left argument, like so:
      '+Code -al +lf' {s l←⍵0⋄s⊣{g←1↓⍵⋄'+'=⊃⍵:+s∘←(l↑s),g,l↓s⋄l∘←¯1+1⍳⍨g⍷s⋄+s∘←(l↑s),s↓⍨l+⍴g}¨{1↓¨⍵⊂⍨⍵=⊃⍵}' ',⍺} 'Goal'
CodeGolf

JavaScript (ES6), 117 bytes
(s,r,t='')=>r.match(/\S\w*/g).map(r=>(q=r.slice(1),r<'-'?(s=t+q+s.t=''):([b,...a]=s.split(q),t+=b,s=a.join(q))))&&t+s

Explanation: Instead of using a cumbersome pointer, I keep the left half of the string in t and the right half in s. Additionally, split and join are a convenient way to perform the removal.


text:
Is it a Linearized Tree? (Breadth-first Edition)
Background
An unlabelled tree may look like this:
   o
 / | \
o  o  o
|    / \
o   o   o

To linearize this tree, we first label each node o with it's number of child nodes:
   3
 / | \
1  0  2
|    / \
0   0   0

and then write the numbers in a list in a breath-first manner, meaning line by line and left to right:
[3, 1, 0, 2, 0, 0, 0]

This is a unique and unambiguous representation of the tree above, meaning that no two different pure trees will have the same linearizations and that we can reconstruct the original tree from the list.
Although each tree corresponds to a certain integer list, not each integer list represents a valid linearized tree: For example [2, 0, 0, 0] does not represent a valid tree, if we try to de-linearize it we end up with this tree
[2,0,0,0] -> 2 [0,0,0] -> 2 [0,0] -> 2 [0]
            / \          / \        / \
                        0          0   0

but still have a 0 left in the list and nowhere to put it. Similarly [2, 0] is not a valid tree linearization either, as the de-linearized tree has an empty child spot:
  2
 / \
0

Task
Given an integer list, decide whether it is a valid linearization of a tree using as few bytes as possible. You may write a full program or a function.
Input:  A non-empty list of non-negative integers.
Output:  A truthy value if the list is a linearization of a tree, a falsy value otherwise.
Testcases

Truthy

[0]
[2, 0, 0]
[1, 1, 1, 1, 1, 0]
[3, 1, 0, 2, 0, 0, 0]
[2, 0, 2, 2, 0, 0, 2, 0, 0]
[3, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0]
[1, 5, 3, 0, 2, 1, 4, 0, 1, 0, 0, 2, 1, 0, 0, 1, 1, 0, 0, 0, 0, 2, 1, 0, 0, 1, 0]

Falsy

[0, 1]
[2, 0]
[2, 0, 0, 0]
[1, 0, 1]
[3, 2, 1, 0]
[2, 0, 0, 2, 0, 0]
[4, 1, 0, 3, 0, 0, 0, 0]
[4, 2, 0, 3, 1, 0, 0, 0, 0, 0]

Haskell, 44 bytes
f[n:k]=iterate f[k]!!n
f _=[]
g x=f[x]==[[]]

Defines a function g that takes a list and returns a boolean.
See it pass all test cases.
Explanation
This relies on the fact that depth-first and breadth-first linearizations produce the same arrays.
See Martin's answers for details; basically they both give the same arithmetical condition on the array.
The function f is given the input list wrapped in a singleton list.
It pops one number n off the list, then calls itself n times on the remaining list to process the children of the popped node (depth first).
Popping the empty list results in [], which I use as an error state.
The function g checks that the end result is [[]], the unique non-erroneous state with no unprocessed nodes.
If Haskell was weakly typed, I could just use 0 or something as the error state, and wouldn't have to wrap the input into another list.

Mathematica, 38 bytes
Last@#<0<=Min@Most@#&@Accumulate[#-1]&

The basic idea is that we keep track of a number of nodes to fill. Each element in the list uses up one node and adds as many as it has children. So each element i changes the total count by i-1. This count is off by one, because should be starting from 1 (the root), not 0.
For the tree to be valid we a) can never go below 0 throughout the list, because we wouldn't have anywhere to place the current node and b) need to end up with -1 at the end, otherwise we've got unused nodes left.
We obtain this running total of remaining nodes with Accumulate[#-1] (which computes the prefix sums of the input list minus one). And then we check that the last element and only the last element is -1 with:
Last@#<0<=Min@Most@#

Note that checking that the last element is negative is sufficient, since we can never decrement by more than 1, so if the last values was -2 or lower it would be impossible for the minimum the others to be non-negative.

Retina, 29 bytes
\d+
$*
^(?<-1>(1)*,)*$(?(1)!)

Try it online! (The first line enables a linefeed-separated test suite.)
Explanation
The basic idea is the same as that of my Mathematica answer: we keep track of a running total of remaining nodes, ensure it never goes below zero but ends on zero. However, the way this is implemented with regex is very different.
\d+
$*

This simply converts the input to unary, turning each integer n into n 1s.
^(?<-1>(1)*,)*$(?(1)!)

This is where the real magic happens. It's a fairly short regex that matches only valid trees, but it's mechanics are quite subtle.
I'm using balancing groups to keep track of the number of nodes, which are a way to work with stacks inside the regex.
First off, of course such a stack can never have a negative depth, so we can't really end up with a representation of -1 at the end, as we do in the Mathematica solution. However, we can note that the final element of the input has to be zero on a valid stack (otherwise we couldn't end up with -1). It turns out that it actually saves bytes to check both that we end on zero and with zero remaining nodes.
So here is a breakdown of the regex:
^        e# Anchor the match to the beginning of the string.
(?<-1>   e# Each repetition of this group will match one number.
         e# We can ignore the <-1> for now.
  (1)*   e#   Match each unary digit of the current number, pushing
         e#   a capture onto stack 1. This increments our total of
         e#   remaining nodes by 1 for each child.
  ,      e#   Match a comma. Note that this requires that there is at
         e#   least one more number in the list.
)*       e# At the end of the repetition the <-1> pops one capture from
         e# the stack. This is the node that the current number itself
         e# takes up.
$        e# Match the end of the string. This requires the input to end
         e# in a zero, because the last thing we matched was a comma.
(?(1)!)  e# Make sure that stack 1 is empty, so that we don't have any
         e# unused nodes.

CJam (20 bytes)
{X0@{+\(_0>{\}*}/|!}

Online test suite. This is an anonymous block which takes an array on the stack and leaves 0 or 1 on the stack.
Dissection
In pseudocode this is:
p = 1
q = 0
foreach (i in input):
  q += i
  if (--p <= 0):      # in practice, if (--p == 0):
      p, q = q, p
return (p | q) == 0   # i.e. p == 0 && q == 0

q accumulates the sum of the labels of the nodes at the current level in the tree; p counts down the nodes remaining in the current level.

{X0@{+\(_{\}&}/|!} I think?

Also it seems like you should be able to save a byte by using a full program to avoid the @.

Labyrinth, 17 bytes
(
+?
;-)
,_"
@@,!

Try it online!
Truthy output is -1 and falsy output is empty. Defining truthy and falsy in Labyrinth is a bit tricky, because Labyrinth's branches are principally ternary. However, the only way to construct a conditional with reliably two branches, you can only do this:
>"F
 T

In this case, I'd consider moving straight ahead falsy (because the direction of movement is unaffected) and turning truthy. These correspond to zero and non-zero respectively. The reason I'm using an empty output to represent zero is that, if you were to pipe the output back into another Labyrinth program, the input operator ? would actually push a zero if the input is empty, so I consider the empty string a valid representation of zero.
Explanation
The algorithm is still the same as in my Mathematica and Retina answers, but due to Labyrinth's control flow, it works a bit different this time:

We don't work with the total counter off-by-one here. Instead we a) work with a negative counter and b) initialise it to -11 initially, so that we want the counter to be negative throughout the list and hit zero on the last input. This actually simplifies the control flow here.
Instead of building the full list and checking whether it contained the wrong value, there are three possible termination conditions:

We hit EOF before reaching a total count of zero. In that case there are unused nodes left and we print nothing.
We reach zero and we're at EOF. In this case, we've got a valid tree.
We reach zero and aren't at EOF yet. In this case, we ran out of nodes before covering all elements, and we print nothing.

As for the actual code, we start in the top left corner. The ( turns the implicit zero on top of the stack into a -1, which will be the running total. We then enter the very tight main loop of the program, +?-)"_,;+:
+   Add the top two values. This does nothing on the first iteration,
    but gets rid of a helper-zero on subsequent iterations.
?   Read and push integer.
-   Subtract it from running total.
)   Increment.
"   No-op. There is a branch at this point. If the running total is zero,
    we move straight ahead onto the , (see below). Otherwise, the loop continues.
_   Push a zero. This is necessary to prevent the IP from turning south.
,   Read a character. This will either be the next separator (some positive
    number) or EOF (-1). If it's EOF, the IP turns south and the program
    terminates. Otherwise, the loop continues.
;   Discard the separator.

That leaves only the cases where we've reduced the running total to zero at some point. The IP moves onto the lower-right , and reads another character to check if we've reached EOF. If not, the value will be positive and the IP turns west towards the @ and the program terminates. If we did reach EOF, the IP turns east and prints the -1 with !. The IP will then worm its way towards the lower left @ via a slightly weird path to terminate the program.

Python, 82 bytes
lambda l:len(l)==sum(l)+1 and not any(list(l[x]>=len(l)-x for x in range(len(l))))

Need more test cases.

You shouldn't need to cast with list if this is Python 2 at least, and by rearranging and inverting the second condition you can get it to 70 bytes: lambda l:all(l[x]<len(l)-x for x in range(len(l)))and len(l)==sum(l)+1

^ In relation to this, you can change the body of all to be x<len(l)-y for y,x in enumerate(l) to save another 2 bytes to get it to 68.

I'm not golfing this further right now because I don't think it's an accurate solution. Thanks for the tips.

Pyth, 13 bytes
qxsM._tMQ_1tl

We start by calculating the current filled-ness of the tree at all points in the input representation. That portion of the idea is largely borrowed from Martin Ender, so thanks to him. sM._tMQ
Once we have this list, we check if the first index containing -1 (x..._1) is the length of the input minus one (q...tl(Q)).
Don't believe it works? Try it yourself!

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
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:

Generate a (not necessarily uniformly) random integer n between 1 and 10, inclusive.
Wait n seconds.
Print the initial/next n chars of the input, or the rest of the input if there are less than n chars.
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 code-golf, so the shortest code in bytes wins.

Comments are not for extended discussion; this conversation has been moved to chat.

Can we use spaces for languages that does not support waiting/do not have a notion of time ?

I bet any language has a way to spend time without producing output, @FliiFe!

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?

This is not a valid scoring method. See meta post.

Would you be willing to fix it based on the community consensus?

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.

Pushy, 20 17 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

@LuisMendo ok, thanks for the clarification :)

Nice answer BTW :-)

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.

Python 3 is one byte longer. Insert a '(' between print and 'i' and a ')'  before the bracket

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)

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:])

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.

@zeppelin Fair point, according to the standard definition it doesn't count. (http://meta.codegolf.stackexchange.com/a/1325/56071). I shall change it accordingly.

You can also save a pair of bytes, by removing  "|0"

@zeppelin I don't think I can remove |0. It's there to round down the random number. If I don't do then the timeout might be longer than the spec allows.

just give it a try :) ("abc".slice(1.99999999)=="abc".slice(1))

The largest timeout you can get w/o rounding is: (1+0.99999999*10)*999 = 10988.9999001, which is within the 10% margin of error, as allowed by the task.

@zeppelin The problem is at the other end of the spectrum: (1+0.099999*10)*999 > 1997. As you have shown yourself, this will mean n===1 for the rest of the computation, but it will wait almost twice as long, as it should :)

You know, you can express 1000 in three bytes too: 1e3 ;-)

@ETHproductions Oh, good point. That is nicer. Thank you.

(1+0.099999*10)999 > 1997
True, but you can probably replace 999 with <<10, to work around this:
(1+0.09999910)<<10 => 1024, (1+0.9999999910)<<10 => 10240

@zeppelin Yes, this last one is very nice. Thank you very much. :)

I believe setTimeout accepts a string to be eval'd as well, which could save a byte by getting rid of the _=> at the cost of a pair of quotes

@jrich Unfortunately, afaik that string is eval'd in the global scope and will therefore not have access to s.

@Lmis Argh, didn't consider that. Sorry :(

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

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

@Octopus It doesn't matter, since it will sleep for no time and produce no output in that case.

Fixed the typo in my explanation.

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!

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

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

@AlfieGoodacre the 5th std:: is only in the usage code, in the golfed one there are only 4

Ah so it's identical!

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

to run, add
int main(){f("Programming Puzzles & CodeGolf");}

then compile and execute

The function rand is not random, it always returns numbers from the same sequence.

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:]

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

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

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
add esi,edx
sub edi,edx
jnz l
pop eax
pop ebx
ret

Try it online!

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Figure and Ground

Source: Wikipedia
For this challenge, you should write two programs which resemble the figure and ground of the above image, such that one of them prints figure and the other prints ground. Specifically:

Write a program which takes no input and prints the string figure. The only allowed whitespace characters in your program are spaces (code point 0x20) and newlines (carriage returns, 0x0D, linefeeds, 0x0A, or a combination of both).
Ignoring the newlines, the number of space characters (code point 0x20) and non-space characters has to be the same. For example, this would be a valid program (in a hypothetical language):
ab c
   d
e f

Note that there is a trailing space on the first line.
If you swap the nth space character with the nth non-whitespace character, the program should print ground instead. For the above example the program would look like this:
  a b
cde
 f

Note that there are trailing spaces on the second and third lines.

Both the figure and the ground solutions should be full programs in the same language which print to STDOUT. You may print a single optional trailing newline in either case. You may output anything you want to STDERR, as long as STDOUT is correct.
You may use any programming language, but note that these loopholes are forbidden by default.
This is code-golf, so the shortest valid answer – measured in bytes – wins.
Helper Script
You can use this CJam script to convert between a figure and ground program. Simply paste one of the two into the Input field and run the program. It will also tell you if there the number of spaces and non-spaces doesn't match up.
Leaderboard

function answersUrl(a){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+a+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(a,b){return"http://api.stackexchange.com/2.2/answers/"+b.join(";")+"/comments?page="+a+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(a){answers.push.apply(answers,a.items),answers_hash=[],answer_ids=[],a.items.forEach(function(a){a.comments=[];var b=+a.share_link.match(/\d+/);answer_ids.push(b),answers_hash[b]=a}),a.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(a){a.items.forEach(function(a){a.owner.user_id===OVERRIDE_USER&&answers_hash[a.post_id].comments.push(a)}),a.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(a){return a.owner.display_name}function process(){var a=[];answers.forEach(function(b){var c=b.body;b.comments.forEach(function(a){OVERRIDE_REG.test(a.body)&&(c="
"+a.body.replace(OVERRIDE_REG,"")+"
")});var d=c.match(SCORE_REG);d?a.push({user:getAuthorName(b),size:+d[2],language:d[1],link:b.share_link}):console.log(c)}),a.sort(function(a,b){var c=a.size,d=b.size;return c-d});var b={},c=1,d=null,e=1;a.forEach(function(a){a.size!=d&&(e=c),d=a.size,++c;var f=jQuery("#answer-template").html();f=f.replace("{{PLACE}}",e+".").replace("{{NAME}}",a.user).replace("{{LANGUAGE}}",a.language).replace("{{SIZE}}",a.size).replace("{{LINK}}",a.link),f=jQuery(f),jQuery("#answers").append(f);var g=a.language;g=jQuery(""+g+"").text(),b[g]=b[g]||{lang:a.language,lang_raw:g,user:a.user,size:a.size,link:a.link}});var f=[];for(var g in b)b.hasOwnProperty(g)&&f.push(b[g]);f.sort(function(a,b){return a.lang_raw.toLowerCase()>b.lang_raw.toLowerCase()?1:a.lang_raw.toLowerCase()<b.lang_raw.toLowerCase()?-1:0});for(var h=0;h<f.length;++h){var i=jQuery("#language-template").html(),g=f[h];i=i.replace("{{LANGUAGE}}",g.lang).replace("{{NAME}}",g.user).replace("{{SIZE}}",g.size).replace("{{LINK}}",g.link),i=jQuery(i),jQuery("#languages").append(i)}}var QUESTION_ID=101275,ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",OVERRIDE_USER=8478,answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:350px;float:left}table thead{font-weight:700}table td{padding:5px}
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

Jelly, 20 bytes
Figure
“¦ĠȮ“©ụd» Ṃ

Nine trailing spaces. Try it online!
Ground
         “ ¦ĠȮ“©ụd»Ṃ

No trailing spaces. Try it online!
How it works
First, note that spaces aren't atoms, so the space characters outside the string literals do not affect the program in any way.
The string literals use Jelly's built-in dictionary-based string compression to produce the desired words. A compressed string literal begins with “, ends with », and uses “ internally to create an array of strings.
In the figure program, “¦ĠȮ“©ụd» yields the string pair (“figure”, “ground”), and the atom Ṃ selects the lexicographical minimum, i.e., “figure”.
In the ground program, “ ¦ĠȮ“©ụd» yields the string pair (“logicallyAbacs”, “ground”) instead. The lexicographical minimum is now “ground”, which Ṃ selects dutifully.
In both cases, the interpreter automatically prints the last return value – i.e., the selected minimum – to STDOUT.

05AB1E, 15 14 bytes
Figure
 'ŠÂ,'í¶

Try it online!
Ground
'       ŠÂ,'í¶

Try it online!
Uses the CP-1252 encoding. Note the trailing spaces. In the Figure program, it's a normal program without errors. It decompresses the following words:
'ŠÂ  ->  figure
'í¶  ->  ground

The comma prints pops and prints the figure  word with a newline. Since something has been printed, the top of stack is not printed anymore.
In the Ground program, there are some errors which is convenient in this case. The following part:
'<space>

pushes a space character on top of the stack. The Š rotates the stack, which has an arity 3. There is just one element on the stack and no input, so this gives an exception, clearing the stack. The Â bifurcates the top of the stack, but this has the same story as the rotate operator. So basically the , command prints nothing.
That means that the program will still output the top of the stack which is 'í¶. Resulting into ground.

Python 2, 53 bytes
Replace · with space in both answers:
····················
print'······figureground'[6:12]#

Prints figure.
print'figureground'[
······6:12]#····················

Prints ground.

Retina, 31 bytes
Figure:
|
figure
 |ground

Ground:
 |figure

|
ground
Figure and Ground. Both programs require that STDIN be left empty to be valid figure or ground programs.

Pyth, 30 bytes
Figure
"figure" "ground

14 trailing spaces.
Test
Ground
No trailing spaces
        "       figure""ground

Test
How it works
Rather helpfully, a space supresses printing in Pyth, while string literals with no closing " are implicitly closed.
The first program therefore consists of two strings, "figure" and "ground              ". The first string is implicitly printed, and the printing of the second is supressed, meaning that just figure is printed.
The second program consists of two strings, "       figure" and "ground". The printing of the first is supressed, and the second is implicitly printed, meaning that just ground is printed.

MATL, 37 bytes
First program
'figure'
%x'ground'

Each line has 9 trailing spaces.
Try it online!
Second program
    'figure'%
      x'ground'

There are no traling spaces here.
Try it online!
Explanation
Nothing terribly fancy...

Spaces and newlines between statements are ignored by MATL.
% is the comment symbol, which ignores the rest of the line.
x deletes the top of the stack.
The stack is implicitly printed at the end of the program.

Java, 180 bytes
Replace . with space.
Prints "figure":
class
A{public
static
void
main(String[]a){System.out.println(
//"ground"
//
.....
........
......
....
...................................
..
........
..........
....
"figure");}}

Prints "ground":
.....
........
......
....
...................................
..........
..
class
A{public
static
void
main(String[]a){System.out.println(
//
"ground"
//"figure"
);}}
............

Befunge, 54 bytes
Figure (Try it online!)
#v "erugif"v          >
      :#,_@>
"dnuorg"
Ten trailing spaces on the second line.
Ground (Try it online!)
  #         v"erugif"v
>:#,_@      >"dnuorg"

One trailing space on the first line and eight spaces on the third line.

Mathematica, 50 34 bytes
Uses a REPL environment. (Adding a Print[] wrapper with an equal number of spaces would increase the byte count by 14.) The two programs are
01figure+0 1ground

(with 16 trailing spaces) and
          0       1figure+01ground

The key here is that Mathematica treats digit concatentation without spaces as a single number, but intervening spaces are interpreted as neighborly multiplication, as is the concatenation of numbers and arbitrary variable names. So the first expression evaluates to 1*figure+0*1*ground, which is figure; the second expression evaluates to 0*1*figure+1*ground, which is ground.

PHP, 44 42 bytes
figure: (16 trailing spaces, 5 spaces between figure & ;)
echo''?ground:figure     ;

ground: (20 leading spaces)
                     echo' '?ground:figure;

Pretty simple really, works because '' is falsey and ' ' is truthy. Use like:
php -r "echo''?ground:figure     ;                "
php -r "                    echo' '?ground:figure;"

edit: 2 retrospectively obvious bytes saved thanks to Martin Ender

Haskell, 96 94 88 82 77 bytes
First program, prints "figure":
main              =          putStr$idid"ground"
idid    _          ="figure"

Second program, prints "ground":
    main=putStr$id id"ground"
    idid _="figure"

Calls one of two differently named constant functions

Haskell, 88 65 bytes
main=putStr
...........--
.."figure"..........
--"ground"........

and
...........
main=putStr..
--........"figure"--
.........."ground"

. indicates a space. Just some line comment (-> --) juggling.

JavaScript (ES6), 56 bytes

alert('figure'
                //&&'ground'
           )

alert('figure'//
&&'ground')

The figure has no trailing spaces.

I count 56 bytes for each program, unless the newlines don't count. I doubt it will get any shorter.

@ETHproductions Ugh, that's what happens when you count bytes manually :-(

Python 2, 52 bytes
........................
print"figure"
an
d
"ground"

.s indicate spaces. The last three lines are split up to error out without having a SyntaxError which would prevent the code from running in the first place.
The ground version just uses and to make the second string be printed.

Alternative (longer) attempts:
.......
print(#"ground")#
"figure")...................

print"figure"""and"ground"
.............
.............

Rail, 56 bytes
Figure
$'main'
 -[figure]o
-          [ground]o

There are 16 trailing spaces on the second line. The program terminates with an error.
Try it online!
Ground

$          'main'-[figure]o
 -[ground]o
There are 7 spaces on the first line and 9 trailing spaces on the last line. This program also terminates with an error.
Try it online!
Explanation
Rail looks for a line starting with (regex notation) \$.*'main' to find an entry point. The train (instruction pointer) then starts from the $ moving south-east. Things that aren't reachable by the train can be ignored completely for the program. This includes anything on the same line as the entry point. Since, the - south-east of the $ immediately turns the train east, both programs simply reduce to:
 -[figure]o

 -[ground]o

[...] denotes a string literal and o prints it. Normally, you need a # to end the rail, but if you omit it, the program terminates anyway (but complains on STDERR that the train crashed).

><>, 39 bytes
Using · to represent spaces.
Figure
v·
"·dnuo
e·
r·
u·
g··
i··
f···
"·
>·o·

Try it online!
Ground
·v
·"····
·d
·n
·u
·oe
·ru
·gif
·"
·>·o

Try it online!
Both programs terminate with an error.
Explanation
By writing the code vertically, I was able to reuse the g and the r between both solutions, as well as the quotes and the > and o for the output loop.
In both cases, the only bit that gets executed is the column below the v, which pushes the letters of the required word onto the stack in reverse order. Then > redirects the instruction pointer to the right, where it loops through the o, printing the characters until the stack is empty.

I just started working on my own ><> version, then I came across yours. I really like the idea of yours working vertically (mine is very 'normal').

@Tealpelican I didn't come up with this until working out the Fission answer. Before that my best ><> solution was 42 bytes: !__|"druong">o<"figure" (where _ are spaces, and the remaining spaces simply go at the end of the line).

My shortest current version is this;##  "  de  nr  uu  og  ri  GF" > o!  ~ ~!  < ## Which funny enough is 42 bytes also! My previous versions had error checking but could only reduce to 53 bytes.

Fission, 37 bytes
Using · to represent spaces.
Figure
D·
"···
f··
i··
g·
u·
r·
e·ound
"·
;·

Try it online!
Ground
·D
·"fi
·gu
·re
·o
·u
·n
·d····
·"
·;

Try it online!
Explanation
Works basically the same as my ><> answer (although I actually found this one first). The only differences are that " prints the characters immediately in Fission, which is why the words aren't written upside down and why we only need to terminate the program with ; at the end.

Brian & Chuck, 55 53 bytes
Figure
erugif?dnuorg
}<.<.<.<.<.<.

There are 13 trailing spaces on each line.
Try it online!
Ground
             erugif?dnuorg
             }<.<.<.<.<.<.

Try it online!
Explanation
Ah, it's been a while since the last time I used Brian & Chuck. As a short reminder, Brian and Chuck are two Brainfuck-like instances, which use each others' source code as their tape. Only Chuck can use the printing command ., ? switches between the two instances conditionally, and } is sort of like [>] in Brainfuck. Unknown commands are simply ignored.
Since the spaces at the beginning of the programs are ignored, the two programs are almost identical. The only difference comes from the fact that after the switching command ?, the instruction pointer moves before executing the next command. Hence, the first command on Chuck's tape is always skipped. So the only real difference is that the ground program executes the } whereas the figure program doesn't. So here is how the code works:
?   Switch control to Chuck.
}   GROUND PROGRAM ONLY: Move the tape head on Brian to the end of the tape.
<.  Move the tape head left and print the character there.
... Do the same another five times to print the remainder of the string.

reticular, 46 bytes
                      "ground""figure"" "?$$o;

Try it online! This prints ground.
"ground""figure"""?$$o                 ;

Try it online! This prints figure.
ground
Relevant code:
"ground""figure"" "?$$o;
................          push these two strings
                " "?$     pop " " off (since " " is truthy, `?` executes `$`)
                     $    pop TOS ("figure")
                      o;  output and terminate

figure
Relevant code:
"ground""figure"""?$$o;
................         push these two strings
                ""?$     doesn't activate
                    $    pop ""
                     o;  output and terminate

WinDbg, 74 bytes
Ground
                      ea2000000"      groundfigure";;;da       2000006  L6

Figure
ea2000000"groundfigure          ";;;da                  2000006       L6

Figure has 2 trailing spaces. I feel like at least 2 or 4 bytes ought to be golfable...
It works by writing a string to memory and showing 6 chars from it. The chars in the string are re-arranged so the shown chars change between the programs:
* Ground:
ea 2000000 "      groundfigure";     * Write string "      groundfigure" starting at 2000000
;                                    * No-op
;                                    * No-op
da 2000006 L6                        * Print 6 ascii chars, from 2000006, ie- ground

* Figure:
ea 2000000 "groundfigure          "; * Write string "groundfigure          " to memory
;                                    * No-op
;                                    * No-op
da 2000006 L6                        * Print 6 ascii chars, ie- figure

Output:
0:000>                       ea2000000"      groundfigure";;;da       2000006  L6
02000006  "ground"
0:000> ea2000000"groundfigure          ";;;da                  2000006       L6
02000006  "figure"