text:
Color me a Pole
Lets say your job is to paint poles, and a client asks you to paint a pole with 4 red sections and 3 yellow sections.  You can do that pretty easily as follows:
r y r y r y r

With just yellow and red stripes.  Now lets say your client asks you to paint a pole with 2 red sections, 2 yellow sections, and 1 green section.  There are a couple of ways you could paint your pole
g y r y r
y g r y r
y r g y r
y r y g r
y r y r g
g r y r y
r g y r y
r y g r y
r y r g y
r y r y g
y r g r y
r y g y r

More precisely thats 12 ways to paint the pole.  This blows up the more colors and sections that are involved
Now if your client says they want 3 red sections and 1 yellow section there is no way to paint a pole like that.  Because no matter how you attempt to arrange the sections two red sections will touch, and when two red sections touch they become a single red section.
And that is pretty much our one rule for painting poles

Adjacent sections may not be of the same color

Task
Given a list of colors and sections required, output the number of possible ways to paint a pole as requested.  You may represent colors in any reasonable way (integers, characters, strings), but you will never be given more than 255 different colors at a time.  If you wish you can even choose to not have the colors assigned names and just take a list of section counts if that is easier.
Test Cases
These are rather hard to calculate by hand, especially as they get larger.  If anyone has a suggested test case I'll add it.
[4,3]    -> 1
[2,2,1]  -> 12
[3,1]    -> 0
[8,3,2]  -> 0
[2,2,1,1]-> 84

May we take input as, for example, "rrrryyy" for [4,3]?

@Leo Sure that is perfectly reasonable.

Can I get input as [1, 1, 1, 1, 2, 2, 2]? I suppose so.

@EriktheOutgolfer Yes that is also a reasonable input method

If you take in a list of colors, may you assume it to be sorted?

@xnor Yes you may,

Turns out the closed form solution is pretty damn hard for even professional mathematicians...

Not super important, but capitalizing the word Pole makes it sounds like you are talking about a person from Poland.

Mathematica, 37 44 48 60 62 bytes
Take input as a list of integers {1, 1, 1, 2, 2}. Try it on Wolfram Sandbox.
Pattern-matching method, thanks @Not a tree !
Count[Split/@Permutations@#,{{_}..}]&

Split splits a single list into sublists of consecutive elements, e.g. {1, 1, 2, 3, 4, 4} into {{1, 1}, {2}, {3}, {4, 4}}
{{_}..} is, namely, {{_}, {_}, {_}, ...}. The pattern matches a list of unary sublists.
Differences method, 48 bytes:
Tr@Abs@Clip[1##&@@@Differences/@Permutations@#]&

The code uses Differences to determine whether adjacent elements are the same.
Step by step:

Permutations@# generates all permutations of input list to a N!*N list.
Differences/@ calculates the difference between N elements, and yields a N!*(N-1) list.
1##&@@@ calculates the multiplication of all lists. If a list contains 0 (two adjacent elements are the same), the result will be 0, otherwise non-zero, to a N! list.
Clip[] acts like Sign[],  transform the list from (-inf, inf) to [-1, 1]
Tr@Abs turns all -1 into 1 and now the N!-length list contains only 0 (invalid) and 1 (valid). So we just sum the list.

You can save 4 bytes with some pattern matching: Permutations@#~Count~Except@{___,x_,x_,___}&.

I have another one: Count[Split/@Permutations@#,{{_}..}]&, 37 bytes!

Jelly, 7 bytes
Œ!QIẠ€S

Try it online!
Takes input as e.g. [1,1,1,1,2,2,2] for [4,3]. The [8,3,2] testcase takes too long to run on TIO.
How it Works
Œ!QIẠ€S - main link, input as a list
Œ!      - all permutations
  Q     - remove duplicates
   I    - take increments (returns a 0 for two adjacent identical numbers)
    Ạ€  - apply “all” atom to each: 0 for containing 0 and 1 otherwise
      S - sum

You abused grace period...;)

Does Œ!QIẠ€S work? Try it online!

@nmjcman101 That appears to work. Nice find! I preferred the P over the any and all atom for its simplicity.

@fireflame241 Technically that's not the any-and-all atom, it's the all atom.

BTW P€ instead of Ạ€ would still work.

@EriktheOutgolfer No. Since they are summed, using P would count [3,1,2] negative 2 times.

@fireflame241 Oh right I was confusing with my 05AB1E answer.

05AB1E, 7 bytes
œÙ€¥PĀO

Try it online!
-1 thanks to nmjcman101 on another answer.

Mathematica, 50 bytes
Expand[1##&@@(LaguerreL[#,-1,x](-1)^#)]/._^i_:>i!&

Try it in Mathics, or at the Wolfram sandbox!
Takes input like in the test cases — e.g. {4,3} means "4 red stripes, 3 yellow stripes".
This is a naïve implementation of a formula I found here. "Naïve" means "I have no idea how the maths works so please don't ask me for an explanation…"

Can we have an explanation of the maths given in this answer?

@TheLethalCoder Seconded, can someone please explain the maths to me?

Python 3.5, 65 bytes
f=lambda s,p=0:sum(f(s.replace(c,'',1),c)for c in{*s}-{p})or''==s

Try it online!

Ruby 2.4, 47 bytes
Input is a list of characters: For the test case [4,3], input can be %w[a a a a b b b], "1111222".chars, or some other array formatting method that's valid in Ruby.
->x{x.permutation.uniq.count{|a|a*''!~/(.)\1/}}

Requires 2.4 for Enumerator#uniq (earlier versions only had it available on the Array class). As such, the TIO link adds 5 bytes to convert the permutation enumerator to an array first via to_a, since it does not have the above function.
Try it online!

R, 72 bytes
pryr::f(sum(sapply(unique(combinat::permn(x)),pryr::f(!sum(!diff(x))))))

Creates the function
function (x)
{
    sum(sapply(unique(combinat::permn(x)), pryr::f(!sum(!diff(x)))))
}

Takes input in the form [1,1,1,1,2,2,2] as per Erik the Outgolfer's comment. Uses combinat's permn function to create a list of all permutations, and then unique to get all distinct entries. sapply then applies the following function on all entries:
pryr::f(!sum(!diff(x)))

Which evaluates to
function (x)
!sum(!diff(x))

Note that this x is not the same as the x in the big function's input. Using another character in this function would fool pryr::f into believing the big function needs another argument.
Anyways, when given a permutation, this function takes the difference between the vector: 2 1 3 4 2 1 -> -1  2  1 -2 -1. ! converts nonzero's into FALSE and zeros into TRUE, so the vector becomes FALSE FALSE FALSE FALSE FALSE. Summing that to check if there are any TRUEs (TRUE would imply diff=0 --> two the same consecutive numbers). We can again invert this with ! to get a boolean on whether or not there are consecutive values in the permutation.
Summing over these booleans gives us the total number of permutations where this is not the case.
Doesn't work for the [8,3,2] testcase because it requires a vector of 46GB to store those permutations.

Jelly, 11 bytes
Œ!Q⁻2\Ạ$ÐfL

Try it online!

Python 2, 140 89 bytes
Input format is 'aaaabbb' for test case [4,3].
lambda s:len({p for p in permutations(s)if all(map(cmp,p,p[1:]))})
from itertools import*

Try it online!

Ruby, 84 76 bytes
f=->a,x=p{i=s=0;a.map{a[i-=1]-=1;a[i]<0||i!=x&&s+=f[a,i];a[i]+=1}.max>0?s:1}

A recursive lambda function. Looks at each possible color and dose a recursive tree search, counting the number of times it uses all stripes.
Explanation (for old version):
f=->
  a, # a is the input array in [3,3,4] form
  x = -1 # x is the last color placed (-1 when run normaly, used in recursive calls)
{
  j = i = s = 0;
  # i is the index
  # s is the sum of valid final patterns (the answer)
  # j is used to count the total stripes

  a.map{|e| # Iterate over array of colors

    a[i] -= 1; # remove a stripe of current color (the array will be used in recursive call)

    s += f[a,i] if i!=x && e>0;
      # add to sum recursively if:
        # we are not using the same color as the last color AND
        # we have stripes of the current color left to paint

    a[i] += 1; # replace the stripe we removed above

    j += a[i]; # add stripes to j

    i+=1 # increment the index

  }; # End loop

  j == 0 ? 1 : s
  # if we had stripes, give the recursive sum, otherwise return 1
}

x=p as the initial condition? p acts as an alias of nil in this case and should satisfy the check it's being used for.

Husk, 8 bytes
#ȯ¬ṁtguP

Try it online!
Takes input in the format "aaabb" for [3,2].
Times out on the longest test case.
Explanation
Nothing fancy here, just counting the unique permutations where all groups of adjacent elements have length 1.
#ȯ¬ṁtguP
       P  Permutations.
      u   Remove duplicates.
#ȯ        Count how many satisfy the following condition:
     g    group adjacent elements,
   ṁt     concatenate tails of groups
  ¬       and negate.

MATL, 11 8 bytes
Y@Xu!dAs

Input format is [1 1 1 1 2 2 2] for [4 3], etc.
Runs out of memory for the last test case.
Try it online!
Explanation
Y@    % Implicit input. Matrix of all permutations. Each row is a permutation
Xu    % Unique rows
!     % Transpose
d     % Consecutive differences along each column
A     % All: true for columns such that all its entries are nonzero
s     % Sum. Implicitly display


text:
Is it a Harshad Number?
A Harshad number is a number that is divisible by the sum of its digits.  This is obviously dependent on what base the integer is written in.  Base 10 Harshad numbers are sequence A005349 in the OEIS.
Your Task:
Write a program or function that determines whether a given integer is a Harshad number in a given base.
Input:
A positive integer <10^9, and a base between 2 and 36, OR, a positive integer in its base, using lowercase letters for the numbers from 11-36 and a base between 2 and 36.  You only have to handle one of these options.
Output:
A truthy/falsy value indicating whether the first input is a Harshad number in the base of the second input.
Examples:
27,10 ----------> truthy
8,5 ------------> truthy
9,5 ------------> falsy
1a,12 OR 22,12 -> truthy

Scoring:
This is code-golf, lowest score in bytes wins.

closely related

Jelly, 4 bytes
bSḍḷ

Try it online!
How it works
bSḍḷ  Main link. Arguments: n (integer), k (base)

b     Convert n to base k.
 S    Take the sum.
   ḷ  Left; yield n.
  ḍ   Test for divisibility.

OK, definition of FGITW right here.  Impressive though.  How do you do these things?

It's fairly easy with a base conversion built-in.

I'm just impressed by the built-in to take the sum of the digits.  Didn't even know that was a thing.

There's no built-in to take the sum of the digits. b converts n into the array of its base-k digits, then S takes its sum.

Oh, I see.  I thought b just converted n into an integer in base k.

Python 2, 46 bytes
lambda n,b:n%sum(n/b**i%b for i in range(n))<1

Try it online!

Python 3, 73 bytes
def f(n,b):
 if b<2:return 1
 s=0;c=n
 while n:s+=n%b;n//=b
 return c%s<1

Try it online!
1 is truthy, you know.

-3 bytes in Python 2.

@notjagan I don't use Python 2

-7 bytes in Python 2 (works in Python 3 if you redefine ∈put∈putinput to use Python 2's semantics, which is allowed, and change / to // for a 1-byte cost), using a full program with exit code returns

@musicman523.  In a different version, with 7 bytes shaved off, I would just post that myself.

@Gryphon I didn't come up with the actual code, though; I'm working on my own answer now.

Good luck beating Dennis!

@LeakyNun, base 1 is no longer required.  Sorry about that.

Python 2, 54 47 bytes
n,k=input();m=n;s=0
exec's-=m%k;m/=k;'*n
1>>n%s

Time and memory complexity are O(n), so don't try 109 on TIO.
Output is via exit code, so 0 is truthy, 1 is falsy. If this output method winds up being allowed, a further byte can be saved by turning the program into a function.
Thanks to @musicman523 for suggesting exit codes!
Try it online!

Can you change the language to "Python 2 interpreter" and use exit(n%s) where 0 is truthy and anything else is falsy?

Found something even shorter, thanks to your suggestion. :)

Nice! I thought maybe you could incur a ZeroDivisionError, but your way is shorter I believe

Pyth, 12 7 bytes
!%hQsjF

Try it online!
Byte count is now lower since unary is no longer required.
Explanation
!%hQsjF
     jF    Fold the input over base conversion (converts given number to given base)
    s      Sum the values
  %hQ       Take the first input modulo that sum
!          Logical not, turning 0s from the modulus into True and all else into False

Dyalog APL, 20 bytes
{⍺=1:0⋄⍵|⍨+/⍺⊥⍣¯1⊢⍵}

Try it online! [15 first numbers in 15 first bases]
Takes the number as a right argument and the base as a left argument, 0 is truthy.
How?
⍺⊥⍣¯1⊢⍵ - ⍵ in base ⍺ as a list of digits
⍵|⍨ - ⍵ modulo ...
+/ - the sum

Husk, 5 bytes
¦ΣB²¹

Try it online!

Javascript (ES6), 68 67 bytes
n=>k=>!(n%eval([...n.toString(k)].map(_=>parseInt(_,k)).join('+')))

Note that since we are required only to handle either base-k or base-10 numbers for n, I assume n is a base-10 integer always.
-1 byte, thanks to TheLethalCoder!
How it works:
!                                    # Convert to true if 0 else false
 (n%                                 # Compute n modulo
    eval(                            # evaluate string
         [...n.toString(k)]          # convert to array of base-k divisors
         .map(_=>parseInt(_,k))      # map lowercase characters to ints
         .join('+')                  # join array as string of characters
    )                                # get the raw remainder, and let ! do its work
 )

Try it online!

Welcome to the site! :)

Take input in currying syntax to save a byte i.e. n=>k=>..., would be called like (345)(10)

Java (OpenJDK 8), 54 bytes
n->b->{int s=0,c=n;for(;c>0;c/=b)s+=c%b;return n%s<1;}

Try it online!

Shown as curried, TIO as non-curried.

R, 64 60 bytes
(requires the pryr package)
pryr::f({d=pryr::f('if'(n<b,n,n%%b+d(b,n%/%b)));!n%%d(b,n)})

This is an anonymous function that takes two arguments, b and n that evaluates to (which is on TIO):
function(b,n){
   d=function(b,n)
     if(n<b) n else n%%b + d(b,n%/%b)
   !n%%d(b,n)
}

where d computes the digit sum for the required base.
Dropped 4 bytes once the base was guaranteed to be greater than 1.
Try it online!

Japt, 9 bytes
vUsV ¬xnV

Takes input as two integers.
Try it online!

K (ngn/k), 12 bytes
{~(+/y\x)!x}

Try it online!
A function taking an integer (x) and the base to use (y).

y\x convert x to a base-y representation
+/ take the sum of the digits
~(...)!x check if the sum of the digits mod the input integer is non-zero

Javascript ES6, 62 bytes
n=>b=>!(n%[...n.toString(b)].reduce((x,y)=>x+parseInt(x,b),0))

C (gcc), 37 bytes
f(n,b,i,s){n?f(n/b,b,i,s+n%b):i%s<1;}

Try it online!
Returns zero for true, non-zero for false.
I want to know, why not just i%s does work, but i%s<1 does (isn't that very strange?).

Pari/GP, 25 bytes
(n,b)->n%sumdigits(n,b)<1

Try it online!

Perl 6, 40 bytes
{$^b>1??$^a%%[+] $a.polymod($b xx*)!!?1}

Test it
Expanded:
{  # bare block lambda with placeholder parameters ｢$a｣ and ｢$b｣

    $^b > 1          # declare ｢$b｣ and compare against 1

  ??                 # if ｢$b > 1｣ then:

      $^a            # declare ｢$a｣
    %%               # is it divisible by
      [+]            # reduce the following with &infix:<+> (sum)
        $a.polymod(
          $b xx *    # infinite list of ｢$b｣s
        )

  !!                 # if ｢$b <= 1｣ then:

    ? 1              # Boolify 1 (shorter than True)
}

Mathematica, 30 bytes
#2<2||Tr@IntegerDigits@##∣#&

Pure function taking two arguments, the integer and the base (in that order), and returning True or False. Careful: the first two |s are just the normal ASCII character, while the last ∣ is U+2223.
#2<2 deals with the special case of base 1. Otherwise, Tr@IntegerDigits@## produces the sum of the digits of the first argument when written in the base of the second argument, and ...∣# tests whether that sum divides the first argument.

Batch, 119 bytes
@if %2==1 echo 1&exit/b
@set/at=%1,s=0
:l
@if %t% gtr 0 set/as+=t%%%2,t/=%2&goto l
@set/at=%1%%s
@if %t%==0 echo 1

Outputs 1 for Harshad numbers.

Python 3, 45 bytes
lambda n,b:int(n,b)%sum(int(i,b)for i in n)<1

Try it online!
Based on the updated formats for input.

C (gcc), 57 bytes
f(n,b,t,s){while(b>1&&t){s+=t%b;t/=b;}return b<2||n%s<1;}

Try it online!

Is passing extra parameters allowed? Or is it the only way here..

Japt -!, 5 bytes
%ìV x

Try it

C (gcc), 49 43 bytes
a,b;f(x,n){for(a=x,b=0;b+=x%n,x/=n;);a%=b;}

Try it online!
Returns zero for true, non-zero for false.
It is very simple. It just accumulates all the digits of x in b and returns x % b.
Ungolfed version:
// local variables
int a, b;
int f(int x, int n)
{
    // Accumulate all digits in b
    // Note that the for loop only checks x /= n
    for (a = x, b = 0; b += x % n, x /= n;)
        ;
    // Then return a % b.
    return a % b;
}

Thanks to dingledooper for the -6 bytes!

You may use the return hack to achieve 43 bytes.

Thanks! [undefined behavior ｉｎｔｅｎｓｉｆｉｅｓ]

x86 Machine Code, 19 bytes
50 31 C9 99 F7 F6 01 D1 85 C0 75 F7 58 99 F7 F1 85 D2 C3

The above bytes define a function that accepts the value in the EAX register and the base in the ESI register, and sets the zero flag (ZF) based on whether the value is a Harshad number (ZF will be clear if the value is a Harshad number).
Note that this is a custom calling convention, defined expressly for the purposes of this challenge. Assembly/machine language programmers are allowed to do that. However, note further that the choice of the ESI register for the second parameter (base) is completely arbitrary. This can be changed to any other unused general-purpose integer register (i.e., EBX, EDI, or EBP) without affecting either correctness or code size.
Try it online!
In ungolfed assembly language mnemonics:
; bool IsHarshadNumber(unsigned value, unsigned base)
;
; Inputs:
;    EAX = input value
;    ESI = base
; Outputs:
;    ZF = 0 if Harshad number; otherwise, ZF = 1
; Clobbers:
;    EAX, EDX, ECX
;
        IsHarshadNumber:
50         push   eax             ; preserve input value
31 C9      xor    ecx, ecx        ; zero-out accumulator

        Accumulate:               ; <----------------------------------------------------\
99         cdq                    ; zero-out EDX (based on EAX) to prepare for division  |
F7 F6      div    esi             ; divide by base (EAX = quotient; EDX = remainder)     |
01 D1      add    ecx, edx        ; accumulate remainder                                 |
85 C0      test   eax, eax        ; is quotient 0?                                       |
75 F7      jnz    Accumulate      ; keep looping until it is ----------------------------/

58         pop    eax             ; restore input value
99         cdq                    ; zero-out EDX (based on EAX) to prepare for division
F7 F1      div    ecx             ; divide by accumulator
85 D2      test   edx, edx        ; set ZF based on remainder
C3         ret
```

Ruby, 43 bytes
->n,b,s=0,i=n{(s+=n%b;n/=b)while n>0;i%s<1}

Try it online!

Ruby, 43 bytes
f=->n,b,s=0,i=n{n>0?f[n/b,b,s+n%b,i]:i%s<1}

Try it online!

JavaScript (Node.js), 41 bytes
f=(n,b,s=0,i=n)=>n?f(n/b|0,b,s+n%b,i):i%s

Try it online!
Returns zero for true, non-zero for false.

source: Stack Exchange

license: 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/

sort: votes


text:
Multiply a string by a number!
There was a challenge up a while ago about multiplying strings.  It showed us how we can multiply not only numbers, but also strings.  However, we still can't multiply a number by a string properly.  There has been one attempt to do so but this is obviously wrong.  We need to fix that!
Your Task:
Write a function or program that multiplies two inputs, a string and an integer.  To (properly) multiply an string by an integer, you split the string into characters, repeat each character a number of times equal to the integer, and then stick the characters back together. If the integer is negative, we use its absolute value in the first step, and then reverse the string. If the input is 0, output nothing (anything multiplied by 0 equals nothing).
Input:
A string that consists solely of printable ASCII characters and newlines, and an integer (possible negative).
Output:
The string multiplied by the integer.
Examples:
Hello World!, 3            --> HHHeeellllllooo   WWWooorrrlllddd!!!
foo, 12                    --> ffffffffffffoooooooooooooooooooooooo
String, -3                 --> gggnnniiirrrtttSSS
This is a fun challenge, 0 -->
Hello
World!, 2                  --> HHeelllloo

                               WWoorrlldd!!

Scoring:
This is code-golf, lowest byte count wins!

Can we assume the string is printable ASCII-only, plus newlines?

Can we output a list of strings?

Partial solution in Retina. Only works for positive values of the integer. I probably won't make time to finish it if someone wants to. https://tio.run/##K0otycxL/P8/Tk@bS0WLqzhBw97G9tA2PS1NLk6u6oQ4Qy6uWohgnCFQkFNDDyihYqhiyBWTEHdoWw0n1///RlweqTk5@Vzh@UU5KYoA

@mbomb007, yes, sorry for taking so long about that.

@totallyhuman, no you may not.

@Gryphon You said that you cannot output an array of characters. But what if the language can do only that? C is an example, where there is no native string class. You have to use char[], or char *. Which are essentially arrays of characters. But one is a pointer to that array.

Jelly, 6 5 4 bytes
²Ɠxm

Try it online!
How it works
²Ɠxm  Main link. Argument: n (integer)

²     Yield n².
 Ɠ    Read and eval one line of input. This yields a string s.
  x   Repeat the characters of s in-place, each one n² times.
   m  Takes each |n|-th character of the result, starting with the first if n > 0,
      the last if n < 0.

OK, now I'm really impressed.  I'd love an explanation of this particular wonder in miniature.

Sure. As soon as I made a test suite and am done golfing.

OK, if you can make this any smaller, I'm going to give up trying to make a question that will take you >10 bytes.

Woah. Never seen an input nilad being used before!

@Zacharý Rarely useful, but dyadic chain rules weren't doing what I wanted.

@Gryphon Added an explanation.

OK, that's it.  I'm learning Jelly.  I want to be able to do magic too.

Wait ... how does x not think m is an argument?

@Zacharý In monadic chains, dyads don't bind to each other. That's why I'm using a nilad.

So ... it sort of becomes post-fix because it has to?

@Zacharý That's how all chains work: process as many links as possible, skip them, start over.

gives up I guess I'll have to learn Jelly.

We all know how a discussion about Jelly chains ends up being a mess...

JavaScript (ES6), 63 bytes
Takes input in currying syntax (s)(n).
s=>n=>[...s].reduce((s,c)=>n<0?c.repeat(-n)+s:s+c.repeat(n),'')

Test cases

let f =

s=>n=>[...s].reduce((s,c)=>n<0?c.repeat(-n)+s:s+c.repeat(n),'')

console.log(f(`Hello World!`)(3))
console.log(f(`foo`)(12))
console.log(f(`String`)(-3))
console.log(f(`This is a fun challenge`)(0))
console.log(f(`Hello
World!`)(2))

Python 3, 44 bytes
f=lambda s,n:s and s[0]*n+f(s[1:],n)+s[0]*-n

Try it online!

The base case seems to ignore the last character.

Not quite sure why I did that... Thanks!

41 bytes. but idk if a function call as f(n,*s) is considered valid

Python 2, 59 57 50 46 bytes
-2 bytes thanks to Anders Kaseorg. -4 bytes thanks to Dennis.
lambda s,n:''.join(i*n**2for i in s)[::n or 1]

Try it online!

05AB1E, 10 bytes
S²Ä×J²0‹iR

Try it online!
S          # Split the string into characters
 ²Ä×       # Repeat each character abs(integer) times
    J      # Join into a string
     ²0‹i  # If the integer is less than 0...
         R #   Reverse the string

TFW you spend 30 minutes trying to come up with something to prove to @Riley that ²0‹i isn't the best route and come up with literally 0 alternatives.

@MagicOctopusUrn I've used something like ²0‹i before and I always think there has to be something better.

I think I've tried to find an alternative around 10 times now... wasting a cumulative 3 hours of my life ._. Ä.D)øJ¹0‹iR is the best I can do without copying you, I think yours is optimized.

If you care, Emigna used è here, though I can't find a way to apply it in this scenario. Would save a maximum of 1 byte, if that.

SÂÎ›@²Ä×J, using Î to push 0 and input works if you change the order. Saves 1 byte! (Also replaced the if, so it doesn't need to be closed)

@kalsowerus That's a completely different approach than mine. Feel free to post it yourself.

R, 83 78 76 74 bytes
function(s,i)cat('if'(i<0,rev,I)(rep(el(strsplit(s,'')),e=abs(i))),sep='')

Anonymous function.
Frederic saved 3 bytes, Giuseppe saved 2 4, pajonk saved 2.
Explanation:
     el(strsplit(s,''))                      # split string into list characters
 rep(                  ,e=abs(i)))           # repeat each character abs(i) times

    'if'(i<0,rev, ){...}                     # if i>0, reverse character list
                 I                           # otherwise leave it alone: I is the identity function
cat(                    ,sep='')             # print the result

Tests:
> f('Hello World!', 3 )
HHHeeellllllooo   WWWooorrrlllddd!!!
> f('foo', 12)
ffffffffffffoooooooooooooooooooooooo
> f('String', -3)
gggnnniiirrrtttSSS
> f('This is a fun challenge', 0)
> f('Hello
+ World!', 2)
HHeelllloo

WWoorrlldd!!

Well done ! You could save a few bytes by writing rep(foo,,,3) or rep(foo,e=3) (same lenght) ;-)

@Frédéric you beat me to it, I was going to say the same thing!

-2 bytes

actually, with Frederic's improvement, that gets you down to 78, which isn't too bad.

Thanks! @Giuseppe, can you help me understand what your if statement is doing?

yeah, no problem! Basically, I wanted to get rid of the braces, so I needed to get rid of a=. Hence, I used the value of a as an argument to the reverse function if i<0, by having the conditional return the function (which is why I needed the backquotes). But I needed to also apply the identity function for the i>=0 case, so I used ( which is close enough. ( is in fact a function. R is weird.

btw, the R docs for Paren say that ( is semantically equivalent to the identity function(x)x

76 bytes

74 bytes?

@pajonk is I generally a synonym for (, or the identity function? If so that's really interesting and I'll update this

It essentially is an identity function of you don't care about special classes https://stat.ethz.ch/R-manual/R-devel/library/base/html/AsIs.html

J, 19 15 13 bytes
(#~|)A.~0-@>]

Try it online!
Explanation
        0-@>]      NB. first or last index depending on sign of right arg
     A.~           NB. get first or last Anagram of left arg
(#~|)              NB. copy left arg, absolute-value-of-right-arg times

(#~|)A.~0-@>] for 13 bytes

Very nice @miles !

No problem. You also don't need to count the parentheses used to invoke the verb.

Also 13 bytes: #~ ::(|.@#~|)

@FrownyFrog Nice!

V, 29, 23, 18, 17 bytes
æ_ñÀuñÓ./&ò
ÀäëÍî

Try it online!
Hexdump:
00000000: e65f f1c0 75f1 d32e 2f26 f20a c0e4 ebcd  ._..u.../&......
00000010: ee                                       .

Thanks to @nmjcman101 for saving 6 bytes, which encouraged me to save another 5!
The original revision was pretty terrible, but now I'm really proud of this answer because it handles negative numbers surprisingly well. (V has next to no numerical support and no support for negative numbers)
Explanation:
æ_          " Reverse the input
  ñ  ñ      " In a macro:
   À        "   Run the arg input. If it's positive it'll give a count. If it's negative
            "   running the '-' will cause V to go up a line which will fail since we're
            "   on the first line, which will break out of this macro
    u       "   (if arg is positive) Undo the last command (un-reverse the line)
      Ó./&ò " Put every character on it's own line

At this point, the buffer looks like this:
H
e
l
l
o

w
o
r
l
d
!
<cursor>

It's important to not the trailing newline, and that the cursor is on it.
À           " Run arg again. If it's negative, we will move up a line, and then give the
            " absolute value of the count. If it's positive (or 0) it'll just give the
            " count directly (staying on the last line)
 ä          " Duplicate... (count times)
  ë         "   This column.
   Íî       " Remove all newlines.

A few bytes for ya Try it online!  I always hate the "Negative numbers mean something else!" edge case too.  This is a case where your 0 special cases in V came in super handy.

Sorry about the negative numbers special.  However, a lot of answers managed to incorporate that into their main answer.  Impressive on this V one though.

@nmjcman101 Oh wow, that's so obvious, I don't know how I didn't think of it. Thank you!

@Gryphon Oh I know. The challenge is fine, I just dislike my own language for being so bad at what it's supposed to be good at. :P

Haskell, 41 36 bytes
f n|n<0=reverse.f(-n)|1<3=(<*[1..n])

Try it online!
Example usage: f (-3) "abc" yields "cccbbbaaa".
Edit: -5 bytes thanks to xnor!

There's (<*[1..n]) for ((<$[1..n])=<<).

@xnor Thanks! That's good to know.

MATL, 9 bytes
y|Y"w0<?P

Inputs are: number, then string.
Strings with newlines are input using char 10 as follows: ['first line' 10 'second line'].
Try it online! Or verify all test cases.
Explanation
Consider inputs -3 and 'String'.
y      % Implicitly take two inputs. Duplicate from below
       % STACK: -3, 'String', -3
|      % Absolute value
       % STACK: -3, 'String', 3
Y"     % Run-length decoding
       % STACK: -3, 'SSStttrrriiinnnggg'
w      % Swap
       % STACK: 'SSStttrrriiinnnggg', -3
0<     % Less than 0?
       % STACK: 'SSStttrrriiinnnggg', 1
?      % If so
  P    %   Flip
       %   STACK: 'gggnnniiirrrtttSSS'
       % End (implicit). Display (implicit)

PHP>=7.1, 65 bytes
for([,$s,$n]=$argv;$i<strlen($s)*abs($n);)echo$s[$i++/$n-($n<0)];

PHP Sandbox Online

In integer context, $n<0 has the same value as $n<0?:0 but it's 3 bytes shorter :-)

05AB1E, 10 bytes
0‹FR}ʒ¹Ä×?

Try it online!
Explanation
0‹F         # input_1 < 0 times do:
   R        # reverse input_2
    }       # end loop
     ʒ      # filter
      ¹Ä×   # repeat current char abs(input_1) times
         ?  # print without newline

Brain-Flak (BrainHack), 154 152 bytes
([(({})(<()>))]<>)<>{({}()<([{}]()<([{}])>)<>({}<>)<>>)<>}{}<>{}<>({}<([][()]){{}({<({}<(({}<>)<>)>())>[()]}<{}{}>)([][()])}{}{}<>>){{}{({}<>)<>}(<>)}{}

Try it online!
Just here to give DJMcMayhem some competition. ;)
Explanation
Here's a modified version of DJMcMayhem's explanation
#Compute the sign and negative absolute value
([(({})<(())>)]<>)<>{({}()<([{}]()<([{}])>)<>({}<>)<>>)<>}{}<>{}<>

#Keep track of the sign
({}<

    #For each char in the input string:
    ([][()])
    {
        {}

        #Push n copies to the alternate stack
        ({<({}<(({}<>)<>)>())>[()]}<{}{}>)

        #Endwhile
        ([][()])
    }{}{}<>

#Push the sign back on
>)

#If so...
{{}

    #Reverse the whole stack
    {({}<>)<>}

    #And toggle over, ending the loop
    (<>)
}

#Pop the counter off
{}

Elm, 69 bytes
f n=if n<0 then List.reverse>>f -n else List.concatMap(List.repeat n)

Defines f to be a function that takes an integer and a list of characters and returns a list of characters. You can try it here. Here is a full test program:
import Html exposing (text)

f : Int -> List Char -> List Char
f n=if n<0 then List.reverse>>f -n else List.concatMap(List.repeat n)

main =
  text (String.fromList (f -3 ['S','t','r','i','n','g']))

Explanation
This is my first Elm submission, so please let me know any golfing tricks I've missed.
Using currying, we define a function f that takes an integer n and returns a function from a list of chars to a list of chars. There are two cases in the function definition:

If n is negative, call f on its absolute value (f -n); then compose (>>) the resulting function with List.reverse.
Else, create a function that puts n copies of a value in a list (List.repeat n) and map that function over each char in the list, flattening the result into a list of chars (List.concatMap).

Java (OpenJDK 8), 99 98 89 87 85 bytes
s->n->{for(int i=s.length*(n<0?n:-n),r=n<0?0:~i;i++<0;)System.out.print(s[(i+r)/n]);}

Try it online!

-2 bytes thanks to @Xanderhall
-2 bytes thanks to @Nevay

Ideas that don't work (way longer): reverse the string before, use a stream,

Save 2 bytes with s[(n<0?-l-~i:i)/n]

@Xanderhall Thanks! I've been looking for that one for so long my eyes bleed. I knew it was possible, I just messed everything up when implementing it.

as your function is single statement, do you need curly brackets?

@user902383 Yes, it's mandatory. If they were optional, a lot of things would be unreadable. Also, my function is not a "single statement", but a for-loop, which encompass several statements.

You can save 1 byte by incrementing i in the condition s->n->{for(int l=s.length*(n<0?-n:n),i=0;i++<l;)System.out.print(s[(n<0?i-l:i-1)/n]);}. Another byte can be saved by iterating from -l to 0 instead (s->n->{for(int i=s.length*(n<0?n:-n),r=n<0?0:~i;i++<0;)System.out.print(s[(i+r)/n]);}).

@Nevay This is some really nice golfing. Thank you!

Brain-Flak (Haskell), 202 192 bytes
(({})<(([({})]<>)){({}()<([{}])<>({}<>)<>>)<>}{}([{}]<><{}>)([][()]){{}({<({}<(({}<>)<>)>[()])>()}<{}{}>)([][()])}{}{}<>>)([({}<(())>)](<>)){({}())<>}{}{((<{}>))<>{}}{}<>{}{{}{({}<>)<>}(<>)}{}

Try it online!
This is probably the worst possible language to do it in, but it's done. Thanks to @Wheatwizard for providing the Haskell interpreter, which allows mixed input formats. This would be about 150 bytes longer without it.
Explanation:
#Keep track of the first input (n)
(({})<

    #Push abs(n) (thanks WheatWizard!)
    (([({})]<>)){({}()<([{}])<>({}<>)<>>)<>}{}([{}]<><{}>)

    #For each char in the input string:
    ([][()])
    {
        {}

        #Push n copies to the alternate stack
        ({<({}<(({}<>)<>)>[()])>()}<{}{}>)

        #Endwhile
        ([][()])
    }{}{}<>

#Push the original n back on
>)

#Push n >= 0
([({}<(())>)](<>)){({}())<>}{}{((<{}>))<>{}}{}<>{}

#If so...
{{}

    #Reverse the whole stack
    {({}<>)<>}

    #And toggle over, ending the loop
    (<>)
}

#Pop the counter off
{}

You could use my 52 byte abs to save 2 bytes, you could also use the 50 byte -abs I gave you and increment instead of decrementing to save 6 bytes.

Some friendly competition.

Dyalog APL, 15 bytes
{⌽⍣(⍵<0)⊢⍺/⍨|⍵}

String as a left argument, number as a right argument.
Try it online!
How?
⍺/⍨ - repeat the string
|⍵ - abs(number) times
⌽⍣ - reverse if
(⍵<0) - the number is below 0

Umm, it'd be nice if the TIO like worked?

@Gryphon and here goes the byte...

Yep, I'd just realized that and was typing out my comment to tell you.

MATLAB, 37 bytes
@(s,n)flip(repelem(s,abs(n)),(n<0)+1)

This defines and anonymous function with inputs s: string and n: number.
Example runs:
>> @(s,n)flip(repelem(s,abs(n)),(n<0)+1)
ans =
    @(s,n)flip(repelem(s,abs(n)),(n<0)+1)

>> f = ans;

>> f('String', 3)
ans =
SSStttrrriiinnnggg

>> f('String', -3)
ans =
gggnnniiirrrtttSSS

>> f('String', 0)
ans =
   Empty matrix: 1-by-0

Choosing which dimension to flip along was way better than the mess I wrote  +1. and I always forget repelem exists.

@StewieGriffin Well, you could incorporate that in your answer too :-) (+1 already). I think there's no repelem in Octave, for now

C89 bytes
main(int c,char**v){for(;*v[1];v[1]++)for(c=atoi(v[2]+(*v[2]=='-'));c--;)putchar(*v[1]);}

I saw Ben Perlin's version and wondered if you couldn't be shorter still and also have  a full program; surely, atoi() and putchar() aren't that expensive in terms of bytes? Seems I was right!

C (gcc), 108 106 103 101 bytes
-2 bytes thanks to ceilingcat
e,p,j,d;f(s,i)char*s;{p=0,e=strlen(s);for(i*=d=i<0?p=e-1,e=-1:1;p^e;p+=d)for(j=i;j--;)putchar(s[p]);}

Try it online!

@ceilingcat Cheers!

Japt, 12 bytes
®pVaÃ¬r!+sVg

Try it online!
Explanation
Implicit input of string U and integer V.
®pVaÃ

Map (®) each letter of U (implicitly) to itself repeated (p) abs(V) (Va) times.
¬r

Turn the string into an array of chars (¬) and reduce (r) that with...
!+sVg

"!+".slice(sign(V)) - this either reduces with + → a + b, or with !+ → b + a.
Thanks @Arnauld for the backwards-reduce idea!

I feel like £gY*Vg)pVa should lead to a shorter solution but my brain has shut down for the holidays so I can't quite figure it out. You may be able to do something with it, though.

CJam, 9 bytes
q~__*@e*%

Try it online!

Excel VBA, 93 89 88 86 85 Bytes
Anonymous VBE immediate window function that takes input as string from cell [A1] and int from cell [B1] and outputs to the VBE immediate window
l=[Len(A1)]:For i=1To l:For j=1To[Abs(B1)]:?Mid([A1],IIf([B1]>0,i,l+1-i),1);:Next j,i

-4 bytes for abandoning [C1] as intermediate variable
-1 byte for adding a as intermediate variable
-2 bytes for replacing a with l, ([Len(A1)])

05AB1E, 9 bytes
Based off Riley's approach.
SÂÎ›@²Ä×J

Try it online!
Explanation
SÂÎ›@²Ä×J   Arguments: s, n
S           Push s split into individual characters
 Â          Get a (without popping) and push a reversed
  Î›        n lower than 0 (true = 1, false = 0)
    @       Get value at that index in the stack
     ²Ä×J   Repeat each character abs(n) times and join
            Implicit output

Octave, 49 bytes
@(s,n){t=repmat(s,abs(n),1)(:)',flip(t)}{2-(n>0)}

Try it online!
I will provide an explanation tomorrow.

Pyth, 13 11 bytes
*sm*.aQdz._

Try it!
-2 bytes thanks to @jacoblaw
explanation
*sm*.aQdz._
  m     z     # map onto the input string (lambda var: d)
   *.aQd      # repeat the char d as often as the absolute value of the input number
 s            # sum the list of strings into a single string
*        ._Q   # Multiply with the sign of the implicit input value: reverse for negative Q

old approach, 13 bytes
_W<Q0sm*.aQdz

Try it!

you can save two bytes with this reversal logic

Ruby, 59 +1 = 60 bytes
Uses -n flag.
n=eval$_
a=$<.read
a.reverse!if n<0
a.chars{|i|$><<i*n.abs}

Try it online!

eval$_ is shorter than $_.to_i by 1 byte. String#chars can also accept a block the same way String#each_char can. Finally, reverse the input before processing each character so you can print it directly instead (switching your flag to -n). All of this combines to become 55+1=56 bytes.

Charcoal, 16 bytes
Ｆθ¿‹η0Ｆ±Ｉη←ιＦＩηι

Try it online! Link is to verbose version of code. Explanation:
Ｆθ              For each character in the input string
  ¿‹η0          If the input number is less than zero
      Ｆ±Ｉη      Repeat the negation of the input number times
          ←ι    Print the character leftwards (i.e. reversed)
      ＦＩη       Otherwise repeat the input number times
         ι      Print the character

Python 3, 68 bytes
h=lambda s,n:h(s[::-1],-n)if n<0 else s[0]*n+h(s[1:],n)if s else s*n

Try it online!

Hello, and welcome to the site! Unfortunately, this answer is invalid right now, since it doesn't support Negative numbers. The challenge says: If the integer is negative, we use its absolute value in the first step, and then reverse the string.

Thanks for fixing it! BTW, you could take two bytes off by removing the spaces after parenthesis )

Edited, thanks for the contribution

n<0 else => n<0else

WendyScript, 46 bytes
<<f=>(s,x){<<n=""#i:s#j:0->x?x>0n+=i:n=i+n/>n}

f("Hello World", -2) // returns ddllrrooWW  oolllleeHH

Try it online!
Explanation (Ungolfed):
let f => (s, x) {
  let n = ""
  for i : s
    for j : 0->x
      if x > 0 n += i
      else n = i + n
  ret n
}

Forth, 132 bytes.
My first golf, Idk what I'm doing I'm sure it could be improved a lot.
: Z chars + c@ emit ; : X 0 do dup n Z loop ; : Y dup 0 < if negate then dup 0 > if n count 0 do over i 1 + swap X drop loop then ;

or
: Z chars + c@ emit ;
: X 0 do dup n Z loop ;
: Y dup 0 < if negate then dup 0 > if n count 0 do over i 1 + swap X drop loop then ;

The negate and comparisons are just for the 0 and negative cases.
This is assuming we've already been given the string at 'n', I'm unsure if this is allowed.

C, 109 bytes
char *f(int n, char *s){char *o=calloc(n,strlen(s)+1),*t=o;while(*s){for(int i=n;i--;)*t++=*s;s++;}return o;}

Starting with a function declaration that takes an int and a string and produces a string (it seems implied that memory is not preallocated and must be created) it seems that the straight-forward approach is shorter than any attempts at being cleaver that I had tried.
char *f(int n, char *s){
  char *o=calloc(n, strlen(s)+1),
    *t=o;

  while (*s) {
    for(int i=n; i--; )
      *t++=*s;
    s++;
  }

 return o;

}

This does not seem to work for negative n.

Julia, 44 bytes
(s,x)->for i in split(s,"") print(i^abs(x))end

That doesn't quite work. When the integer argument is negative, the string should be reversed.

K/Kona, 19 18 bytes
{,/$[y>0;;|:]y#'x}

Now, in the 0 case, it does output something, but that's the empty string so I'm sure that's all gravy.
I actually missed the negative input part of this initially, which cost me eleven bytes! Definitely not my best work
Usage:
k){,/$[y>0;;|:]y#'x}["Hello World";3]
"HHHeeellllllooo   WWWooorrrlllddd!!!"
k){,/$[y>0;;|:]y#'x}["Hello World!";0]
""
k){,/$[y>0;;|:]y#'x}["String";-3]
"gggnnniiirrrtttSSS"

Can trim a couple bytes by using (y<0)|:/ instead of $[y>0;;|:].

PowerShell, 89 bytes
param($s,$n)-join($s[((0..($L=$s.Length)),(-1..-$L))[$n[0]-eq45]]|%{"$_"*"$n".trim('-')})

Try it online!
Generates a list of characters in the string, either forward or reversed, string-multiplies each, and joins the resulting array. $n[0]-eq45 is the ASCII code of - and .Trim('-') is shorter than [Math]::Abs($n)

Mathematica, 89 bytes
(T=Table;t=""<>T[s[[i]]~T~Abs@#2,{i,Length[s=Characters@#]}];If[#2>0,t,StringReverse@t])&

input

["Hello World!", 3]

QBIC, 32 bytes
g=sgn(c)[_l;||[:*g|?_sA,b*g,1|';

Explanation
            Takes inputs A$ ('Hello'), and c (-3) from the cmd line
g=sgn(c)    Save the sign of c          -1
[_l;||      FOR each char in A$
[:*g|       FOR the number of repetitions wanted    (ie: -3 * -1)
            Note that : reads a number from the cmd line, and c is the first
            available variable to save it in after a and b got used as FOR counters.
            Also note that a negative value times the sign becomes positive.
?_s         PRINT a substring
  A         of A$
 ,b*g       startng at char n, where n is the first FOR loop counter times the sign
                That means that when c is negative, so is this. A negative starting index
                on Substring instructs QBIC to take from the right.
 ,1|        taking 1 char.
';          This bit injects a literal ; in the output QBasic, to suppress newlines om PRINT

Braingolf, 22 bytes
1-v{R.[v.R]v}R[v>R]v&@

Try it online!
Eeh, not bad.
Takes input as an integer and an array of characters.
Alternatively:
Braingolf, 31 bytes
l1->[M]1-v&,{R.[v.R]v}R[v>R]v&@

Try it online!
Takes input as an integer and a string

Brainfuck, 26 bytes
,>>,[<<[->+>.<<]>[-<+>]>,]

Try it online!

vim, 45 bytes
:s/\(.\)/\1<C-v>
/g
adl<esc>gJaP<esc>"add
:%norm @a
:%j!

<esc> is 0x1b, and <C-v> is 0x16.
:s/\(.\)/\1<C-v><nl>/g splits the string into one character per line.
adl<esc>gJaP<esc>"add then constructs a command in buffer a that will copy a line n times, where n is the number that was previously on this line.
%norm @a and :%j! then apply that command to each line in the file and rejoin the lines respectively.
Try it online

C#, 70 Bytes
using System.Linq;(s,n)=>string.Join("",s.Select(c=>new string(c,n)));

The select function is used to create a new string with the original character repeated n-times, results are joined together.

Hello and Welcome to PPCG! Unfortunatley your answer does not work for negatives or zero. You can also shorten your code by using currying i.e. s=>n=>, string.Concat() and you don't need the trailing semi colon.

C++, 152 bytes
#define l(x,n)for(int x=0;x<n;++x)
typedef std::string s;s f(s t,int c){s r;l(i,t.size())l(j,abs(c))r+=t[i];if(c<0)reverse(r.begin(),r.end());return r;}

And here's the full code you can test with.
#include <iostream>

#define l(x,n)for(int x=0;x<n;++x)
typedef std::string s;s f(s t,int c){s r;l(i,t.size())l(j,abs(c))r+=t[i];if(c<0)reverse(r.begin(),r.end());return r;}

int main(int argc, const char * argv[]) {
    std::cout << f("Hello World!", 3) << std::endl;
    std::cout << f("foo", 12) << std::endl;
    std::cout << f("String", -3) << std::endl;
    std::cout << f("This is a fun challenge", 0) << std::endl;
    std::cout << f("Hello\nWorld!", 2) << std::endl;
    return 0;
}

To start you certainly don't need all the whitespace here.

@WheatWizard Thanks! I didn't know the spaces don't count.

I'm not getting the same byte count.  I'm getting 202 bytes.  If I remove all the unnecessary whitespace it goes down to 140, but I don't see where the 134 number is coming from.

@ZackLee Spaces do count. You can just remove a lot of them by writing the whole thing on one line and writing (for example) for( instead of for (

You need to count those typedefs and defines.  And the #include.  And the using nam...you need to count everything that isn't main.

@Ray Thanks! I updated my code. I didn't count "#include " as it is a default library for C++.

C#, 108 bytes
using System.Linq;s=>n=>{var a=s.Select(c=>new string(c,n>0?n:-n));return string.Concat(n<0?a.Reverse():a);}

Full/Formatted Version:
using System;
using System.Linq;

namespace TestBed
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<string, Func<int, string>> f = s => n =>
            {
                var a = s.Select(c => new string(c, n > 0 ? n : -n));

                return string.Concat(n < 0 ? a.Reverse() : a);
            };

            Console.WriteLine(f("Hello World!")(3));
            Console.WriteLine(f("foo")(12));
            Console.WriteLine(f("String")(-3));
            Console.WriteLine(f("This is a fun challenge")(0));
            Console.WriteLine(f(@"Hello
World!")(2));

            Console.ReadLine();
        }
    }
}

Unwanted, Unnecessary, Opportunistic, 7 bytes
IAM*|V^

Clojure, 24 bytes
#(for[c % _(range %2)]c)

Returning a string instead of a sequence of characters pushes this to 35 bytes:
#(apply str(for[c % _(range %2)]c))

[C#], 103 bytes
var r=n<0?-n:n;var a=new int[p.Length*r].Select((_,i)=>p[i/r]);return String.Concat(n<0?a.Reverse():a);

Try It Online!
Tried something a little different from the other C# answers, without using 'new string(str, x)'.

><> (Fish), 61 bytes
:&0)?v>i:0(?^\
-$0&0/\p3a'r'&
 .07~v?:<+1&:/
{:}+1/ >o< ~\.28

Try it
Explanation

Takes the number as the initial stack value, and the string as the STDIN.
Uses source code modification: Inserts a r command at 10,3 if the number is positive. If so invert the number. The & instruction is nicely in the perfect place both from the top and from the right side.
The {:} copies the character -n times.

Vyxal, 7 bytes
ȧ•?0<[Ṙ

Try it Online!
There's gotta be a better way to do this.
 •      # Repeat each char by...
ȧ       # absolute value of input
  ?0<[  # If it's negative
      Ṙ # Reverse

Thunno 2, 7 bytes
AḄ$0<?r

Attempt This Online!
Explanation
AḄ$0<?r  # Implicit input
 Ḅ       # Multiply each character of the second input by...
A        # ...the absolute value of the first input
  $      # Push the first input again
   0<    # And check if it's negative
     ?   # If it is negative:
      r  #  Reverse the string
         # Implicit output

This doesn't work for cases like String, -3, as negative numbers need to reverse the input them multiply

@lyxal thanks, fixed.

Mathematica, 56 bytes
""<>Thread@Table[Reverse[Characters@#2,2+Sign@#],Abs@#]&

Try it at the Wolfram sandbox! (Doesn't work in Mathics…)
Takes the number then the string as input.
The Reverse function can take a second parameter saying what level of the array to reverse at (so Reverse[{{1,2},{3,4}}] returns {{3,4},{1,2}} but Reverse[{{1,2},{3,4}},2] gives {{2,1},{4,3}}, for instance). When the input number is negative, we reverse at level 1, but when it's zero or positive, we reverse at level 2 or 3. Since Characters@#2 is a list with only one level, reversing at deeper levels has no effect.
Once that's done, we repeat the list of characters then transpose the resulting array using Thread so the repeated characters end up next to each other.

tcl, 120
proc M s\ n {if $n<0 {set s [string rev $s];set n [expr -$n]};lmap c [split $s ""] {append x [string repe $c $n]};set x}

demo

Retina, 76 bytes
Os^$`(?<=^-.+¶.*).

^.+
$*
s`(?<=¶.*)

{`^1

}s`(?<=^1.*)	(.)
	$1$1
\`^¶|

Try it online!

Husk, 13 bytes
So?I↔>0o`ȯṁRa

Try it online!
Ungolfed/Explanation
       o`ȯṁ    -- with the input string..
           Ra  -- ..multiply each character by the absolute value |N|
So?            -- depending on N either apply..
   I           -- ..the identity..
     >0        -- ..if N>0 or else..
    ↔          -- ..reverse it

Raku,  50 bytes
{($^a.comb »x»$^b.abs).join.&{$b <0??.flip!!$_}}

Try it online!

JavaScript (Node.js), 61 bytes
n=>g=(h,i=n,[c,...x]=h)=>c?i?i>0?c+g(h,i-1):g(h,i+1)+c:g(x):h

Try it online!
No longer longer than Q256411, but even same length it's only

Japt -P, 10 bytes
ÆVÃÕzUÌÉ©2

Try it
ÆVÃÕzUÌÉ©2     :Implicit input of integer U & string V
Æ              :Map the range [0,U)
 V             :  Return V
  Ã            :End map
   Õ           :Transpose
    z          :Rotate clockwise this many times
     UÌ        :  Sign of difference between U & -1
       É       :  Subtract 1
        ©2     :  Logical AND with 2
               :Implicitly join & output

C (gcc), 80 bytes
i;L;f(s,n)char*s;{L=strlen(s);for(i=0;i*i<L*n*L*n;)putchar(s[i++/n+~-L*(n<0)]);}

Try it online!
-1 byte from ceilingcat

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


text:
Repeated Consecutive Digital Product Sum Convergence
Given a positive integer n (Example: n=1234444999)

Separate into consecutive digit runs:

[1, 2, 3, 4444, 999]

Take the digital product of each run.

[1, 2, 3, 4*4*4*4, 9*9*9] = [1, 2, 3, 256, 729]

Sum it...

991

Repeat until this converges to a single number:

1234444999
991
82
10
1

Return last number.

Test Cases
BASE CASES:
0 = 0
...
9 = 9

OTHER CASES:
1234444999                     = 1
222222222222222                = 8
111222333444555666777888999000 = 9
11122233344455566677788899     = 8
1112223334445                  = 6
14536                          = 1
99                             = 9

Requested Example:
334455553666333
9+16+625+3+216+27
896
8+9+6
23
2+3
**5**

Winning?
It's code-golf, lowest byte-count is the winner.

Annnnnnnnnnnnnnnnnnnd... this is NOT the sandbox. Crap. Well, not much I can do now, sorry all ._.

It would be good to have test cases where digits of the same kind aren't all in a consecutive chunk.

Can we take input as a list of digits? Some languages can't support integers as high as 11122233344455566677788899.

@ETHproductions you may state the maximum integer input allowed by your language and have your answer be valid if you can explain the bounding.

Will the same digit evet appear in 2 different runs, eg: 33445555666333?

@Mr.Xcoder I mean... You're repeating the process until it converges to a single digit. The intermediate steps have many different examples of that.

05AB1E, 7 6 5 bytes
Thanks to Emigna for saving a byte!
vSγPO

Uses the 05AB1E encoding. Try it online!

I just now noticed for the first time that your avatar is a doge meme.

@MagicOctopusUrn and you just made me notice that as well...

You could replace gF with v.

@Emigna Oohh of course! Thank you! :)

Japt, 17 15 13 bytes
e".+"_¬ò¦ x_×

Test it online! Takes input as a string.
Still not satisfied with this answer...
Explanation
e".+"_  ¬ ò¦  x_  ×
e".+"Z{Zq ò!= xZ{Zr*1}}

e".+"                     Repeatedly replace all matches of /.+/ (the entire string)
     Z{               }   Z with this function:
       Zq                   Split Z into chars.
          ò!=               Partition at inequality; that is, split into runs of equal items.
              xZ{    }      Take the sum of: for each item in Z:
                 Zr*1         the item reduced by multiplication (i.e. the product).
                          This procedure is repeated until the same result is yielded twice.
                          Implicit: output result of last expression

You can also just take it as an integer and state the maximum allowable input, sorry, I changed my answer after posting it to my default answer for that question.

@MagicOctopusUrn Oh, hey, thanks. That saves two bytes, anyway...

Also, the x_× combined with I'm unsatisfied made me laugh. Thanks ;).

I thought ß might have been the way to go here. I was wrong! (At least at half 5 in the morn', sat on the bus to  the airport I was!)

"Still not unsatisfied" ... so ... you're satisfied finally?

@Zacharý Haha, I caught that right before you commented. Nope, still unsatisfied :P I'm thinking I should change something in Japt to make the ".+" unnecessary...

Jelly, 9 bytes
DŒgP€SµÐL

Try it online
Here's how it works:
D  - input as a list of digits
Œg - group runs of equal elements
P€ - the product of each element
S  - the sum of the list
µ  - syntax stuff to separate the left from the right
ÐL - repeat until we get a result twice, then return that result.

Why doesn't P automatically vectorize? That seems strange...

No, P automatically vectorizes, so you don't need the €.

No, P doesn't vectorize: https://tio.run/##y0rNyan8/9/l6KT0gOBDWw9P8Pn//78RKgAA

Oh, I see - Œg is inconsistent when there's only a single group. What's the reasoning behind that?

No clue at all!

It looks like it's because Jelly automatically unpacks singleton lists. I don't see why that's very useful, though...

Make sure you look carefully though, as how Jelly displays strings and lists is ... weird.

Very late I know, but P and S do vectorise, but along columns, not rows

Brachylog, 8 bytes
Ḋ|ẹḅ×ᵐ+↰

Try it online!
Explanation
Ḋ          Input = Output = a digit
 |         Or
  ẹ        Split into a list of digits
   ḅ       Group consecutive equal elements together
    ×ᵐ     Map multiply
      +    Sum
       ↰   Recursive call

You'd never expect Brachylog to outgolf Jelly here would you?

@EriktheOutgolfer When Brachylog beats Jelly, my first assumption is that the Jelly answer isn't optimal

Mine too, except I tried to do this in Jelly too. The thing is, well, 05AB1E still beats this. :)

Well. it's one byte, and the Jelly answer is by me, yeah, I'd expect Brachylog to beat Jelly.

Mathematica, 55 42 bytes
#//.i_:>Tr[Times@@@Split@IntegerDigits@i]&

-13 bytes from  @JungHwan Min. Thanx!
in case someone wants to use this as a random-digit-generator,
here is the tally of the first 100.000 numbers

{{1, 17320}, {2, 4873}, {3, 10862}, {4, 11358}, {5, 10853}, {6,
    9688}, {7, 11464}, {8, 10878}, {9, 12704}}
or if you gamble, don't put your money on 2!

Pyth, 11 bytes
us^M_MrjGT8

Try it online. Test suite.

Python 3, 96 bytes
from itertools import*
f=lambda n:n*(n<10)or f(sum(int(k)**len([*g])for k,g in groupby(str(n))))

Try it online!

JavaScript (ES6), 77 73 67 65 bytes
Saved 2 bytes thanks to @CraigAyre
f=s=>s>9?f(''+eval(s.replace(/(.)\1*/g,s=>'+'+[...s].join`*`))):s

How?
The input s is transformed into an arithmetic expression with:
s.replace(/(.)\1*/g, s => '+' + [...s].join`*`)

For instance, 1234444999 becomes +1+2+3+4*4*4*4+9*9*9.
We evaluate this expression and do a recursive call with the result until it's boiled down to a single decimal digit.
Test cases

f=s=>s>9?f(''+eval(s.replace(/(.)\1*/g,s=>'+'+[...s].join`*`))):s

console.log(f("1234444999"                    )) // = 1
console.log(f("222222222222222"               )) // = 8
console.log(f("111222333444555666777888999000")) // = 9
console.log(f("11122233344455566677788899"    )) // = 8
console.log(f("1112223334445"                 )) // = 6
console.log(f("14536"                         )) // = 1
console.log(f("99"                            )) // = 9

Can you save a couple of bytes by comparing against 9?: f=s=>s>9?f(''+eval(s.replace(/(.)\1*/g,s=>'+'+[...s].join\*`))):s`

@CraigAyre Seems like my approach was a bit overcomplicated indeed. Thanks!

Husk, 8 bytes
ωöṁΠgmis

Takes and returns an integer.
Try it online!
Explanation
Having a built-in for base 10 digits would be nice...
ωöṁΠgmis
ω         Iterate until a fixed point is found
 ö        the composition of the following four functions:
       s   convert to string,
     mi    convert each digit to integer,
    g      group equal adjacent integers,
  ṁΠ       take product of each group and sum the results.

...looks like incorporating a built-in for base 10 digits during the intervening 3 years was worth it, then: now 6 bytes.

MATL, 11 bytes
`!UY'^sVtnq

Try it at MATL Online
Explanation
        % Implicitly grab input as a string
`       % Do...while loop
  !U    % Convert the string to an array of numbers (the digits)
  Y'    % Perform run-length encoding
  ^     % Raise the digits to the power corresponding to the number of times they
        % occurred consecutively
  s     % Sum the result
  V     % Convert to a string
  tn    % Duplicate and determine the number of characters in the string
  q     % Subtract one, causes the loop to continue until it's a single digit
        % Implicit end of do...while loop and display

CJam, 22 bytes
r_,{1/e`Wf%::i::#:+s}*

Try it online!

Braingolf, 25 bytes
!L1-Mv[RG(d&*)&+!L1-Mv>]R

Will add a TIO link once I get Dennis to pull the latest version, as using greedy operators inside (...) loops is currently broken on TIO
Explanation
!L1-Mv[RG(d&*)&+!L1-Mv>]R  Implicit input from commandline args
!L1-M                      Push length of input minus 1 to stack2
     v                     Switch to stack2
      [.........!L1-Mv>]   While length of input > 1..
       RG                  Split into digit runs
         (d&*)             Product of digits of each item in stack
              &+           Sum stack
                        R  Return to stack1
                           Implicit output from stack

Haskell, 103 70 69 bytes
import Data.List
until(<10)$sum.map product.group.map(read.pure).show

Try it online!

You can shorten that a lot by using until(<10). Also the map(read.pure) can be moved before show, which saves parentheses.

Yup, it is a lot better!

You can use $ instead of the outer parentheses.

PHP, 113 bytes
for(;9<$a=&$argn;$a=$s){$s=0;preg_match_all('#(.)\1*#',$argn,$t);foreach($t[0]as$v)$s+=$v[0]**strlen($v);}echo$a;

Try it online!

Are you  full-time PHP developer?

@MagicOctopusUrn No I have experience over  few years

K (ngn/k), 17 23 bytes
+6 bytes from handling cases where the same digit is present in multiple chunks
{+/*/'(&~=':x)_x:10\x}/

Try it online!

{...}/ run a converge reduction over the input
x:10\x convert input to a list of digits, updating x
(&~=':x) identify indices where the value differs from the previous element
(...)_x split the list of digits on those indices
*/' take the product of each chunk
+/ add those products together

Fails on inputs too large for 64-bit integers.

Perl 5, 50 bytes
49 bytes of code + -p flag.
s/(.)\1*/"+".$&=~s%.%$&*%gr.1/ge while($_=eval)>9

Try it online!

Japt, 19 bytes
=ò¦ m¬®×Ãx)<A?U:ßUs

Try it online!
Explanation:
=ò¦ m¬®×Ãx)<A?U:ßUs
=                    // Implicit U (input) =
 ò¦                  //   Split the input into an array of consecutive digit runs
    m¬               //   Split each inner array: ["1","22","333"] -> [["1"],["2","2"],["3","3","3"]]
      ®              //   Map; At each item:
       ×             //     Get the product of each run
        Ã            //   }
         x           //   Sum
           <A        // <10
             ?       // If true:
              U      //   return U
               :     // Else:
                ß    //   Run the program again; Pass:
                 Us  //     U, cast to a string

R, 114 104 bytes
n=scan(,'');while(nchar(n)>1){n=el(strsplit(n,''));b=table(n);n=as.character(sum(strtoi(names(b))^b))};n

reads from stdin; returns the answer as a string.
Try it online!

You could use paste instead of as.character. The former coerces its input into character type ;-)

R, 97 96 bytes
a=scan(,"");while(nchar(a)>1){a=paste(sum(strtoi((b<-rle(el(strsplit(a,""))))$v)^strtoi(b$l)))}a

Slightly different approach than the other answer using R.
This answer makes use of the rle function, which compute[s] the lengths and values of runs of equal values in a vector.
-1 bytes thanks to @Giuseppe !

** is equivalent to ^

J-uby, 45 bytes
:!~&(:digits|:slice_when+:!=|:*&(:/&:*)|:sum)

Attempt This Online!
Explanation
:!~ & (:digits | :slice_when + :!= | :* & (:/ & :*) | :sum)

:!~ & (                                                   )  # Apply the following function until F(x) == x
       :digits |                                             #   Get digits
                 :slice_when + :!= |                         #   Group like elements (slice between unequal)
                                     :* & (:/ & :*) |        #   Map with reduce with product
                                                      :sum   #   Sum

Vyxal 3 g, 6 bytes
ᵡλġᵛΠ∑

Try it Online!

Japt -h, 9 bytes
I/O as digit arrays
£=òÎx_×Ãì

Try it
£=òÎx_×Ãì     :Implicit input of digit array
£             :Map
 =            :  Reassign to U
  ò           :  Partition between elements where
   Î          :    The sign of their difference in truthy (not zero)
    x         :  Reduce by addition
     _        :  After passing each through this function
      ×       :    Reduce by multiplication
       Ã      :  End function
        ì     :  Split to digit array
              :  Implicit output of last element

Groovy, 69 68 bytes
f={r->r>9?f((r=~/(.)\1*/)*.tap{}.sum{n->n[1]as int**n[0].size()}):r}

Requires Groovy 3.x.
Explanation
If the input is single digit, returns it, else recursively calls the function on the next pass of the algorithm.
f={r->r>9?f(...):r}     : Recursively call algorithm if input > 9, else return input
r=~/(.)\1*/)            : Regex capture of each run, e.g. [["444", "4"], ["2", "2"]]
*.tap{}                 : Convert Matcher to List<List<Integer>> so we can call sum()
.sum{...}               : Apply the closure to each List element and sum them
n[1]as int**n[0].size() : <digit>^<run length> from e.g. ["444", "4"]

Uiua SBCS, 20 17 bytes
⍥(/+⊜/×+1.-@0°⋕)∞

Try it!


text:
Write a Stepping Quine
Related
Your goal, is to write a set of programs, that progresses from one to the other, one character at a time. For example. Given the starting program abcd and the ending program wxyz, you should have 5 valid programs, with the respective outputs.
abcd -> wbcd
wbcd -> wxcd
wxcd -> wxyd
wxyd -> wxyz
wxyz -> wxyz

As can be seen, the last program should be a quine.
Rules

Your start and end program may be any length, And they may also be different lengths
Your start and end program must contain entirely unique characters at each position, but may share characters overall.
Each program should affect a single character at a time, in any order, characters should only be added or removed from the end of the program.
None of your programs need to follow the valid quine rules, they only need to output the correct string.
Standard Loopholes Apply.

Scoring
Programs are scored by the length of the start program plus the length of the end program in bytes. In the previous example, 4 + 4 = 8, so the score is eight. This is code-golf, so shortest programs wins.
Some Valid Programs
In languages that hopefully don't exist
abcd -> dbcd -> dccd -> dcbd -> dcba
a -> b
a -> b -> bc -> bcd -> bcde
ab -> aa -> ba
[BLANK PROGRAM] -> a
xyz -> xy -> x -> [BLANK PROGRAM]

If the scoring isn't exactly "length of the code" you should use [tag:code-challenge] instead.

I'd disagree, as it's just the length of 2 programs. It's still very much so a golfing challenge.

BLANK PROGRAM is zero bytes right (thus disallowed according to your first rule?)

I knew I was going to condradict myself somewhere, fixed. @StewieGriffin

Python, 0 + 0 = 0: (empty program) it's both the start and end program

I feel like maybe this should have been [tag:code-bowling], since the shorter an answer is, the fewer stages it needs to go through before reaching the end program.

Retina, Score 1

Try it online!

The empty program outputs 1, since the empty input matches the empty string exactly once.
1 outputs 0, since 1 doesn't match the empty input.
0 outputs 0, since 0 doesn't match the empty input. Since it outputs itself, it's a quine (as defined in this challenge).

You'd technically need to use the latest Retina commit, because the version on TIO still prints trailing linefeeds by default.

And I think the empty program is allowed, see the second-to-last example in the challenge.

@MartinEnder The OP was self-contradictory on this when this answer was posted.

@ØrjanJohansen which is why I've informed Stewie that it's now been clarified and the answer can be updated. :)

@MartinEnder Yeah but the examples didn't change, only the part contradicting them.

@ØrjanJohansen Ah, fair enough.

@MartinEnder edited :) Thanks :)

05AB1E, Score 1
=

Try it online!
= prints top of stack (nothing) without newline.
 (empty program) also generates no output.
Boring solution, but it works.

Braingolf, Score 2
/

Try it online!
Niladic / pushes 5, with implicit output, 5 also pushes 5.

Japt, Score 2
T

Output: 0 (Test it)

0

Output: 0 (Test it)

Any uppercase letter after T would also work in the same way.


text:
Help me do my washing
Help! My Completely Automated Lights From Darks Separator V3001.01 broke! :(
Guidelines

Task
Write a program that will take an input of an array (or a list in some languages) of any amount of strings that are either the letter L or the letter  D (representing lights or darks) and output an array that contains two arrays, one with all the L's, and one with all the D's.

Rules

It's code golf so the shortest answer in bytes wins
Input will only ever contain capitals
There must be the same number of L's in the output as there is in the input, same goes for the D's
The input may only have one element (or maybe even zero elements)
If one or both of the output arrays contain no elements, output an empty list (in some languages this may mean you need to output a string)
Always have the first array be the array of L's

Example output:
["L","D","L","D","D"] -> [["L","L"],["D","D","D"]]
["L","L","L"] -> [["L","L","L"],[]]
["D","D"] -> [[],["D","D"]]
[] -> [[],[]]

Can we input/output as a string? For example: "LDLDD" -> "LL DDD" or something  like that?

Or output perhaps as a list of the two strings, e.g. `"LDLDD" -> ["LL", "DDD"]

Would also like an answer, as my answer depends on this

How about mixed output? As in an array containing one string and one array of strings? e.g., ["L","L",["D","D","D"]].

No, the output must be an array/list. @ComradeSparklePony

Is it acceptable to take a string as input e.g. 'LDLDD' instead of ['L', 'D', 'L', 'D', 'D']?

@EriktheOutgolfer No the input must be an array/list. However, I would presume in most languages it would be easy to convert an array of string to a string?

@Amorris Yeah it should probably.

@EriktheOutgolfer After all, a string is an array of characters...

Welp, that's braingolf out then. Can't do nested arrays

@Amorris what about 2 separate Arrays (IE [L, L], [D, D, D]) as opposed to an array of arrays?

@Mayube Sure thats fine, not sure how your gonna get that in one output though...

APL, 8 bytes
'DL'~⍨¨⊂

Explanation:

⊂: enclosed input
~⍨¨: without each
'DL': 'D' and 'L'

Examples:
      ('DL'~⍨¨⊂) 'LDLDD'
┌──┬───┐
│LL│DDD│
└──┴───┘
      ('DL'~⍨¨⊂) 'LLL'
┌───┬┐
│LLL││
└───┴┘
      ('DL'~⍨¨⊂) 'DD'
┌┬──┐
││DD│
└┴──┘
      ('DL'~⍨¨⊂) ''
┌┬┐
│││
└┴┘

Why is it 'DL' but not 'LD'?

@LeakyNun: added explanation. It works by removing the wrong character rather than selecting the right one.

'LD'∩⍨¨⊂ or ⍞∘∩¨'LD' may be easier to explain.

Python 3, 37 bytes
lambda a:[[c]*a.count(c)for c in"LD"]

Try it online!

Haskell, 28 bytes
f l=[filter(==[c])l|c<-"LD"]

Try it online!
If the input can be a list of characters, the [] around c can be removed.

PHP, 46 bytes
Assumed given list is:
$arr = ['L','L','D','D','L','D','D','D','D','L'];
foreach($arr as $b){$a[$b][]=$b;};print_r($a);

As a default I/O rule, you cannot assume input is stored in one variable

@KeyuGan argh! Fair enough

Use can use $argv instead of $arr and expect the script to be run from command line as php -f golf.php L L D D L D D D D L - but then again you have to go around $argv[0] which is the file name

using this way the shortest solutions are for(;$b=$argv[++$i];)$a[$b][]=$b;print_r($a); or <?foreach($_GET as$b)$a[$b][]=$b;print_r($a);

My first golf attempt after years lurking and I'm still a total amateur! Thanks for the feedback (and up-votes) though everyone :)!

Mathematica, 27 bytes
Rest/@Gather[{L,D}~Join~#]&

Pure function taking a list of Ls and Ds (symbols, not characters/strings) as input and returning a list of two lists. For example,
Rest/@Gather[{L,D}~Join~#]& @ {D, L, L, D, L}

returns {{L, L, L}, {D, D}}. Try it online!
Gather by itself is close to what we want, but fails to meet the spec in two ways: it doesn't produce empty lists if the input is missing Ls or Ds, and it doesn't always sort Ls to the left. Replacing the input # with {L,D}~Join~# solves both problems at once: it means there will be at least one L and at least one D, and the Ls will be returned first since an L was encountered first. Rest/@ then removes the initial L and D.
(I tried a solution using Count, but due to currying issues, it didn't seem to be shorter: ±q_:=#~Table~Count[q,#]&/@{L,D} is 31 bytes.)

TIO link (mathics)?

How about Cases@@@{{#,L},{#,D}}&, for 22 bytes?

Great idea, Not a tree! You should post that answer—I'll upvote :)

Done!

Haskell, 32 bytes
import Data.List
partition(>"K")

Just a boring library function.
Try it online!

Try with no imports :P

Japt, 13 12 10 bytes
2Æf¥"LD"gX

Test it (-Q flag for visualisation purposes only)

Explanation
Implicit input of array U.
2Æ

Generate the array [0,1] and pass each element through a function, with X being the current element.
f¥

Filter U by checking for equality...
"LD"gX

...with the character in string LD at index X.

"Hmm, removing the ¥ should work..." [["L","L","D","D"],[]] "Nope, not going there :)" - me 2017

@ETHproductions: Ha-ha! Yeah, I tried so many ways to try to get it to work without the ¥.

Ruby, 26 bytes
->x{x.partition{|e|e==?L}}

Try it online!

Prolog (SWI), 42, 37 bytes
l('L').
w(L,D,W):-partition(l,W,L,D).

Try it online!
Given that W is a list of washing, w/3 will unify L and D into lists of Lights and Darks respectively, by partitioning the washing against a predicate which succeeds if an item is a Light.
[Edit: golfed -5 thanks to Fatalize]

l('L'). is 5 bytes shorter than l(X):-X='L'.

@Fatalize - thanks! Edited in.

Common Lisp, 66 65 bytes
(defun f(x)`(,(remove"D"x :test'equal),(remove"L"x :test'equal)))

Try it online!
If, instead of strings, we use symbols, then it is much shorter:
Common Lisp, 42 41 40 bytes
(defun f(x)(mapcar'remove'(D L)`(,x,x)))

Try it online!
(f '(D D L L D L D)) ; => ((L L L) (D D D D))

PHP7, 52 45 bytes
-7 bytes thanks to @Jörg Hülsermann
foreach($argv as$a)$$a[]=$a;print_r([$L,$D]);

Use with CLI as php -r a.php L L L D D L D
The script goes through the provided arguments and appends them to an array based on its value.

45 bytes with using -r option instead of -f remove<?php and drop the space after the as

Mathematica, 22 18 bytes
4 bytes saved by the genius of CalculatorFeline!
Cases@@@{#|L,#|D}&

Try it online, or at the Wolfram sandbox!
Input is a list of the symbols L and D — not strings, just the letters on their own, like in Greg Martin's answer. The syntax #|L is shorthand for Alternatives[#,L], but the @@@ syntax replaces the head Alternatives with Cases, so this code is equivalent to {Cases[#,L],Cases[#,D]}&.

{#,x} can be #|x for -4 bytes.

@CalculatorFeline, wow, that trick is amazing! Thank you!

@@ and @@@ work with any head, not just List. If | doesn't work, you can still save in some cases with &&, ||, or **.

You can also use . and arithmetic operators.

Also, precedence abuse has more savings for you (with an output format change): #.L|#.D

@CalculatorFeline, I can't get that to work without brackets, and Cases@@@(#.L|#.D)& is no shorter than the current answer. What version of Mathematica are you using?

Oh yeah I forgot about that X(

Racket, 48 bytes
(compose list((curry partition)(λ(x)(eq? x'L))))

Just apply this anonymous function to, e.g., '(L D L D D L)

Pyth, 10 9 bytes
mc@dQ1"LD

Test suite.

Using .g seems to be shorter.

05AB1E, 8 bytes
'LÃ¹'DÃ)

Try it online!

Javascript (ES6), 37 bytes
This is based on a (now deleted) Javascript (ES6) answer.
a=>[(b=c=>a.filter(d=>c==d))`L`,b`D`]

Ungolfed version:
function(array) {
  function filter(character){
    return array.filter(function(d) {
      return character == d;
    });
  }
  return [filter("L"), filter("D")];
}

Example code snippet:

f=

a=>[(b=c=>a.filter(d=>c==d))`L`,b`D`]

console.log(f(["L", "D", "L", "D", "D"]))

Java 8, 110 106 bytes
a->{String[]r={"",""};for(char c:a)r[c/69]+=c;return new char[][]{r[1].toCharArray(),r[0].toCharArray()};}

-4 bytes thanks to @Nevay.
Explanation:
Try it here.
a->{                      // Method with char-array parameter and 2D char-array return-type
  String[]r={"",""};      //  Two Strings in an array
  for(char c:a)           //  Loop over the characters of the input
    r[c/69]+=c;           //   Append either of the two String with the character
                          //   c/69 will result in 0 for 'D' and 1 for 'L'
                          //  End of loop (implicit / single-line body)
  return new char[][]{    //  Return a 2D character-array
    r[1].toCharArray(),   //   With the String for L's converted to a char-array
    r[0].toCharArray()};  //   and String D's converted to a char-array
}                         // End of method

You can store l and d in an array to remove the if-else statement. a->{String[]r={"",""};for(char c:a)r[c/69]+=c;return new char[][]{r[1].toCharArray(),r[0].toCharArray()};} (-4 bytes)

C#, 61 bytes
using System.Linq;a=>new[]{a.Where(c=>c<69),a.Where(c=>c>68)}

Full/Formatted Version:
using System;
using System.Linq;

class P
{
    static void Main()
    {
        Func<char[], System.Collections.Generic.IEnumerable<char>[]> f =
            a => new[] { a.Where(c => c < 69), a.Where(c => c > 68) };

        Console.WriteLine(string.Join(", ", f(new[]{ 'L', 'D', 'L', 'D', 'D' }).SelectMany(a => a.Select(c => c))));

        Console.ReadLine();
    }
}

F#, 37 bytes
let f s=List.partition(fun a->a="L")s

Try it online!
Takes input as a list of strings, and returns two lists, the first with elements where fun a -> a="L" is true and the other with elements that result in false.

Jelly, 10 bytes
ẎfÐ€⁾LDW€€

Try it online!
In Jelly a string is a list of 1-char Python strings, e.g. ['a', 'b', 'c']. That's why you get output such as [[['L'], ['L']], [['D'], ['D'], ['D']]], since 1-char Jelly strings behave the same.
Doesn't work as a full program, hence the ÇŒṘ at the bottom.

@Leo Hmm, you may be right...fixed.

It seems Jelly input is different from Jelly output?  Does the interpreter do string->char[] automagically?

@nmjcman101 On strings it's different, since input is in Python format and output is in Jelly format. That's why I need the W€€ part.

Perse, 21 bytes
part(i,fn(x){x=="L"})

I may or may not have implemented the list partition function specifically for this challenge. Takes the input as an array of strings.

Husk, 7 bytes
Mof-"DL

Try it online!
Explanation
Mof-"DL
M   "DL    For each character in ['D','L']:
 of-         keep only those strings that are not empty if that character is removed

Julia, 26 bytes
g(s)=s[s.=="L"],s[s.=="D"]

Octave, 21 bytes
@(A){A(a=A>72),A(~a)}

Input is an array of characters, output is a cell array. Recycled from my answer here.
Sample execution on ideone.

R, 35 bytes
x=scan(,'');list(x[i<-x>'D'],x[!i])

Try it online!
Reads from stdin.

Ruby, 20 bytes
->l{[l-[?D],l-[?L]]}

Try it online!

Thunno 2, 8 bytes
`LDdẊcx×

Try it online!
Explanation
`LDdẊcx×  # Implicit input                   ->  ["L","D","L","D","D"]
`LD       # Push the string "LD"             ->  ["L","D","L","D","D"]  "LD"
   d      # Split it into characters         ->  ["L","D","L","D","D"]  ["L","D"]
    Ẋ     # Store it in x without popping    ->  ["L","D","L","D","D"]  ["L","D"]
     c    # Count occurrences in the input   ->  [2,3]
      x×  # Multiply by x elementwise        ->  [["L","L"],["D","D","D"]]
          # Implicit output

Haskell (Lambdabot), 41 bytes
reverse.map tail.group.sort.("LD"++).join

Try it online!

PowerShell, 27 bytes
($args-eq'L'),($args-eq'D')

Try it online!

Edit: previously $args.where({$_-eq'L'},'sp') for 28 bytes. Could be $args.where({+"0x$_"},'sp') for 27 if not for the rule that L's must come first.

Retina, 21 11 bytes
-10 bytes thanks to CalculatorFeline
O^`.
LD
L D

Try it online!

The 21 byte version can be O^\. LD L D`.

CJam, 14 bytes
"LD"qf{1$e=*}`

Input is a list of characters (string), output is a list of lists of characters (list of strings).
Try it online!
Explanation:
"LD"  e# Push the string "LD"                  | "LD"
q     e# Push the input                        | "LD" "LDLLDLDDL"
f{    e# Foreach char in "LD", push input and: | ['L "LDLLDLDDL"
  1$  e#   Copy from 1 back                    | ['L "LDLLDLDDL" 'L
  e=  e#   Count occurences                    | ['L 5
  *   e#   Repeat character                    | ["LLLLL"
}     e# End                                   | ["LLLLL" "DDDD"]
`     e# Stringify:                            | "[\"LLLLL\" \"DDDD\"]"
e# Implicit output: ["LLLLL" "DDDD"]

Perl 5, 70 bytes
$"='","';@L=(L)x y/L//;@D=(D)x y/D//;$_="[[\"@L\"],[\"@D\"]]";s/""//g

Try it online!

Javascript, 38 bytes
q=>['L','D'].map(x=>q.filter(y=>x==y))

Hello and welcome to the site! We do not allow answers that assume a variable as input, we call these snippets.  Instead format your answer as a function (named on unnamed), or a full program with IO.

Thanks @FunkyComputerMan. I edited it, let me know if it is correct.

J, 13 bytes
<@-."1 0&'DL'

Try it online!

Vyxal, 53 bitsv2, 6.625 bytes
‛LDƛ?Oẋf

Try it Online!
Ports Thonnu 2
Explained
‛LDƛ?Oẋf
‛LDƛ      # To each character in the string "LD":
    ?O    #   Count the character in the input
      ẋ   #   And list repeat it that many times
       f  #   flatten that

Created with the help of Luminespire.


text:
Quining a Pristine World
This challenge is based off of Helka Homba's question Programming a Pristine World. From that question, the definition of a pristine program is:

Let's define a pristine program as a program that does not have any errors itself but will error if you modify it by removing any contiguous substring of N characters, where 1 <= N < program length.
For example, the three character Python 2 program
`8`

is a pristine program (thanks, Sp) because all the programs resulting from removing substrings of length 1 cause errors (syntax errors in fact, but any type of error will do):
8`
``
`8

and also all the programs resulting from removing substrings of length 2 cause errors:
`
`

If, for example, `8 had been a non-erroring program then `8` would not be pristine because all the results of substring removal must error.
Notes:

Compiler warnings do not count as errors.
The erroring subprograms can take input or give output or do anything else as long as they error no matter what eventually.

Your task is to create a program of non-zero length that prints its own source code exactly, follows the rules for a proper quine, and is pristine.
Shortest answer in bytes for each language wins.

I'm assuming languages that don't error can't compete?

@ATaco Unfortunately yes. Other languages, such as lisp, have the syntax structured in such a way that making a useful pristine program is impossible.

RIP Actually/Seriously

'Shortest answer in bytes for each language wins.' I am not sure about short being the best measure for a pristine program.

@P.Siehr What would you reccomend instead?

Difficult question. I have thought about it for some time after I read your challenge. If you see the measure as something that measures the difficulty or complexity of the answer, than it would grow proportional to length (longest) and not inversely proportional (shortest). Then again, that is contrary to 'shortest quine'.

I'd actually say the longest pristine program is a better accomplishment.

Haskell, 132 bytes
q x=if length x==132then putStr x else fail[];main=q$(++)<*>show$"q x=if length x==132then putStr x else fail[];main=q$(++)<*>show$"

Try it online!
This is an extension of the quine
main=putStr$(++)<*>show$"main=putStr$(++)<*>show$"

which works by concatenating the data string with a quoted version (by using show) of itself and printing the result. However, this is not pristine as any characters in the data string can be removed without failing and also the $(++)<*>show$ or (++)<*> part could be dropped without the program breaking.
To fix this, a custom print function q is defined which checks the length of the given string and calls fail if it's shorter than 132. This catches the removing of any sequence from the data string and also the removals of $(++)<*>show$ or (++)<*>, as in both cases the resulting string passed to q is shorter.
In q the number 132 could be shortened to 1, 13, 32 or 2, but in each case again fail is called.
As far as I can tell, the removal of any other substring causes either an syntax or type error, so the program does not even compile in the first place. (Haskell's strict type system comes in handy here.)
Edit: Thanks to Ørjan Johansen and Shelvacu for pointing out a flaws!

I'm afraid fail[]|length x/=122 can be removed. fail[]:[putStr x|length x==122] might work better.

Argh, no, then |length x==122 could be removed. if length x==122 then putStr x else fail[] perhaps?

@ØrjanJohansen Good catch, I had an if then else before but thought I could shorten it.

putStr x can become p x, which when I tried on my system ran for a very long time before I killed it, I suspect the tail call recursion was optimized, so it's an infinite loop. I don't know enough haskell to give any suggestions on how to fix it.

@Shelvacu Whoops. Renaming p to q should fix that.

@Shelvacu Good catch, it's fixed now as Ørjan Johansen suggested.

<$> within the data segment should presumably be <*> to match the code, otherwise it's not a quine.

@Shelvacu Thanks again, this was a copy-paste error.

Python 3, 113 bytes
for[]in{113:[]}[open(1,"w").write((lambda s:s%s)('for[]in{113:[]}[open(1,"w").write((lambda s:s%%s)(%r))]:a'))]:a

Try it online!
How it works
We can’t easily use multiple statements since the second one could be deleted, so we start with a single-expression quine:
print((lambda s:s%s)('print((lambda s:s%%s)(%r))'))

To protect it against substring deletions, we use open(1,"w").write instead of print.  In Python 3, write returns the number of written characters, which we will verify is 113 to ensure that no part of the string was deleted.  We do this by looking up the return value in the dictionary {113:[]}, and looping over the result with for[]in…:a, which will fail if we didn’t get an empty iterable or if the for statement is deleted.

Could you give an explanation of how your code works?

@Shelvacu Yeah, added.

Standard ML (MLton), 204 182 189 bytes
val()=hd[(fn s=>let val$ =s^"\""^String.toString s^"\"]"val(189,%)=(size$,$)in print%end)"val()=hd[(fn s=>let val$ =s^\"\\\"\"^String.toString s^\"\\\")\"val(189,%)=(size$,$)in print%end)"]

Try it online!
For MLton, full SML programs are either expressions delimited and terminated by ; (e.g. print"Hello";print"World";) or declarations with the var and fun keywords (e.g. var _=print"Hello"var _=print"World") where _ is a wild card which could also be replaced by any variable name.
The first option is useless for pristine programming because ; on its own is a valid program (which does nothing, but doesn't error either). The problem with the second approach is that declarations like var _=print"Hello" can be shortened to just var _="Hello" (or even var _=print) because the declaration with var works as long as the right-hand side is a valid SML expression or value (SML is a functional language, so functions can be used as values too).
At this point, I was ready to declare pristine programming in SML impossible, when by chance I stumbled upon pattern matching in val-declarations. It turns out that the syntax for declarations is not val <variable_name> = <expression> but val <pattern> = <expression>, where a pattern can consist of variable names, constants and constructors. As the print function has type string -> unit, we can use a pattern match on the unit-value () to enforce that the print function is actually applied to the string: val()=print"Hey". With this approach, removing either print or "Hey" results in a Pattern and expression disagree-error.
With this way of pristine printing at hand, the next step is to write a quine, before finally some more save-guarding needs to be added. I previously used an easy SML quine technique (see the revision history), but Anders Kaseorg pointed out a different approach which can save some bytes in his case. It uses the built-in String.toString function to handle string escaping and is of the general form <code>"<data>", where "<data>" is an escaped string of the code before:
val()=(fn s=>print(s^"\""^String.toString s^"\""))"val()=(fn s=>print(s^\"\\\"\"^String.toString s^\"\\\"\"))"

This is a working quine but not yet pristine. First of all Anders Kaseorg found out that MLton accepts a single quote " as code without producing errors, which means we cannot have code ending in a quote as above. The shortest way to prevent this would be to wrap everything after val()= in a pair of parenthesis, however then the code could be reduced to val()=(). The second shortest way I found is to use val()=hd[ ... ], that is we wrap everything into a list and return its first element to make the type checker happy.
To make sure that no part of the data string can be removed without being noticed, the pattern-matching in val-declarations comes in handy again: The length of the final string to be printed (and thus the program length) should equal 195, so we can write let val t=... val 195=size t in print t end in the body of the fn abstraction instead of print(...). Removing a part of the string results in a length less than 189, thus causing a Bind exception to be thrown.
There is still an issue left: the whole val 195=size t check could simply be dropped. We can prevent this by expanding the check to match on a tuple: val t=... val(216,u)=(n+size t,t)in print u end, such that removing the check results in an unbound variable u.
Altogether, this yields the following 195 byte solution:
val()=hd[(fn s=>let val t=s^"\""^String.toString s^"\")"val(195,u)=(size t,t)in print u end)"val()=hd[(fn s=>let val t=s^\"\\\"\"^String.toString s^\"\\\")\"val(195,u)=(size t,t)in print u end)"]

Applying the golfing trick of using operator variable names like !, $ and % instead of n, t and u in order to save some white space (see this tip) leads to the final 182 byte version.
All other substring-removals which where not explicitly stated in the explanation should result in a syntax or type error.
Edit 1: length(explode t) is just size t.
Edit 2: Thanks to Anders Kaseorg for a different quine approach and pointing out a "vulnerability".

−2 bytes by writing "\"" directly and using String.toString for escaping.

Wait, this is horrible: MLton seems to accept the program ", producing empty output (TIO).

@AndersKaseorg Huh, that's strange. However it should be possible to fix this issue by using another let ... in ... end.

@AndersKaseorg I fixed the issue, hopefully without introducing new "vulnerabilities".

Actually I looked into MLton accepting " as a program, and it seems that bug was fixed in this commit, so maybe your 182 or my 180 is fine as long as you specify the unreleased Git version of MLton.

Furthermore, your fix isn’t sufficient on the released MLton, which also accepts "] as a program (TIO). (By the way, you have a ) that should be ].)

@AndersKaseorg I think I just specify Moscow ML. mosmlc rejects unclosed string literals. Also I found a 178 byte version: Try it online! , but I don't want to rewrite the explanation yet again.

Ruby, 78 bytes
eval(*[($>.write((s=%{eval(*[($>.write((s=%%{%s})%%s)-78).chr])})%s)-78).chr])

I wrote this when I thought of the challenge to make sure it was possible. It uses the same "wrapper" from one of my answers to the original pristine challenge.
Explanation:

eval(*[ expr ])
This evaluates whatever code returns as a ruby program. This effectively tests that the string that code returns is a valid ruby program. Conveniently, ruby programs can be blank, or only consist of whitespace.
The "splat" operator * allows you to use an array as arguments to a function. This also means that if eval is removed, the resulting program is (*[ expr ]), which is not valid ruby.
($>.write( str )-78).chr
$> is a short variable for STDOUT.
$>.write(foo) writes foo to STDOUT and, importantly for this code, returns the number of bytes written.
$>.write(foo)-78: Here 78 is the length of the program, and so if the program is not mangled, will also be the number of bytes written. Therefor, in the unmangled case, this will return zero.
num.chr returns num as a character, eg 0.chr will return a string containing a single null byte. In the unmangled program, this will give a string with a single null byte to eval, which is a valid ruby program that is a no-op.
Also, the program can have a substring removed such that it's just eval(*[(78).chr]) or eval(*[(8).chr]), which means that the numeric constant cannot end with any of the numbers (0, 4, 9, 10, 11, 12, 13, 26, 32, 35, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 59, 64, 95) because they are ascii codes for valid single-character ruby programs.
%{ str }
This is a lesser-known syntax for string literals in ruby. The reason it's used here is that balanced pairs of {} can be used within the string, which means this syntax can contain itself. For example, %{foo{bar}} is the same as "foo{bar}".
(s=%{ data })%s
This defines the variable s which is the data of this quine, as a printf string.
Assignments in ruby return what was assigned, so this is the same as first assigning s and then running s%s
% on a string is syntatic sugar for ruby's equivalent of sprintf. The %s signifies where within the data the data itself should be embedded.
This bit of code defines the data portion of the quine and embeds it within itself to create the full code.