text:
Factory workers
Challenge
Factory workers are usually very hard-working. However, their work is now being commonly replaced with machines.
You have to write a program that takes a number as input. It will print out a factory of 10 workers 10 times. Every time, each worker has a 1/input chance of being 'fired' and replaced by a machine.
Input
An integer, coming from STDIN or a function call.
Output
10 cases of the factory, each one with usually more workers fired.
Output format - how to print a factory
A factory looks like this:
|0000000000| or |0000011001|
A pipe represents the walls, a 0 represents a worker, and a 1 represents a machine, so the first print of the factory will always be |0000000000|.
Example
Input: 10
Output:
|0000000000| //always start off with this
|0000000010| //a 1/10 chance means that this worker lost his job
|0000010010|
|0010010010|
|1010010010|
|1010110010|
|1010110011|
|1010111011|
|1010111111|
|1110111111|

Input: 5
Output:
|0000000000| //always start here
|0000001001| //a 1/5 chance means that 2 workers got fired
|1000101001|
|1000101111|
|1101101111|
|1111111111| //after achieving all machinery, the machines continue to be printed
|1111111111|
|1111111111|
|1111111111|
|1111111111|

NOTE
The number of workers fired is RANDOM - in my examples for 1/5 chance there would always be 2 workers fired but your program has to do this randomly - sometimes 1 and sometimes 3 - they just have 1/5 chance of being fired.

The input is always >1? what happens if you still have a worker after 10 iterations ?

It doesn't matter - the worker can be considered very lucky ;)

Does an input of 10 mean that each worker has a 1/10 chance of losing their job each time, or that 1/10th of the workers will be fired each time?

The former as specified in the NOTE (sometimes 1 sometimes 3)

can we have spaces between the workers, like | 0 0 0 0 0 0 0 0 0 0 |?

@12Me21 it means each worker has a 1/10 chance of losing their job, NOT the latter.

@Uriel No, I'm mean =)

@Arnauld it seems like it was simply a mistake, and I was the only one who took it as correct :)

Shouldthe 1/x chance per worker or per employed worker?

@Pureferret It doesn´t matter. Any worker already sacked could have a (x-1)/x chance of not being fired again; but he stays fired.

Japt -R, 22 21 20 19 18 bytes
AÆP=®|!UöÃªAçTÃû|C

Try it

Explanation
AÆP=®|!UöÃªAçTÃû|C     :Implicit input of integer U
A                      :10
 Æ                     :Map the range [0,A)
  P=                   :  Assign to P (initially the empty string)
    ®                  :    Map P
     |                 :      Bitwise OR with
      !                :      The negation of
       Uö              :      A random integer in the range [0,U)
         Ã             :    End Map
          ª            :    OR, for the first element when the above will still be an empty string (falsey)
           Aç          :    Ten times repeat
             T         :      Zero
              Ã        :End Map
               û|      :Centre pad each element with "|"
                 C     :  To length 12
                       :Implicitly join with newlines and output

R, 92 89 bytes
cat(t(cbind("|",apply("[<-"(matrix(runif(100)<1/scan(),10),1,,0),2,cummax),"|
")),sep="")

Try it online!
Ungolfed:
m <- matrix(runif(100)<1/n,10,10)   #10x10 matrix of TRUE with probability 1/n
                                    #and FALSE with probability 1-1/n
m[1,] <- 0                          #set first row to 0
m <- apply(m,2,cummax)              #take the column cumulative maxima
m <- cbind("|",m,"|\n")             #put "|" as the first and last columns
m <- t(m)                           #transpose m for the write function
cat(m,sep="")                       #print m to stdout, separated by ""

I spent quite a bit of time trying to beat 92 this afternoon using various implementations of replicate and for loops without success, however but with your tips for Do-while loops, I have finally just realized how abusable { potentially this. I have extended this abuse to an example with for() for a 92 bytes solution. Maybe you already realized the implications of { abuse when you wrote that tip post, but I have realized just now. https://tio.run/##K/r/PyEtvyhBI1OnusK2ODkxT0PTusy2KLVAw0DH0EDT2tDKslanOjmxREOpRkmnTEephktJpzi1wFZJCaQwN7GgIKcSKldUmpeZpgHUZWOoX6GpbVCr@d/0PwA

@Vlo Is that the right TIO link? Still, looks like you've beaten me with a function! I golfed you down to 82 bytes

I should start an R chatroom... I think "for" is almost always no better than for, and it's occasionally worse!

Haha, of course pmax can be used. Here is my earlier point about the { operator. https://tio.run/##PZDBasNADETv@xVDfKhNjcGHXAKl5OJTT2l/YGPL2aXLKmjlBBP67e7WSXoRCL2RZiTLshlZNqWv29227t6617ZCAXU@4crxRXOVb9MtBb4c4QY@k1hlQW8jjgS@kAS2Aw24enVQhpWjV7EyQ6YIG2f0PNA69vf@gHGKvXqODfYJFkJpClo/hit@4jAiOZ7CgCxTRyzzO6aUb8Yw50JIpOARZdWs7nISBOYzsvmsFCV5JLFzY0yBD44nEpO50uelt7/M2137U9W91dJXVWY@70Lz/Ms/9GSWXw

JavaScript (ES6), 84 bytes
n=>[...s=2e9+''].map(j=>`|${s=s.replace(/./g,i=>i&1|Math.random()*n<!+j)}|`).join`
`

Try it online!

Recursive version, 88 bytes
n=>(g=k=>k?`|${s=s.replace(/./g,i=>i%5|Math.random()*n<(s!=k))}|
`+g(k>>3):'')(s=5e9+'')

Try it online!
How?
We start with k = s = '5000000000'.
At each iteration:

We coerce each character i of s to a number, compute i modulo 5 -- so that the leading 5 is treated like a 0 -- and randomly perform a bitwise OR with 1 with the expected probability 1/n, except on the first iteration.
The counter k is right-shifted by 3 bits. We stop the recursion as soon as k = 0, which gives 10 iterations.
It is important to note that 5000000000 is slightly larger than a 32-bit integer, so it is implicitly converted to 5000000000 & 0xFFFFFFFF = 705032704 just before the first bitwise shift occurs. Hence the following steps:
 step | k
------+-----------
   0  | 705032704
   1  | 88129088
   2  | 11016136
   3  | 1377017
   4  | 172127
   5  | 21515
   6  | 2689
   7  | 336
   8  | 42
   9  | 5
  10  | 0

APL (Dyalog), 37 bytes
⎕{⎕←' '~⍨⍕'|'⍵'|'⋄×⍵+⍺=?10⍴⍺}⍣10⊢10⍴0

Try it online!
How?
10⍴0 - start with 10 zeros.
⎕←' '~⍨⍕'|'⍵'|' - every time print the formatted array,
?10⍴⍺ - generate a random array with values ranging 1 to input,
⍺= - element-wise comparison with the input. should mark 1 / input of the elements, giving each a 1 / input every time,
⍵+ - add to the array,
× - signum. zero stays zero, anything greater than one comes back to one.
⍣10 - repeat 10 times.

Confused I am, +1 =)

PowerShell, 82 80 69 bytes
param($x)($a=,0*10)|%{"|$(-join$a)|";$a=$a|%{$_-bor!(Random -ma $x)}}

Try it online!
Takes input $x. Creates an array of all zeros, saves that into $a and then loops that many times. Conveniently, the factory is just as wide as it is iterations worth. Each iteration, we output our current factory with "|$(-join$a)|", then loop through each element of $a.
Inside we're selecting the current element $_ that has been -binary-ored with either 1 based on the Random chance based on input $x. For example, for input 10, Get-Random -max 10 will range between 0 and 9 and be 0 approximately 1/10th of the time. Thus with a !(...) wrapping the Random, we'll get a 1 approximately 1/input amount of the time, and the other 1-1/input amount of the time we'll get $_. Yes, this sometimes means that we're overwriting a 1 with another 1, but that's fine.
That resulting array is then stored back into $a for the next go-round. All of the resulting strings are left on the pipeline, and the implicit Write-Output at program completion gives us newlines for free.
-2 bytes thanks to Veskah.
-11 bytes thanks to ASCII-only.

80 Bytes?

@Veskah Yes, that will work nicely. Thanks!

78?

69????

@ASCII-only Oh sure, why are we re-indexing into $a when we're already looping through it? lol And that's a clever trick with the -bor. Thanks!

Retina, 30 bytes
.+
|¶10*$(*0¶
.-10+0\%0<@`\d
1

Try it online!
I'm having lots of fun with randomness in Retina^^
Explanation
The first stage sets up the string we will be working with:
.+
|¶10*$(*0¶

It replaces the whole input with |, a newline, and then 10 lines containing as many 0s as the input says. The first character on each line will represent a   worker of the factory.
The following stage means:
.                     Disable automatic printing at the end of the program
 -10+                 Do the following exactly 10 times:
       %                For each line:
        0<                Print the first character, then
          @`\d            Pick a random digit and
1 (on the next line)      replace it with a 1
     0\                 Then print the first character of the whole string
                        followed by a newline

The first line of the working string contains only a |, which will be the first character printed by every iteration of the loop (being the first character of the first line), and will be also printed at the end of every iteration (being the first character of the whole string). The replacement will never have any effect on this line because it doesn't contain any digit.
Each other line contains n digits, so there is a 1 in n chance to turn the first character of the line (which is the only meaningful one) into a 1.

Python 2, 104 103 bytes
from random import*
x='0'*10;i=input()
exec"print'|%s|'%''.join(x);x=[choice('1'+n*~-i)for n in x];"*10

Try it online!

Sorry, you need to format the output

@lolad fixed c:

well done, +1 =)

JavaScript (Node.js), 105 93 90 bytes
x=>w.map(a=>(`|${w=w.map(j=>j|Math.random()<1/x),w.join``}|
`)).join``,w=Array(10).fill(0)

Try it online!
+2 bytes for putting the array inside the function, thanks to @Shaggy for pointing that out
(x,w=Array(10).fill(0))=>w.map(a=>(`|${w=w.map(j=>j|Math.random()<1/x),w.join``}|
`)).join``

Try it online!

Note that functions need to be reusable here, so w will need to be declared within your function.

@Shaggy, thanks I edited it. unfortunately it added 2 bytes

Jelly, 22 bytes
ẋ⁵ẋ€⁵¬1¦X€€=1o\j@€⁾||Y

A full program accepting the integer as a  command line input and printing the output to STDOUT.
(As a monadic link it returns a list of characters and integers.)
Try it online!
How?
Effectively decides at each stage if each worker (including any machines) lose their job (with a one in N chance), however machines are replaced by machines (using logical-OR).
ẋ⁵ẋ€⁵¬1¦X€€=1o\j@€⁾||Y - Main link: integer, N
 ⁵                     - literal ten
ẋ                      - repeat -> [N,N,N,N,N,N,N,N,N,N]
    ⁵                  - literal ten
  ẋ€                   - repeat €ach -> [[N,N,N,N,N,N,N,N,N,N],...,[N,N,N,N,N,N,N,N,N,N]]
       ¦               - sparse application...
      1                - ...to indices: [1]
     ¬                 - ...do: logical-NOT -> [[0,0,0,0,0,0,0,0,0,0],[N,N,...],...]
        X€€            - random integer for €ach for €ach
                       -   (0s stay as 0s; Ns become random integers in [1,N])
           =1          - equals one? (vectorises)
             o\        - cumulative reduce with logical-OR
                  ⁾||  - literal list of characters = ['|','|']
               j@€     - join with sw@pped arguments for €ach
                     Y - join with line feeds
                       - implicit print

Perl 6, 58 bytes
{say "|$_|" for 0 x 10,|[\~|] ([~] +(1>$_*rand)xx 10)xx 9}

Try it online!
+(1 > $_ * rand) generates a single bit with the required frequency of 1s.  xx 10 replicates that expression ten times to produce a single factory instance as a list of bits, and [~] joins that list into a single string.  xx 9 replicates that factory-string-generating expression nine times, and then [\~|] does a triangular reduction (which some other languages call a "scan") with the stringwise or operator ~|, so that a worker fired in an earlier iteration remains fired in later ones.

Nice. You can remove the space before for. Beats the number-based solution {say "|{.join}|"for [\<<+|>>] (?$++X*!<<^$_).roll(10)xx 10} I was working on by two bytes. With [\Z+|] it would be 56 bytes but this doesn't work for some reason.

You can also replace $_*rand with .rand. The way I interpret the rules, returning a list of "factory" strings should also be OK.

C (gcc), 110 106 bytes
-4 bytes from @ceilingcat
char l[]="|0000000000|",i,j;f(n){for(srand(time(i=0));i++<10;)for(j=!puts(l);j++<10;)rand()%n||(l[j]=49);}

Try it online!
Iterates through a list of characters for each round of replacements.
Ungolfed:
f(n)
{
    //start with a fresh factory
    char l[]="|0000000000|";

    //init rng
    srand(time(0));

    //print 11 lines
    for(int i = 0; i < 11; i++)
    {
        //print current factory
        puts(l);

        //iterate through the workers. start at index 1 to skip the '|'
        for(int j = 1; j < 11; j++)
        {
            //the expression (rand()%n) has n possible values in the range [0,n-1],
            //so the value 0 has 1/n chance of being the result and thus the worker
            //has 1/n chance of being replaced
            if(rand()%n == 0)
            {
                l[j] = '1';
            }
        }
    }
}

I think you print 1 too many factories. The example shows 10, but your TIO link shows 11.

Hm you're right. I changed it to 11 after reading a comment on someone else's solution telling them it's supposed to be 11, but I never actually verified the example from the challenge. Thanks

MATL, 26 bytes
'|'it10th&Yr=0lY(Y>48+y&Yc

Try it online!
(Long) explanation
Example stack contents are shown along the way. At each step, stack contents are shown bottom to top.
'|'    % Push this character
       % STACK: '|'
it     % Take input. Duplicate
       % STACK: '|'
                5
                5
10th   % Push [10 10]
       % STACK: '|'
                5
                5
                [10 10]
&Yr    % Random 10×10 matrix of integers from 1 to input number
       % STACK: '|'
                 5
                 [4 5 4 4 5 5 2 1 2 3
                  3 4 3 3 1 4 4 3 1 5
                  5 1 4 5 4 4 5 2 3 2
                  3 4 5 2 1 3 2 5 3 4
                  4 1 2 2 4 1 1 5 1 1
                  4 5 3 1 5 3 5 2 4 1
                  2 1 4 3 3 1 3 5 3 5
                  1 2 2 1 2 2 4 3 5 3
                  4 5 4 1 2 2 5 3 2 4
                  4 1 2 5 5 5 4 3 5 1]
=      % Is equal? Element-wise
       % STACK: '|'
                [0 1 0 0 1 1 0 0 0 0
                 0 0 0 0 0 0 0 0 0 1
                 1 0 0 1 0 0 1 0 0 0
                 0 0 1 0 0 0 0 1 0 0
                 0 0 0 0 0 0 0 1 0 0
                 0 1 0 0 1 0 1 0 0 0
                 0 0 0 0 0 0 0 1 0 1
                 0 0 0 0 0 0 0 0 1 0
                 0 1 0 0 0 0 1 0 0 0
                 0 0 0 1 1 1 0 0 1 0]
0lY(   % Write 0 in the first row
       % STACK: '|'
                [0 0 0 0 0 0 0 0 0 0
                 0 0 0 0 0 0 0 0 0 1
                 1 0 0 1 0 0 1 0 0 0
                 0 0 1 0 0 0 0 1 0 0
                 0 0 0 0 0 0 0 1 0 0
                 0 1 0 0 1 0 1 0 0 0
                 0 0 0 0 0 0 0 1 0 1
                 0 0 0 0 0 0 0 0 1 0
                 0 1 0 0 0 0 1 0 0 0
                 0 0 0 1 1 1 0 0 1 0]
Y>     % Cumulative maximum down each column
       % STACK: '|'
                [0 0 0 0 0 0 0 0 0 0
                 0 0 0 0 0 0 0 0 0 1
                 1 0 0 1 0 0 1 0 0 1
                 1 0 1 1 0 0 1 1 0 1
                 1 0 1 1 0 0 1 1 0 1
                 1 1 1 1 1 0 1 1 0 1
                 1 1 1 1 1 0 1 1 0 1
                 1 1 1 1 1 0 1 1 1 1
                 1 1 1 1 1 0 1 1 1 1
                 1 1 1 1 1 1 1 1 1 1]
48+    % Add 48, element-wise. This transforms each number into the
       % ASCII code of its character representation
       % STACK: '|'
                [48 48 48 48 48 48 48 48 48 48
                 48 48 48 48 48 48 48 48 48 49
                 49 48 48 49 48 48 49 48 48 49
                 49 48 49 49 48 48 49 49 48 49
                 49 48 49 49 48 48 49 49 48 49
                 49 49 49 49 49 48 49 49 48 49
                 49 49 49 49 49 48 49 49 48 49
                 49 49 49 49 49 48 49 49 49 49
                 49 49 49 49 49 48 49 49 49 49
                 49 49 49 49 49 49 49 49 49 49]
y      % Duplicate from below
       % STACK: '|'
                [48 48 48 48 48 48 48 48 48 48
                 48 48 48 48 48 48 48 48 48 49
                 49 48 48 49 48 48 49 48 48 49
                 49 48 49 49 48 48 49 49 48 49
                 49 48 49 49 48 48 49 49 48 49
                 49 49 49 49 49 48 49 49 48 49
                 49 49 49 49 49 48 49 49 48 49
                 49 49 49 49 49 48 49 49 49 49
                 49 49 49 49 49 48 49 49 49 49
                 49 49 49 49 49 49 49 49 49 49]
                 '|'
&Yc    % Horizontally concatenate all stack contents as char arrays.
       % 1-row arrays are implicitly replicated along first dimension
       % STACK: ['|0000000000|'
                 '|0000000001|'
                 '|1001001001|'
                 '|1011001101|'
                 '|1011001101|'
                 '|1111101101|'
                 '|1111101101|'
                 '|1111101111|'
                 '|1111101111|'
                 '|1111111111|']
       % Implicitly display

SmileBASIC, 75 bytes
INPUT N
FOR J=0TO 9?"|";BIN$(F,10);"|
FOR I=0TO 9F=F OR!RND(N)<<I
NEXT
NEXT

Perl 5, 44 bytes
#!/usr/bin/perl -a
say"|$_|",s/0/rand"@F"<1|0/eg<0for(0 x10)x10

Try it online!

05AB1E, 22 bytes
TÅ0TFDJ'|.ø=sITи€L€ΩΘ~

Try it online!
There should be some more room for golfing.

TÅ0 — Push a list of 10 zeroes.
TF... — Do this 10 times:

DJ — Duplicate the current item and join it.
'|.ø= — Surround it with two |s and print to STDOUT.
ITи — Repeat the input 10 times.
€L€Ω — And for each occurrence, get a random element of [1 ... N]. (There might be a built-in for this which I haven’t seen yet)
Θ — Push 05AB1E truthified™. For each, check if it equals 1.
s...~ — Logical OR the result by the current item.

Charcoal, 30 29 27 bytes
⊞υ×χ0Ｆχ⊞υ⭆§υ±¹‽⁺1×κ⊖θＥυ⪫||ι

Try it online! Link is to verbose version of code. Explanation:
⊞υ×χ0

Push an string of 10 0s to the empty list u.
Ｆχ

Repeat the next command 10 times.
⊞υ⭆§υ±¹‽⁺1×κ⊖θ

For each character of the last string, repeat it n-1 times, add a 1, and pick a random character from the string. This gives a 1/n chance of changing the character to a 1. The result is pushed to u.
Ｅυ⪫||ι

Map over the list of strings, surrounding each with |, then implicitly print each on its own line.

JavaScript, 83 bytes
f=(n,t=9,s=`|0000000000|
`)=>t?s+f(n,t-1,s.replace(/0/g,v=>+(Math.random()<1/n))):s

f=(n,t=9,s=`|0000000000|
`)=>t?s+f(n,t-1,s.replace(/0/g,v=>+(Math.random()<1/n))):s

<input id=i value=10 /><button id=t onclick="o.textContent=f(+i.value)">Run</button>

80 bytes

Java 10, 153 152 131 bytes
n->{for(int j=10,a[]=new int[j],i;j-->0;){var s="|";for(i=0;i<10;a[i++]|=Math.random()*n<1?1:0)s+=a[i];System.out.println(s+"|");}}

-18 bytes thanks to @OlivierGrégoire, and -3 more bytes by converting Java 8 to Java 10.
Explanation:
Try it online.
n->{                             // Method with integer parameter and no return-type
  for(int j=10,a[]=new int[j],i; //  Create the array with 10 workers (0s)
      j-->0;){                   //  Loop 10 times

    var s="|";                   //  Start a String with a wall
    for(i=0;i<10;                //  Loop `i` from 0 to 10 (exclusive)
        a[i++]                   //    After every iteration, change the current item to:
         |=                      //     If it's a 0:
           Math.random()*n<1?    //      If the random value [0:1) is below 1/n
            1                    //       Change the worker to a machine
           :                     //      Else:
            0;                   //       It remains a worker
                                 //     Else (it already is a machine)
                                 //      It remains a machine
      s+=a[i];                   //   Append the current item to the String
    System.out.println(s+"|");}} //   Print the String, with a trailing wall and new-line

131 bytes. Replace var by String for Java 9 and below and for an extra 3 bytes. I basically merged the two loops you have.

VBA, 144 bytes
Sub f(i)
Dim w(9) As Long
For x = 0 To 9
s = "|"
For y = 0 To 9
s = s & w(y)
If i * Rnd() < 1 Then w(y) = 1
Next
Debug.Print s; "|"
Next
End Sub

Indented for easier reading:
Sub f(i)
    Dim w(9) As Long
    For x = 0 To 9
        s = "|"
        For y = 0 To 9
            s = s & w(y)
            If i * Rnd() < 1 Then w(y) = 1
        Next
        Debug.Print s; "|"
    Next
End Sub

Takes advantage of 2 points: VBA Arrays will default to Base 0 (so w(9) is the same as w(0 to 9)) and creating the Array as a Long will automatically initialise it to 0.
(Annoyingly, 20 bytes are auto-formatting that VBA adds in but not actually required - 19 spaces and one semi-colon)

APL+WIN, 30 40  35 bytes
Missed the bit about no spaces ;( - fixed  & thanks to Uriel for -3 bytes
Prompts for screen input of number
'|',(⍕0⍪×+⍀n=?9 10⍴n←⎕)[;2×⍳10],'|'

Explanation similar to that of Uriel:
?9 10⍴n create a 9x10 matrix of numbers selected at random between 1 and number

×+⍀n= compare elements of matrix to number, cumulatively sum columns and signum

[;2×⍳10] take non-space columns

'|',(⍕0⍪.......,'|' concatenate a row of zeros and front and back columns of |

9 10⍴?90⍴5 → ?9 10⍴5. You also need to eliminate spaces

@Uriel thanks for the -3 bytes and I had missed the no space rule.

Python 3, 132 bytes
from random import*
w,p,c=[0]*10,'|',1/int(input())
for _ in w:print(p+''.join(map(str,w))+p);w=list(map(lambda x:x|(random()<c),w))

Try it online!

I don't see answer for Ruby yet, so:
Ruby, 92 bytes
n=gets.to_i
z='0'*x=10
x.times do
puts'|'+z+'|'
x.times do|s|
z[s]='1' if rand(n)==0
end
end

Try it online!

Save a byte by using rand(n)<1 instead of rand(n)==0, and save a few by using {..} instead of do..end, e.g. x.times{puts'|'+z...}

Ruby, 67 bytes
->n{f=[0]*10;10.times{p"|#{f.join}|";f.map!{|l|rand>(1.0/n)?l:?1}}}

I think I've cheated a few things here. First of all, this function prints the output with quotes around each line, e.g.:
pry(main)> ->n{f=[0]*10;10.times{p"|#{f.join}|";f.map!{|l|rand>(1.0/n)?l:?1}}}[5]
"|0000000000|"
"|0100100000|"
"|0100100000|"
"|0100100000|"
"|0100100100|"
"|0100110100|"
"|0101110100|"
"|0111110100|"
"|1111110110|"
"|1111110110|"
=> 10

If this is unacceptable (given that this is ascii-art, that is probably the case), here is a solution that prints without quotes for 70 bytes:
->n{f=[0]*10;10.times{puts"|#{f.join}|";f.map!{|l|rand>(1.0/n)?l:?1}}}

Explanation:
->n{                                                              } # defines anonymous lambda
    f=[0]*10;                                                       # initializes f to [0,0,0,...] (10)
             10.times{                                           }  # main loop
                      p"|#{f.join}|";                               # joins f and prints | before and after
                                     f.map!{|l|                 }   # maps each element of f
                                               rand>(1.0/n)? :      # if rand is greater than 1.0/n
                                                            l ?1    # keep current element or replace with '1'

PHP, 71 70 bytes
merging loops saved 5 bytes (again):
for(;$k<91;$v|=!rand(0,$argn-1)<<$k++%10)$k%10||printf("|%010b|
",$v);

Run as pipe with -nR or try it online.

edit 1: fixed format and first output (no change in byte count thanks to additional golfing)
edit 2: Golfed one more byte: After the last printing, there´s no more need for firing anyone.

C# (Visual C# Interactive Compiler), 131 bytes
n=>{var r=new Random();var a=new int[10];for(int i=0;i<100;a[i%10]|=r.Next(n)<1?1:0)if(i++%10<1)Write("|"+string.Concat(a)+"|\n");}

Hey, at least I tied with Java.
Try it online!


text:
Read color in my way
Different systems have different ways to describe colors, even if all of them are speaking in R-G-B-A space. A front-end developer who is familiar with CSS may prefer #RRGGBBAA. But Android developers may prefer #AARRGGBB. When handling AAS file format, #AABBGGRR is needed. That's too confusing. Maybe we need a program which can convert between different color formats.
Input:
The input contains 3 parts:

The color to be transformed (e.g. #1459AC0F), a string starting with sharp sign # followed by 8 hex digits.
The format of the given color (e.g. #RRGGBBAA), a string starting with # followed by 8 letters which fall into 4 different groups and each group is one of RR/GG/BB/AA.
The format to convert to.

Output:

Output the color in converted format

Test Cases:
Color, OriginalFormat, TargetFormat -> Result
#12345678, #RRGGBBAA, #AARRGGBB -> #78123456
#1A2B3C4D, #RRGGBBAA, #AABBGGRR -> #4D3C2B1A
#DEADBEEF, #AARRGGBB, #GGBBAARR -> #BEEFDEAD

Input / output are case insensitive. You may input / output in any acceptable way.
Rules:
This is code golf, shortest (in byte) codes of each language win

AARRGGBB is objectively the best color format. If something expects 24 bit RRGGBB and you give it 32 bit AARRGGBB instead, it can just ignore the upper byte and still work.

The color DEADBEEF looks a little Salmon-y.

I've been a front end web dev for years now and I'd never heard of #RRGGBBAA until today, wish more browsers supported it.

@12Me21 And the next question is which endianness is better.

APL (Dyalog Unicode), 6 bytesSBCS
Full program. Prompts on STDIN for Original, then Target, then Color. Prints Result to STDOUT.
⍞[⍞⍋⍞]

Try it online!
  ⍞ prompt for Original
 ⍞⍋ prompt for Target and find the indices into Original that would make Original into Target
⍞[…] prompt for Color and use the above obtained indices to reorder Color

JavaScript (ES6), 53 52 bytes
Saved 1 byte thanks to @tsh
Takes input as 3 distinct parameters: (Color, From, To).
(C,F,T)=>T.replace(/\w/g,(x,i)=>C[F.search(x)-~i%2])

Try it online!

(C,F,T)=>T.replace(/\w/g,(x,i)=>C[F.search(x)-~i%2]) save one byte

@tsh Nice one. ^^

Stax, 8 bytes
ç▼☺↔kàÅJ

Run and debug it
This program takes input in this format.
"{Color}" "{OriginalFormat}" "{TargetFormat}"

Here's the commented ungolfed unpacked version of the same program.
u       drop duplicated characters from target format
{       for each character remaining in target format, map using block...
  [     duplicate original format at second position in stack
  |I    get all indices of target character in original format
  xs@   retrieve characters from those indices from the color string
m       perform map
        output implicitly when complete

Run this one

Python 2, 59 bytes
lambda c,o,t:'#'+''.join(c[o.find(v):][:2]for v in t[1::2])

Try it online!

Retina 0.8.2, 33 bytes
(.)(?<=(..).{7}\1\1.*)\1
$2
.*#
#

Try it online! Link includes test cases. Explanation:
(.)(?<=(..).{7}\1\1.*)\1
$2

For each pair of identical characters, look back for another copy of that pair, and then the 9th and 8th characters before that, and replace the pair with those characters. This is only possible for the pairs of characters in the target format, and replaces them with the desired result.
.*#
#

Delete the colour and source format.

Haskell, 108 104 100 94 87 bytes
(s,(r@(x,y):z))!c|x==c=(s++[y],z)|(p,q)<-(s,z)!c=(p,r:q)
c%i=fst.(foldl(!)("",zip i c))

Try it online!

Old version
Thanks to Laikoni for shortening 6 bytes by finding a shorter way to use lookup!
f(Just x)=x
p('#':z)=p z
p(x:y:z)=[x,y]:p z
p e=[]
c!i=('#':).(f.(`lookup`zip(p i)(p c))=<<).p

Try it online!
Explanation:

the p function "parses" a string by ignoring the leading # and returning groups (lists) of 2 chars.
the (!) operator takes as input the color and the input format and returns a function that takes as a parameter the output format and returns the converted color. It turned out that the pointfree version was shorter, but I started with the more readable version:

f c i o='#':concat[x#zip(p<$>[i,c])|x<-p o]
Try it online!

Perl 5 -p, 33 32 27 bytes
Give input in the order: target, original, number
#!/usr/bin/perl -p
s%.%$2x/(..)+$&(.){10}/g%eg

Try it online!
For each character in the input find the same character an even number of places forward then from there go 10 more characters forward and take that character as replacement. If you can't do these steps replace by nothing.
    +--even-+----10---+
    |       |         |
#AARRGGBB #RRGGBBAA #12345678
    |    >-will get removed-<
    v
    2

05AB1E, 10 bytes
2FI2ô™J}I‡

Try it online!

2F     }   # Loop twice...
  I        # First 2 inputs.
   2ô™     # Title case in pairs of 2.
      J    # Rejoin together.
        I  # Last input (The color).
         ‡ # Transliterate, put color in pattern from a into pattern from b.

This works because I change the input from:
AARRGGBB

To:
AaRrGgBb

So each value is mapped uniquely, then I can use transliterate.
The arguments are reversed.

Java 10, 179 105 102 bytes
(a,b,c)->{var r="#";for(int i=1,t;i<9;)r+=a.substring(t=b.indexOf(c.substring(i,i+=2)),t+2);return r;}

Whopping -77 bytes thanks to @OlivierGrégoire.
Explanation:
Try it online.
(a,b,c)->{            // Method with String as three parameters and return-type
  var r="#";          //  Result-String, starting at "#"
  for(int i=1,t;i<9;  //  Loop `i` from 1 to 9 (exclusive)
    r+=               //   Append the result with:
       a.substring(   //    A substring from the first input,
        t=b.indexOf(  //    where an index is determined in the second input
           c.substring(i,i+=2)),t+2);
                      //    based on a substring of the third input
    return r;}        //  Return the result-String

105 bytes Builds the string from the target by finding the target element in the source format.

@OlivierGrégoire I knew it would be possible without that pesky Map. Thanks a lot, -74 bytes right there!

102 bytes by switching to Java 10, which is now supported on TIO.

J, 5 bytes
/:i./

The left argument is the color. The right argument is a character matrix where the first row is the target format and the second row is the original format. Try it online!

CJam, 14 bytes
{'#\1f>2f/~er}

Try it Online!
Input is an array in the reverse order.
{
 `#\      e# Push '#'+[input array] on to stack
  1f>     e# Remove the '#' symbol from each input string
  2f/     e# Split each input string into an array of substrings of length 2.
  ~       e# Dump the substring-arrays from the container array onto the stack
  er      e# Perform a string replace operation
}

Python 2, 62 bytes
lambda c,s,e:[c[s.index(e[i]):][:2]for i in range(1,len(e),2)]

Perl 6, 55 51 46 bytes
{[~] %(@^b Z=>@^a){@^c}}o*.map(*.comb(/\w?./))

Try it online!
Takes a (color, original, target) list as input. Splits each input string into components, creates a Hash mapping source keys to color values, looks up color values in target key order, then formats the result.

SmileBASIC, 144 bytes
DEF R C,I,O
C[0]="&H
A=R+G+B
RGBREAD VAL(C)OUT VAR(I[1]),VAR(I[3]),VAR(I[5]),VAR(I[7])?"#";RGB(VAR(O[1]),VAR(O[3]),VAR(O[5]),VAR(O[7]))END

Python 3, 102 bytes
lambda x,a,b:['#']+[[x[i:i+2]for i in range(1,len(x),2)][i]for i in[a[1::2].index(i)for i in b[1::2]]]

Try it online!

Red, 154 120 114 bytes
func[c o t][g: func[q][parse q[skip collect 4 keep 2 skip]]
prin"#"foreach p g t[prin pick g c index? find g o p]]

Try it online!

Jelly, 6 bytes
ẹÐ€Qị⁵

Try it online!
Full program.
Argument 1: Original
Argument 2: Target
Argument 3: Color

C (clang), 89 bytes
char *a,b[10],*i,*o;f(x,y){*b=*a;for(x=1;x<8;b[x++]=a[y=index(i,o[x])-i],b[x++]=a[y+1]);}

Try it online!
Takes input value in a, in format in i and out format in o. Returns out value in b
Minor cheat: storing result in b instead of printing to save bytes. Question doesn't disallow it.

C (clang), 100 bytes
char *a,b[10],*i,*o;f(x,y){*b=*a;for(x=1;x<8;b[x]=a[y=index(i,o[x])-i],b[x+1]=a[y+1],x+=2);puts(b);}

Try it online!

C (gcc), 181 bytes
char *a,*i,*o;c[4],x,y,z;g(x){x=x==82?0:x==71?1:x==66?2:3;}f(){a++;for(;z<2;z++){i=(z?o:i)+1;for(y=0;y<7;z?printf("%s%2X","#"+!!y,c[g(i[y])]):sscanf(a+y,"%2X",&c[g(i[y])]),y+=2);}}

Try it online!
Creates a RGBA value in c[] array based on format i, then prints in o format

Suggest char*a,b[10],*i,*o;f(x) instead of char *a,b[10],*i,*o;f(x,y) and x+=2)bcopy(a+(long)index(i,o[x])-i,b+x,2); instead of b[x++]=a[y=index(i,o[x])-i],b[x++]=a[y+1]);

Clojure 1.8, 156 bytes
(fn[c o t](reduce #(str %(val %2))""(sort-by key(reduce-kv #(let[s(clojure.string/index-of t(nth o %2))](assoc %(if(contains? % s)(inc s)s)%3)){}(vec c)))))

Ungolfed
  (fn [c o t]
    (reduce
     #(str % (val %2))
     ""
     (sort-by key
              (reduce-kv
               #(let [s (clojure.string/index-of t (nth o %2))]
                  (assoc %
                         (if (contains? % s) (inc s) s)
                         %3))
               {}
               (vec c)))))

Try it online does not have Clojure 1.8 support. Very strange!

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:
Am I a Self Number?
A self number (also called a Colombian or Devlali number) is a natural number, x, where the equation n + <digit sum of n> = x has no solutions for any natural number n. For example, 21 is not a self number, as n = 15 results in 15 + 1 + 5 = 21. On the other hand, 20 is a self number, as no n can be found which satisfies such an equality.
As this definition references the digit sum, it is base dependent. For the purposes of this challenge, we will only be considering base 10 self numbers, which are sequence A003052 in the OEIS. Binary (A010061) and base 100 (A283002) self numbers have also been calalogued.
The Challenge
Given a positive integer x as input, output a truthy value if x is a self number in base 10, and a falsey value otherwise. For clarification of truthy and falsey values, refer to this meta post on the subject.
You may write a full program or function, and input and output may be provided on any of the usual channels. Standard loopholes are, of course, banned.
This is code-golf, so the shorter your answer (in bytes) the better!
Test cases
Truthy:
1
3
5
7
9
20
31
86
154
525

Falsey:
2
4
6
8
10
15
21
50
100
500

Sandbox link
Leaderboards
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
# Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:
# Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:
# Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the leaderboard snippet:
# [><>](http://esolangs.org/wiki/Fish), 121 bytes

var QUESTION_ID=159881,OVERRIDE_USER=41020;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&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(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.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(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\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:290px;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">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

There seems to be some discussion/disagreement of valid outputs, so I think I haven't been clear on what I was intending. I've added a sentence which should hopefully clear things up, referring to this meta post. Sorry if I've caused any confusion about this!

Not to cause more confusion, but I think this discussion is relevant to why there was some confusion. Please consider this when making future challenges, as it can be difficult to post in languages that don't have if/else constructs if you use the old consensus.

@FryAmTheEggman I hadn't realised the consensus had shifted, I feel like a numpty now :/ Still, I've already added one clarification now, it seems wrong to change it again. I'll just bear it in mind for the next challenge I post. Thanks

I am not any kind of number! I am a free man!

@DavidRicherby *sends white ball after you*

Octave, 37 bytes
@(n)sum(dec2base(t=1:n,10)'-48,1)+t-n

Port of my MATL answer.
Try it online!

Java (JDK 10), 84 bytes
i->{for(int n=i;i-->1;)i|=((""+i).chars().map(x->x-48).sum()+i^n)-1>>-1;return~i<0;}

Try it online!
Explanation
i->{                                    // IntPredicate
  for(int n=i;i-->1;)                   //  for each number below n
    i|=(                                //   keep the sign of
      (""+i).chars().map(x->x-48).sum() //    sum of digits
      +i                                //    plus the number
      ^n                                //    xor n (hoping for a zero)
     )-1>>-1;                           //    changing that into a negative number if equals to zero
  return~i<0;                           //  return i>=0
}

Credits

-1 byte thanks to Kevin Cruijssen
-1 byte thanks to Nevay

-1 byte: n->{int i=n,r=0;for(;i-->0;)r=(""+i).chars().map(x->x-48).sum()+i==n?1:r;return r<1;}

84 bytes: i->{for(int n=i;i-->1;)i|=((""+i).chars().map(x->x-48).sum()+i^n)-1>>-1;return~i<0;}

Brachylog, 12 bytes
¬{⟦∋Iẹ+;I+?}

Try it online!
Explanation
¬{         }    Fails if succeeds, suceeds if fails:
  ⟦∋I             I ∈ [0, ..., Input]
    Iẹ+           The sum of the elements (i.e. digits) of I...
       ;I+?       ... with I itself results in the Input

Is false. a truthy value by any objective method in a way that true. is not? I for one don't think so, and it looks like that would be supported by the meta consensus

@Sok I added 3 uninteresting bytes to adress your concerns.

05AB1E, 8 bytes
LD€SO+ÊW

Try it online!
or as a Test suite
Explanation
L          # push range [1 ... input]
 D         # duplicate
  €S       # split each number into a list of digits
    O      # sum digit lists
     +     # add (n + digitSum(n))
      Ê    # check for inequality with input
       W   # min

J, 28, 24, 22 21 bytes
-1 byte thanks to Conor O'Brien
-2 byts thanks to ngn
$@-.(+1#.,.&.":)"+@i.

Try it online!
Explanation:
i. a list 0 .. n-1
(          )"+ for each item in the list
.,.&.": convert it to a list of digits,
1# find their sum
+ and add it to the item
$@-. exclude the list from the argument and find the shape

I realize this is an old post, but "0 i. can be "+i. (-1 byte).

@ConorO'Brien Thank you! I think I didn't know this kind of golfs back then; now I use it (when I remember :) )

-.@e. -> $@-.

@ngn Thank you, really nice!

@GalenIvanov also [:( )"+i. -> ( )"+@i.

@ngn Of course!

Octave, 49 47 44 bytes
@(x)arrayfun(@(k)k+sum(num2str(k)-48)-x,1:x)

Try it online!
Explanation:
Trying to do the operation on a range is cumbersome and long, since num2str returns a string with spaces as separators if there are more than input number. Subtracting 48 would therefore give something like: 1  -16  -16    2  -16  -16    3  -16  -16    4 for an input range 1 ... 4. Getting rid of all the -16 takes a lot of bytes.
Therefore, we'll do this with a loop using arrayfun. For each of the numbers k = 1 .. x, where x is the input, we add k and its digit sum, and subtract x. This will return an array of with the result of that operation for each of the numbers in k. If any of the numbers in the array is a zero, the number is not a self number.
For inputs 20 and 21, the outputs are:
20:  -18, -16, -14, -12, -10, -8, -6, -4, -2, -9, -7, -5, -3, -1, 1, 3, 5, 7, 9, 2
21:  -19, -17, -15, -13, -11, -9, -7, -5, -3, -10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 1, 3

There are only non-zero elements for input 20, and at least one non-zero element for input 21. That means that 20 is a self number, and 21 is not.
Octave treats an array with at least one zero as false, as can be seen in the TIO-link.

C (gcc), 70 67 65 bytes
i,r,d,j;f(n){for(r=i=n;d=j=--i;r*=d!=n)for(;j;j/=10)d+=j%10;i=r;}

Try it online!
To shave off another 2 bytes, the truthy value returned is no longer 1, but the number itself.

MATL, 11 bytes
t:tFYA!Xs+-

The output is a non-empty array, which is truthy if all its entries are non-zero, and falsy if it contains one or more zeros.
Try it online! Or verify all test cases, including truthiness/falsihood test.
Explanation
Consider input n = 10 as an example.
t       % Implicit input, n. Duplicate
        % STACK: 10, 10
:       % Range
        % STACK: 10, [1 2 3 4 5 6 7 8 9 10]
t       % Duplicate
        % STACK: 10, [1 2 3 4 5 6 7 8 9 10], [1 2 3 4 5 6 7 8 9 10]
FYA!    % Convert to base 10 digits and transpose
        % STACK: 10, [1 2 3 4 5 6 7 8 9 10], [0 0 0 0 0 0 0 0 0 1
                                              1 2 3 4 5 6 7 8 9 0]
Xs      % Sum of each column
        % STACK: 10, [1 2 3 4 5 6 7 8 9 10], [1 2 3 4 5 6 7 8 9 1]
+       % Add, element-wise
        % STACK: 10, [2 4 6 8 10 12 14 16 18 11]
-       % Subtract, element-wise
        % STACK: [8 6 4 2 0 -2 -4 -6 -8 -1]
        % Implicit display

APL (Dyalog), 14 bytes
~⊢∊⍳+(+/⍎¨∘⍕)¨∘⍳

Try it online!
How?
               ⍳   range
     (  ⍎¨∘⍕)      digits
     (+/    )      digit sums
   ⍳+              vectorized addition with the range
 ⊢∊                is the input included?
~                  negate

that's 16 bytes. to make them 15: +/⍎¨∘⍕ -> #+.⍎⍕

Jelly, 6 bytes
ḟDS+Ɗ€

For input n, this returns [n] if n is a self number, [] if not.
Try it online!
How it works
ḟDS+Ɗ€  Main link. Argument: n

     €  Call the link to the left for each k in [1, ..., n].
    Ɗ     Drei; combine the three links to the left into a monadic chain.
 D          Decimal; map k to the array of its digits in base 10.
  S         Take the sum.
   +        Add k to the sum of the k's digits.
ḟ       Filterfalse; promote n to [n], then remove all elements that appear in the
        array to the right.
        This returns [n] if the array doesn't contain n, [] if it does.

What encoding packs these six characters into only six bytes?

Jelly uses a custom code page.

Haskell, 46 bytes
f x=and[x/=n+sum[read[d]|d<-show n]|n<-[1..x]]

Try it online!

Pari/GP, 32 bytes
n->!sum(i=1,n,i+sumdigits(i)==n)

Try it online!

Scala, 44 42 bytes
x=>0 to x forall(n=>x!=(n/:s"$n")(_+_-48))

Try it online

Perl 5 -a, 34 bytes
#!/usr/bin/perl -a
say!grep{s/./$_+=$&/reg;/@F/}1..$_

Try it online!

Python 2, 70 66 Bytes
lambda x:[i for i in range(x)if i+sum([int(j)for j in`i`])==x]==[]

EDIT: -4 thanks to @user56656

in python2 you can use \i`instead ofstr(i)` to save 4 bytes.

@user56656 thanks, I didn't know about that

You can drop the [ and ] inside the sum

lambda x:[i for i in range(x)if i+sum(map(int,\i`))==x]==[]`

lambda x:all(i+sum(map(int,\i`))-x for i in range(x))`

lambda x:all(x^i+sum(map(int,\i`)) for i in range(x))` -- Borrowing from Python 3 answer above. Kinda disappointing. I didn't realize this whole time I've been reinventing what they did above. Just though i was improving this answer. xP EDIT: ...And just realized this last change didn't save anything anyway. xP

Ruby, 38 bytes
->x{(1..x).all?{|n|n+n.digits.sum!=x}}

Try it online!

Pyth, 8 bytes
!/m+sjdT

Test suite.
If swapping truthy / falsy values is allowed, then we can drop the ! and get 7 bytes instead. One of Sok's suggestions helped me golf 2 bytes.
Explanation

!/m+sjdT – Full program. Takes an input Q from STDIN, outputs either True or False.
  m      – Map over the range [0 ... Q) with a variable d.
     jdT – Convert d to base 10.
    s    – Sum.
   +     – And add the sum to d itself.
 /       – Count the occurrences of Q in the result.
!        – Negate. Implicitly output the result.

I had .AmnQ+dsjdT, I had no idea about /. I've not used Pyth properly in a long time it seems! +1

@Sok / basically counts the occurrences of an element in a list. I can also use }, which tests whether an object appears in a list, but I think that's the same byte count.

I think the S isn't required - input will be a positive integer, so having 0 in the mapping list won't be a problem? At least, it seems to work for the given test cases.

@Sok Great, you're right! I shaved off one more byte thanks to this.

How does +sjdT add sjdT to d? I've never seen anything like that

@RK. Pyth infers missing arguments based on context - in this case, + is missing a second argument while inside an m function block, so d is used. The m itself is missing a second argument too, but as its outside any function scope, Q is used. The full program is !/m+sjdTdQ.

@RK. Sok's comment explains that very well. Sorry for not replying to your comment, I must have overlooked it!

Japt -d!, 6 bytes
N¥U+ìx

Try it

Original, 8 bytes
Returns the input number for truthy or 0 for falsey. If only the empty array were falsey in JavaScript, this could be 7 bytes.
ÂNkUÇ+ìx

Try it

Explanation
             :Implicit input of integer U
   UÇ        :Generate the range [0,U) and pass each Z through a function
      ì      :  Digits of Z
       x     :  Reduce by addition
     +       :  Add to Z
  k          :Remove the elements in that array
 N           :From the array of inputs
Â            :Bitwise NOT NOT (~~), casts an empty array to 0 or a single element array to an integer

Alternative
Ç+ìxÃe¦U

Try it
             :Implicit input of integer U
Ç            :Generate the range [0,U) and pass each Z through a function
  ì          :  Digits of Z
   x         :  Reduce by addition
 +           :  Add to Z
    Ã        :End function
     e       :Every
      ¦U     :  Does not equal U

Python 3, 60, 56, 55, 54 bytes
lambda x:{x}-{n+sum(map(int,str(n)))for n in range(x)}

Try it online!
-4 using all inverse instead of any
-1 by changing != to ^ by @jonathan-allan
-1 by using sets by @ovs

Perl 6, 39 33 bytes
{!grep $_,map {$_+[+] .comb},^$_}

Try it out!
A bare block with implicit single parameter, called thus:
say {!grep $_,map {$_+[+] .comb},^$_}(500);
> False
say {!grep $_,map {$_+[+] .comb},^$_}(525);
> True

Since n + digits(n) >= n, we can just calculate the Colombian number for all the numbers up to our query value and see if any of them match. So this calculates the Colombian number for a given input:
{$_ + [+] .comb}

Which we apply to all the values up to our target:
(^$_).map({$_+[+] .comb})

But we only care whether any of them match, not what those values are, so as pointed out by @nwellenhof, we can grep:
grep $_, map {$_+[+] .comb}, ^$_

The rest is just coercion to bool and wrapping in a block.
39 bytes
{!((^$_).map({$_+[+] .comb}).any==$_)}

TIO test link provided by @Emigna
@nwellenhof pointed out that using grep would save 6 bytes!

Cool solution! You could add a TIO link for testing purposes.

{!grep $_,map {$_+[+] .comb},^$_} for 33 bytes.

29 bytes

Add++, 27 18 bytes
L,RFBDB+B]ARz€b+Ae

Try it online!

J, 20 bytes
#@-.i.+1#.10#.inv i.

Try it online!
                  i.     Range [0,n-1]
          10#.inv        To base 10
       1#.               Sum the digits
    i.+                  Plus the corresponding number
  -.                     Remove from the input, leaves an empty list if it was a self number.
#@                       An empty list is truthy, so return the length instead.

Perl 5 -apl -MList::Util=sum,all, 28 bytes
$_=all{"@F"-sum/./g,$_}1..$_

Try it online!

Pip, 18 12 bytes
aNI:_+$+_M,a

Attempt This Online!
-6 thanks to @DLosc
Explanation
aNI:_+$+_M,a  ; Full program. Input (a) on command line
         M,a  ; Map over the range from 0 to a (_)
      $+_     ;  Sum _
    _+        ;  And add this to _
aNI:          ; Is a not in this list?
              ; Implicit output

Old:
$*Y{\a!=a+$+a}M\,a  ; Full program. Input (n) on command line.
               \,a  ; Range from 1 to n
   {         }M     ; Map over this list (a):
          $+a       ;  Sum the digits of a
        a+          ;  Add to a
    \a!=            ;  And check if it's not equal to n
$*Y                 ; Get the product of this list
                    ; Implicit output

@DLosc thanks, updated

Lua, 81 bytes
for i=1,...do a=i+0(i..''):gsub('.',load'a=a+...')b=b or a==0+...end print(not b)

Try it online!
for i=1,...do
    a=i+0                            -- +0 is needed to avoid an error
    (i..''):gsub('.',load'a=a+...')  -- Sums up all the digits of i
    b=b or a==0+...                  -- Sets b to true if a equals the input
end
print(not b)

Arturo, 36 34 bytes
$->x[every? x'n->x<>+∑digits<=n]

Try it

FunStack alpha, 46 bytes
All? Minus Plus foldl ToBase 10 hook map From0

Try it at Replit!
Explanation
First, we construct a function that adds a number to its base-10 digit sum:
Plus foldl                 Left-fold second argument on addition, with first
                           argument as starting value
                     hook  Take a single argument; pass it to the above function
                           twice: first, unchanged, and second, passed through
                           the following function:
           ToBase 10       Convert to list of base-10 digits

This is a bit shorter than the alternatives:
Plus Sum ToBase 10 over hook
Sum Pair ToBase 10 compose3

Then:
                   From0  Range of integers from 0 up to input-1
           ... map        Map the above function to each
     Minus                Subtract each from the input
All?                      Are all results truthy (non-zero)?

Attache, 31 20 bytes
${0={Sum@_+_=x}~1:x}

Try it online!
{Sum@_+_=x} performs the check, ~1:x counts how many occurrences of that check are in the range from 1 to x, and 0= asserts that there are no such elements.

Attache, 30 bytes
None##`=#{_+Sum=>Digits!_}@1&`:

Try it online!
Explanation
This is a composition (##) of two functions:

None
`=#{_+Sum=>Digits!_}@1&`:

This means that whatever the second function returns, None will ensure it contains no truthy values
The second function is a fork (#) of two functions:

`=
{_+Sum=>Digits!_}@1&`:

This means that, given an input n, this fork checks for equality with n and each member of this second function.
This second function is also a composition (@) of two functions, being {_+Sum=>Digits!_}, which sums the digits of the input and adds it to the input and applies this function to each member of the range from 1 to n (1&`:).
In summary, this checks that no (None) element added to its digits ({_+Sum=>Digits!_}) from 1 to n (1&`:) is equal to (`=) n.

Retina, 24 bytes
.+
*

$.`¶$`
\d
*
D`
.\z

Try it online!
Could be 18 bytes with input given in unary, but the other Retina answer uses decimal as well, so I figured using decimal would make for a fairer comparison.
Explanation
.+
*

Convert input to unary, using _ as the unary digit.

$.`¶$`

At each position in the string (i.e. beginning, end, and between every pair of characters), insert: $.`, the length of the prefix (or the zero-indexed position of the match), ¶, a linefeed, $`, the prefix itself (i.e. a unary representation of the zero-indexed position). E.g. if the input was 3 and we'd have the unary representation ___, then this would result in:
0
_1
__2
___3
___

In other words, we get one line for each number from 0 to the input (inclusive), which holds both a unary and a decimal representation of that number.
\d
*

We convert each digit to unary, which effectively computes the digit sum on each line and adds it to the number itself (all in unary).
D`

Deduplicate lines. This doesn't actually delete duplicate lines but just clears them to empty lines. So if any number from 0 to the input plus its digit sum is equal to the input, the last line will get cleared. Otherwise, the last line remains in place.
.\z

Check whether there's still a character on the last line. We can't use $, because that also matches in front of a trailing linefeed (which is exactly where we don't want to look).

Bash + GNU Coreutils, 91 Bytes
Returns truthy or falsy.
e=1;for((i=1;i<=$1;i++));{ [ $(bc<<<`grep -o . <<<$i|tr '\n' +`$i) -eq $1 ]&&e=0; };exit $e

JavaScript (ES6), 52 51 bytes
Saved 1 byte thanks to @l4m2
Returns 0 or 1.
n=>(g=k=>k?eval([...k+'k'].join`+`)-n&&g(k-1):1)(n)

Try it online!

n=>(g=k=>k?n-eval([...k+'k'].join`+`)&&g(k-1):1)(n)

Retina, 55 bytes
.+
*
Lv`_+
_+
$&$.&
^_+
$&¶$&
\d
*
Cms`^(_+)\b.*¶\1\b
0

Try it online! Link includes test cases. Explanation:
.+
*

Convert input x to unary.
Lv`_+

Create a range from x down to 1.
_+
$&$.&

Suffix the decimal value of each n to its unary value.
^_+
$&¶$&

Make a copy of x.
\d
*

Convert each decimal digit of n to unary, thus adding the digits to the existing copy of n.
Cms`^(_+)\b.*¶\1\b

Check whether x appears in any of the results.
0

Invert the result.

Haskell, 63 58 bytes
s 0=0
s x=x`mod`10+s(x`div`10)
f n=all(\x->x+s x/=n)[1..n]

Try it online!

Kotlin, 48 bytes
x->(1..x).all{v->"$v".sumBy{it.toInt()-48}+v!=x}

Try it online!
Explanation:
(1..x)      // Range of numbers from 1 to x
.all{v->    // Function expression that checks if ALL values evaluate to tru
"$v"        // Convert the value into a string
.sumBy{it.toInt()-48} // For each character, get the ASCII char value, subtract 48 in order to get it back to the numerical value, and then sum it up
+v          // Add the original number
!=x}        // Ensure that it does not equal the input

Elixir, 66 65 bytes
fn a->!Enum.any?1..a,fn b->a==b+Enum.sum Integer.digits b end end

Try it online!

Stax, 8 bytes
Å8avj╒Éπ

Run and debug it
Explanation
ASCII equivalent:
{cE+|+x=f!
{       f     Filter [1..input] with block
 cE           Decimal digits of current value
   +|+        Sum of digits and the current value
      x=      Equals input
         !    Logical not, maps empty array to 1 and non-empty array to 0

fcE+|+x= is a Stax program that outputs all numbers whose sum of digits added to itself equals the input. For example for 101 the output would be 91 and 100, each on a separate line.
Run and debug it

Pyt, 7 bytes
ĐřĐŚ+∈¬

Try it online!
If swapping truthy/falsy values is allowed, then the ¬ at the end can be dropped for 6 bytes.
Explanation:
        Implicit input
Đ       Duplicate input
ř       Get [1,2,...,input]
Đ       Duplicate the top of the stack
Ś       Get the sum of the digits of each element in the array
+       Add the top two items on the stack element-wise
∈       Is the input in the list?
¬       Negate the top of the stack
        Implicit print

Io, 81 bytes
Io doesn't allow split("") or list-based base conversion. Therefore I need to do a terrible chain of type conversions...
method(n,Range 1 to(n)map(i,i+i asString asList map(asNumber)sum)indexOf(n)==nil)

Try it online!

Vyxal, 6 bytes
ƛ∑+;c¬

Try it Online!
Just another 6 byter. Kinda sorta ports Jelly in that it maps sum(digits) + n to the range 1..input. 5 bytes if inverted booleans are allowed.
Explained
ƛ∑+;c¬
ƛ  ;   # To each number N in the range [1, input]
 ∑     #  sum the digits of N
  +    #  and add that to N
    c  # is the input in that?
     ¬ # logical not of that

Desmos, 59 bytes
f(k)=∏_{n=1}^ksgn(n+∑_{a=0}^nmod(floor(n/10^a),10)-k)^2

Try It On Desmos!
Try It On Desmos! - Prettified

Nibbles, 5.5 5 bytes (10 nibbles)
-_.,$++`@~

Attempt This Online!
Outputs self-numbers unchanged (truthy), or an empty list (falsy) for non-self-numbers.
-_.,$++`@~      # program;
-_.,$++`@~$$    # program with implicit variables;
  .             # map over each x in
   ,$           # 1..input:
     +          #   add:
      +         #     sum of
       `@ $     #       digits of x in base
         ~      #       10
                #   to
           $    #     x
-               # now remove any of these items from
 _              # input treated as a list

Note that if reversed truthy/falsy was permitted*, the previous 5.5-byte version (-~?.,$++`@~) could have been reduced to only 4.5-bytes (?.,$++`@~).

Julia 1.0, 36 bytes
~x=all(1:x.|>n->n+sum(digits(n))!=x)

Try it online!
-1 byte thanks to MarcMush: rewrite to use all instead of !any

36 bytes Try it online!

PowerShell, 80 73 bytes
$args|%{$a=@();1..($_-1)|%{$a+=$_+(("$_"|% t*y)-join"+"|iex)};$_-notin$a}

Try it online!
Explanation
$args | % {
 $a=@()      # creates an empty array
 1..($_-1)   # loops through 1 to n-1
 | % { $a += $_ + ( ("$_" | % t*y) -join "+" | iex )}

 # adds 'currentNum + turns num into array and joins by "+" then invokes
 # expression' to the array

 $_-notin$a  # checks if n is in the array
}

-7 by changing -notcontains to -notin and param($x) to $args

Thunno 2 !, 5 bytes
æDS+=

Try it online!
or verify all test cases
Explanation
æDS+=  # Implicit input
æ      # Filter [1..input] by:
  S+   #  Add the digit sum
 D     #  To itself
    =  #  Does this equal the input?
       # Take the logical NOT
       # Implicit output

ARBLE, 51 bytes
nt(sum(range(1,n)|eq(x+sum(explode(""..x,".")),n)))

Try it online!

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


text:
Alice and Bob have a fight

Alice (A) and Bob (B) decided to have a battle.
Each combatant has 10 health.
They take turns to roll a 6 sided die for damage.
That damage is removed from their opponent's health.
In the end either Alice or Bob, will vanquish their foe.

Show me how the battle went. Outputting these codes for the actions which have taken place.
Attack
B a A
^ Combatant
  ^ Action (attack)
    ^ Target

Roll
B r 4
^ Combatant
  ^ Action (roll)
    ^ Value

Health change
A h 6
^ Combatant
  ^ Attribute (health)
    ^ Value

Win
A w
^ Combatant
  ^ Action (win)

Example output:
A a B
A r 4
B h 6
B a A
B r 6
A h 4
A a B
A r 6
B h 0
A w

Here are the rules:

Write in any language.
A single roll of the die should have an equal chance of resulting in any one of the numbers 1, 2, 3, 4, 5, or 6.
Alice always starts (Bob is chivalrous, in an old-fashioned way).
Output an action for each turn.
You must report the attack, roll, damage and win actions.
Combatants are upper case, actions are lower case.
It must not consistently produce the same result.
There must be at least one whitespace character between an output combatant, action and value.
The win action takes place when the opponent has zero or less health.
All parts of an action must be on the same line.
There should be one action per line.
Fewest bytes wins.

Have at it!

Are you sure that "It must not consistently produce the same result" is what you want? I can just hardcode two possible outputs and randomly  pick one of them.

@user202729 Curious point, it'd still have to produce the a valid output with the actions described. I'm not sure it'd be all that much shorter than writing the code.

You could specify that the number rolled each time must be uniformly distributed to a reasonable margin between 1 and 6.

@HyperNeutrino It's virtually impossible to verify, tho.

@user202729 "The distribution of dice rolls must look all-right to me" ;)

The names Alice (A) and Bob (B) are giving me flashbacks to network security class. Actor Alice (A) sends a packet to Bob (B) with key... etc...

@MagicOctopusUrn that’s them. They’re usually trying to communicate. Sadly conflict often ensues when communication breaks down.

I miss the days when we were trying to figure out how to hide our secrets from Mallory... those were simpler times...

@Bob Mallory is something of a distraction, really. It's Eve you need to watch out for.

@AJFaraday when they're locked in a you cage, I guess fighting would be the only option then.

It can be hard to verify, but at least it prevents people from hardcoding the values and claiming it has 1/0/0/0/0/0 distribution (though that would probably be dealt with by DV+VTD or a mod anyway)

@HyperNeutrino In the end I made it pretty prescriptive. Equal chances of each.

I don't understand why your first line is AaB. A is attacking B before a roll? Your spec says a roll must be first to determine how much the attack will accomplish.

@msh210 well, the important detail in code golf is that everyone takes the same challenge, but here’s the logic: - if you were playing Dungeons and Dragons, you’d say “I’m going to kick the goblin”, then you’d roll for effectiveness, then implement the result of the roll. A roll is meaningless if nobody knows what you’re rolling for.

I'm not surprised their relationship isnt going well. They've been having communication issues for years.

I want to note that Alice wins 66% of the time because she goes first.  Increasing the starting health will reduces the advantage, but player 1 still wins more often.  Don't play as Bob.  :)

@Ben First rule of all RPG combat, be the protagonist.

05AB1E, 49 bytes
"BaABr0Aha"S3ô»D„ABÂ‡[6LΩ©Tǝ¤H®-©16ǝ=®0‹#s]н…ÿ w?

Try it online!
Explanation
"BaABr0Aha"                                        # push the initial state of B
           S                                       # split to list of characters
            3ô                                     # divide into 3 parts
              »                                    # join each part on space and all on nl
               D„ABÂ‡                              # make a copy with A and B inverted
                     [                             # start a loop
                      6LΩ©                         # pick a random number in [1 ... 6]
                          Tǝ                       # insert at position 10 of the string
                            ¤H                     # get the last char of the string and
                                                   # convert from hex
                              ®-©                  # subtract the random number
                                 16ǝ=              # insert at position 16 and print
                                     ®0‹#          # if the hp is less than 0, break
                                         s         # swap the other string to the stack top
                                          ]        # end loop
                                           н…ÿ w?  # print the winner

Python 3, 131 bytes
x,y="AB"
from random import*
X=Y=10
p=print
while X>0:p(x,"a",y);d=randint(1,6);p(x,"r",d);Y-=d;p(y,"h",Y);x,y,X,Y=y,x,Y,X
p(y,"w")

Try it online!
-8 bytes thanks to officialaimm
-2 bytes thanks to ChooJeremy

predefining p=print will save you around 8 bytes.

Since y always wins at this point (And only X attacks in the loop, which is later swapped to Y), you don't need to check if y has lost. -- ChooJeremy -- From Review

@NoOneIsHere thanks for passing the message on to me :D

randint(1,6) could be replaced with id(X+Y)//3%6+1, although the distribution is not quite uniform.

@Vincent I don't see the point in bending the rules if it doesn't even help make it shorter...

Oh wait, I can remove the random import. Yeah I'd rather keep it uniform to conform to the rules though.

@HyperNeutrino Yea it wasn't a great idea, although I finally found a shorter dice roll.

Python 3, 127 bytes
This is an improvement on @HyperNeutrino answer that wouldn't fit in a comment. See the explanation below.
x,y="AB"
s=id(0)
X=Y=10
p=print
while X>0:p(x,"a",y);s=s**7%~-2**67;d=s%6+1;p(x,"r",d);Y-=d;p(y,"h",Y);x,y,X,Y=y,x,Y,X
p(y,"w")

Try it online!

An epic quest for a shorter python dice roll
TL;DR: It's possible to shave 4 bytes off the standard python dice roll by using RSA encryption.
I wanted to see if the standard python dice roll (32 bytes) could be shortened a bit:
from random import*;randint(1,6)

In particular, id(x) is quite convenient to bring some non-deterministic value into the program. My idea then was to somehow hash this value to create some actual randomness. I tried a few approaches, and one of them paid off: RSA encryption.
RSA encryption, due to its simplicity, only requires a few bytes: m**e%n. The next random value can then be created by encrypting the previous one. Assuming the (e,n) key is available, the dice roll can be written with 22 bytes:
s=id(0);s=s**e%n;s%6+1

That means we have about 10 bytes to define a valid RSA key. Here I got lucky. During my experiments, I started to use the Mersenne prime M67 only to realize later on that Mersenne made a mistake including M67 in his list. It turns out to be the product of p=193707721 and q=761838257287. I had found my modulus:
n=~-2**67

Now, the exponent and the Charmichael totient lcm(p-1,q-1) need to be coprime. Luckily again, the first prime number that do not divide the totient of n is only one digit long: 7. The dice roll can then be written using 28 bytes (4 bytes less than the standard approach):
s=id(0);s=s**7%~-2**67;s%6+1

One good thing with M67 is that the random value generated has 66 bits, which is more than the usual 64 bits RNG. Also, the use of RSA makes it possible to go back in time by decrypting the current value multiple times. Here are the encrypting and decrypting keys:
Encryption: (7,                    147573952589676412927)
Decryption: (42163986236469842263, 147573952589676412927)

I'm definitely not an expert in statistics or cryptography, so I can't really tell whether or not this RNG checks the criteria for "good randomness". I did write a small benchmark that compares the standard deviation of the occurrences of the 1 to 6 dice rolls using different RNGs. It seems like the proposed solution works just like other ones.

Impressive work! :)

C (gcc), 146 141 bytes
f(A,B,r,t,a,b){for(A=B=10;r=1+clock()%6,A*B>0;t=!t)printf("%c a %c\n%c r %u\n%c h %i\n",a=65+t,b=66-t,a,r,b,t?A-=r:(B-=r));printf("%c w",a);}

Try it online!
De-golf:
f(A,B,r,t,a,b){
    for(A=B=10; //Initialize HP
        r=1+clock()%6, // Get the number of processor cycles the program has consumed. This is relatively random, so I call it good enough.
        A*B>0;t=!t) // Flip t for change of turns
        printf("%c a %c\n%c r %u\n%c h %i\n", // Print the turn
            a=65+t,b=65+!t,a,r,b, // 65 is ASCII for 'A', 66 for 'B'
            t?A-=r:(B-=r)); // Deduct the damage.
    printf("%c w",a); // Print the winner
}

Could you save a byte by using a=65+t,b=66-t ?

A*B>0 will save you a few bytes.

A*B will save even more, but I'm kind of in a hurry atm. I'll update in the evening

Found a bug in dice seq {6,4,3,1,5}. b wins with health -4. See  TIO I changed your dice calculator to demo this bug.

@GPS Thanks, I'll patch that now.

Perl 5, 93 88 87 bytes
$A=$B=10;$_=B;${$_^=v3}-=$%=1+rand 6,say"$_ a $'
$_ r $%
$' h $$_"until//>$$_;say"$_ w"

Try it online!

JavaScript (ES6), 122 bytes
f=(h=[10,10,p=0])=>`${x='AB'[p]} a ${y='BA'[p]}
${x} r ${d=Math.random()*6+1|0}
${y} h ${H=h[p^=1]-=d}
${H<1?x+' w':f(h)}`

Try it online!

Java (JDK 10), 180 bytes
v->{var r="";int p=0,H[]={10,10},h=0;for(;H[0]*H[1]>0;)r+=r.format("%3$c a %4$c%n%3$c r %d%n%4$c h %d%n",h+=Math.random()*6-h+1,H[p]-=h,p+65,(p^=1)+65);return r+(char)(66-p)+" w";}

Try it online!
Credits

-8 bytes thanks to Kevin Cruijssen

Java 10 has var? o.Ô I really need to investigate some of the new specs soon.. Anyway, you can golf 4 bytes by changing the char-array to int-array: v->{var r="";int P[]={65,66},p=0,H[]={10,10},h=0;for(;H[0]*H[1]>0;)r+=r.format("%3$c a %4$c%n%3$c r %d%n%4$c h %d%n",h+=Math.random()*6-h+1,H[p]-=h,P[p],P[p^=1]);return r+=P[p^1]+" w";}

@KevinCruijssen Yep, Java 10 has var. Don't need to read further, it's basically the only change that's usable for us golfers. And no I can't do what you suggest: check the last line of the result: it becomes 65 w instead of A w. That's why I extracted it from the int ... statement: to golf a few bytes ;-)

@KevinCruijssen I complied a few examples here: https://codegolf.stackexchange.com/a/159922/16236

v->{var r="";int p=0,H[]={10,10},h=0;for(;H[0]*H[1]>0;)r+=r.format("%3$c a %4$c%n%3$c r %d%n%4$c h %d%n",h+=Math.random()*6-h+1,H[p]-=h,p+65,(p^=1)+65);return r+(p<1?"B":"A")+" w";} (181 bytes)

179 bytes

Java 8, 230 229 228 bytes
v->{for(int h=104,a=h,x=0,y=1,A=10,B=A,r=0,t=0,T;a<119;System.out.printf("%c %3$c %c%n",x+65,y=(a<98?t=r+=Math.random()*6-r+1:a>h?(T=x<1?A-=t:(B-=t))<0?0:T:A*B<1?-16:(x^1)+17)+48,a=a<98?114:a>h?h:A*B<1?119:97))x^=a>h|A*B<1?1:0;}

-2 bytes thanks to @ceilingcat.
Note: there is already a much shorter Java answer, so make sure to upvote his! I use a completely different approach however, so figured it was worth posting as well.
Explanation:
Try it online.
v->{                     // Method with empty unused parameter and no return-type
  for(int h=104,         //  Temp integer with unicode for 'h' to save bytes
          a=h,           //  Second part (Action)
          x=0,           //  First part
          y=1,           //  Third part
          A=10,          //  Score player A, starting at 10
          B=A,           //  Score player B, starting at 10
          r=0,           //  Random dice-roll
          t=0,           //  Previous dice-roll
          T;             //  Temp integer
      a<119              //  Loop until there is a winner:
      ;                  //    After every iteration:
       System.out.printf(//     Print:
        "%c %3$c %c,%n", //      The three parts with spaces, and a new-line
                         //      First part:
        x+65,            //       Add 65 to `x` to convert 0/1 to 65/66
                         //       (unicode values of A/B)
        (y=              //      Third part (after set-up):
           (a<98?        //       If the previous action was 'a'
             t=r+=Math.random()*6-r+1
                         //        Roll the dice, and save it in `t`
            :a>h?        //       Else-if the previous action was 'r':
             (T=x<1?     //        If the first part changed to player A:
              A-=t       //         Subtract the previous dice-roll from A
             :           //        Else:
              (B-=t))    //         Subtract the previous dice-roll from B
             <0?         //        If this score is below 0:
              0          //         Use 0
             :           //        Else:
              T          //         Use this score
           :             //       Else (the previous action was 'h'):
            A*B<1?       //        Is there a winner:
             -16         //         Change the third part to a space
            :            //        Else:
             (x^1)+17)   //         Change the third part to the other player
         +48,            //       Add 48 to convert it to unicode
         a=              //      Second part:
           a<98?         //       If the previous action was 'a':
            114          //        Change it to 'r'
           :a>h?         //       Else-if the previous action was 'r':
            h            //        Change it to 'h'
           :             //       Else (the previous action was 'h'):
            A*B<1?       //        If either score is 0:
             119         //         Use 'w'
            :            //        Else:
             97))        //         Use 'a'
    x^=                  //   First part set-up:
       a>h               //    If the previous action is 'r',
       |A*B<1?           //    or there is a winner:
         1               //     Change A→B or B→A
       :                 //    Else:
         0;}             //     A/B remains unchanged

C (gcc), 142 bytes
#define R(c,t)r=rand()%6+1,c&&printf(#c" a "#t"\n"#c" r %d\n"#t" h %d\n",r,t-=t<r?t:r),t||puts(#c" w")
f(A,B,r){for(A=B=10;A*B;R(B,A))R(A,B);}

Try it online!

Just one problem, this didn't end in a win.

@AJFaraday Oh yes, fixed.

Ruby, 122 120 96 92 91 bytes
f=->x=?A,y=?B,m=10,n=m{p [x,?a,y],[x,?r,r=1+rand(6)],[y,?h,t=n-r]
t<1?p([x,?w]):f[y,x,t,m]}

Saved 1 byte thanks to Asone Tuhid.
Try it online!

It's like I don't even know how to Ruby any more ;)

I'm afraid your alternative doesn't work, "All parts of an action must be on the same line." Although, might it be possible to make the same optimisation with a tab character?

@AJFaraday Would it be acceptable to output lines in the format ["A", "a", "B"]? If so, I have this 96-byte solution.

If they’re output one per line. That should do.

-1 byte if you replace ?(p [x,?w]): with ?p([x,?w]):

@AsoneTuhid I've tried that, but it doesn't work.

No, like this

Batch, 174 bytes
@set/aA=B=10
@set c=A
@set d=B
:g
@set/ar=%random%%%6+1,h=%d%-=r
@echo %c% a %d%
@echo %c% r %r%
@echo %d% h %h%
@if %h% gtr 0 set c=%d%&set d=%c%&goto g
@echo %c% w

Explanation: % variable references are substituted at parse time. This has two useful benefits:

%d%-=r subtracts r from the variable named by d (i.e. indirect reference)
set c=%d%&set d=%c% is simply a straight swap.

PHP 7.1: 159 bytes
<?php $A=$B=10;$t='AB';while($A>0&&$B>0){$a=$t[0];$b=$t[1];$d=rand(1,6);$$b-=$d;echo"$a a $b\n$a r $d\n$b h {$$b}\n";$t=strrev($t);}echo($A>0?'A':'B')." w\n";

Run it in the browser here!
PHP 5.6: 156 bytes
<?php $A=$B=10;$t='AB';while($A>0&&$B>0){list($a,$b)=$t;$d=rand(1,6);$$b-=$d;echo"$a a $b\n$a r $d\n$b h {$$b}\n";$t=strrev($t);}echo($A>0?'A':'B')." w\n";

Run it in the browser here!
Here's what the PHP 5.6 solution looks like with formatting and comments:
<?php
// Initialize both HP counters
$A = $B = 10;

// Set the turn order as a string (which 5.6 allows to be unpacked into a list)
$t = 'AB';

// Run this loop as long as both players have HP
while ($A > 0 && $B > 0) {
    // Unpack the turn string into $a and $b variables; on the first run, $a = 'A'
    // and $b = 'B'. This is no longer possible in PHP 7.0, so the PHP 7.0
    // solution needed to use an array instead.
    list($a, $b) = $t;

    // Set damage to a random number between 1 and 6
    $d = rand(1, 6);

    // Subtract the damage from the referenced value $b. On the first turn, this
    // is 'B', so this ends up subtracting $d from $B. Next turn, $b will be 'A',
    // so it'll subtract $d from $A
    $$b -= $d;

    // Echo the string (interpolated values)
    echo "$a a $b\n$a r $d\n$b h {$$b}\n";

    // Reverse the turn order string ('AB' becomes 'BA', which will affect the
    // call to list in the first line of the while-loop)
    $t = strrev($t);
}

// Someone's run out of HP; figure out whom by figuring out who still has HP
echo ($A > 0 ? 'A' : 'B') . " w\n";

F#, 238 235 bytes
I thought I was doing well, but you've all far outclassed me!
let p=printfn
let mutable A=10
let mutable B=A
let x h a d=
 p"%s a %s"a d
 let i=(new System.Random()).Next(1,7)
 let j=h-i
 p"%s r %i"a i
 p"%s h %i"d j
 if j<=0 then p"%s w"a
 j
while A*B>0 do
 B<-x B"A""B"
 if B>0 then A<-x A"B""A"

Try it online!
Thanks to Rogem for the brilliant advice to use A*B>0 instead of A>0&&B>0 (takes off 3 bytes).
Thank you also to officialaimm, whose hint about predefining printf in the Python answer helped me shave a few bytes off too.

An advice that I got from @OlivierGregoire: A*B>0 will save you a couple more.

That is absolutely brilliant. Love it. Thank you very much!

Haskell, 204 bytes
My attempt with Haskell, I wasn't able to get it more competitive unfortunately
import System.Random
main=getStdGen>>= \g->putStr$q(randomRs(1,6)g)10(10::Int)"A ""B "
(!)=(++)
l="\n"
q(x:z)a b p o=p!"a "!o!l!p!"r "!show x!l!o!"h "!show n!l!if n<1then p!"w"else q z n a o p where n=b-x

Try it online!
Explanations:

import System.Random  --import random module
main=                        --main function, program entry point
 getStdGen                   -- get the global random number generator
   >>= \g->                  --using the random generator g
       putStr $ q            --print the result of function q, passing in ..
          (randomRs (1,6) g) --an infinite list of random numbers, 1 to 6 generated by g
           10 (10::Int)      --the starting health of both players,
                             --type annotation sadly seems to be required
           "A " "B "         --The names of the players,
                             --with an extra space for formatting
(!)=(++) --define the operator ! for list (String) concatenation,
         -- we do this a lot so we save a bit by having a one byte operator
l="\n"   -- define l as the newline character

q      --define function q
 (x:z) --our list of random numbers, split into the next number (x) and the rest (z)
 a     -- the health of the active player
 b     -- the health of the player getting attacked
 p     -- the name of the active player
 o     -- the name of the player getting attacked
=
  p!"a "!o!l --create the attack action string with a newline
 !p!"r "!show x!l -- append the roll action
 !o!"h "!show n!l -- append the health remaining
 !           -- append the result of the following if
  if n<1     -- if the player being attacked has been defeated
  then p!"w" -- append the win string for the active player
  else q z n a o p  --otherwise append the result of calling q again with
                    --rest of the random numbers, and the active players swapped
  where n=b-x -- define the attacked player's new health n
              -- their current health b - the random roll x

You could have a look at our Tips for golfing in Haskell. E.g. where m=b-x can be put into a guard: |m<-b-x=.

You can lose the lambda and one set of parentheses by rearranging some parameters: main=putStr=<<q"A "10"B "10.randomRs(1,6::Int)<$>getStdGen. You can also use a list and concat it to get rid of redefining (++). The last where doesn't seem to be beneficial to just using b-x everywhere.

Julia 0.6, 175 bytes
p=println()
f(l="AB",h=[10,10],a=1)=(while min(h...)>0;d=3-a;p(l[a]," a ",l[d]);r=rand(1:6);h[d]-=r;p(l[a]," r ",r);p(l[d]," h ",max(h[d],0));a=d;end;p(l[findmax(h)[2]]," w"))

Try it online!
Long, ungolfed version:
function status(player, health)
    println("$player h $(max(0,health))")
end

function roll(player)
    x = rand(1:6)
    println("$player r $x")
    x
end

function play()
    players = ["A","B"]
    healths = [10, 10]
    attacker = 1

    while min(healths...) > 0
        println("$(players[attacker]) a $(players[3-attacker])")
        healths[3-attacker]-=roll(players[attacker])
        status(players[3-attacker], healths[3-attacker])

        attacker = 3 - attacker
    end

    winner = findmax(healths)[2]
    println("$(players[winner]) w")
end

There doesn’t seem to be any output in your TIO link.

Yeah I don't know why tio doesn't like it. It works fine on my machine. I'll look into it if I have time.

VBA, 222 185 179 Bytes
This recursive solution involves 3 subs

g is the game start that kicks off the first turn
t is called for each turn.  It uses recursion.
p is shorter than Debug.Print when used more than 3 times (only 4 in this solution) Edit: Now that I learned that Debug.? is an acceptable alternative to Debug.Print, Debug.?x is shorter than calling a Sub to print.

Sub g()
t "A",10,"B",10
End Sub
Sub t(i,j,x,h)
d=Int(Rnd()*6)+1
Debug.?i &" a "&x
Debug.?i &" r "&d
h=h-d
If h<1Then
Debug.?i &" w"
Else
Debug.?x &" h "&h
t x,h,i,j
End If
End Sub

This was a fun challenge. If you know of an online interpreter like TIO for VB6/VBScript/VBA please leave a comment.  Then I can post a link to a working solution.
If you want to test this code and have Microsoft Excel, Word, Access, or Outlook installed (Windows only), press Alt+F11 to open the VBA IDE. Insert a new code module (Alt+I,M) and clear out Option Explicit. Then paste in the code and press F5 to run it. The results should appear in the Immediate Window (press Ctrl+G if you don't see it).
Edit 1:  Removed whitespace that the VBA editor will automatically add back in.  Reduced by 37 bytes
Edit 2:  Removed Sub p()* to save 6 bytes after learning Debug.? is an acceptable alternative to Debug.Print.  Calling a Sub to handle Debug.? only saves bytes after more than six calls.


text:
Limit your numbers by your runs
Self-limiting lists
Consider a nonempty list L containing nonnegative integers.
A run in L is a contiguous sublist of equal elements, which cannot be made longer.
For example, the runs of [0,0,1,1,3,3,3,2,1,1] are [0,0], [1,1], [3,3,3], [2], [1,1].
The list L is self-limiting if for each integer N ≥ 1, the number of occurrences of N is less than or equal to the number of runs of N-1.
The above list is not self-limiting, because there are 4 occurrences of 1, but only one run of 0s.
Here's an example of a self-limiting list: [0,0,3,4,1,0,2,1,1,0,2,1,0,0,0,1,0].
It has

5 runs of 0 and 5 occurrences of 1,
4 runs of 1 and 2 occurrences of 2,
2 runs of 2 and 1 occurrence of 3,
1 run of 3 and 1 occurrence of 4,
1 run of 4 and no occurrences of 5,
no occurrences of other integers.

The task
Your task is to decide whether a list is self-limiting.
More explicitly, your input shall be a nonempty list of nonnegative integers.
If the list is self-limiting, your output shall be truthy; otherwise, it shall be falsy.
Input and output can be in any reasonable format.
The lowest byte count in each programming language is the winner.
Standard code-golf rules apply.
Test cases
Truthy instances:
[0]
[1,0]
[0,1,1,0,2]
[3,1,1,0,0,2,0,0]
[5,0,4,1,3,0,2,2,0,1,1,1,0]
[0,0,1,1,0,0,1,1,0,0,2,2,0,0]
[6,0,0,0,2,2,1,0,5,0,3,4,0,1,1,1]
[5,0,1,0,0,0,0,4,0,3,1,1,1,2,2,0,0,0,0,0]
[4,5,1,3,2,0,5,2,0,3,0,1,0,1,0,0,0,1,0,0,1,0,3,4,4,0,2,6,0,2,6]
[0,4,1,3,10,6,0,1,3,7,9,5,5,0,7,4,2,2,5,0,1,3,8,8,11,0,0,6,2,1,1,2,0,4]

Falsy instances:
[2]
[1,1,0]
[0,0,1,1,1,0,0,2]
[0,1,0,1,1,2,2,3,0,0,4,6]
[1,1,2,1,2,0,2,0,3,0,0,2,2,1,2,3,2,0,1,1,1,0,0,3,3,0]
[3,4,1,0,0,0,5,5,0,2,2,0,0,0,0,0,2,0,1,1,0,4,3,5,4,3]
[1,0,0,0,2,5,3,1,1,0,3,3,1,3,5,4,0,4,0,0,2,0,2,1,1,5,0,0,2,4,4,0,2,0,1,4,4,2,3,3,5,3,4,0,2,0,5]
[4,3,1,0,0,4,6,6,1,0,1,2,1,3,0,1,0,2,0,3,4,0,2,1,1,3,0,2,2,2,0,5,5,0,5,2,5,5,0,4,3,2,3,1,1,3,5,1,4,1,6,2,6,2,4,0,4,0,4,5,3,3,0,0,6,1,0,0,0,6,2,1,0,1,2,6,2,4]
[5,1,1,1,0,2,0,6,1,0,2,1,2,2,5,3,1,0,0,0,3,2,3,0,1,1,0,1,0,1,1,2,0,6,4,1,2,1,1,6,4,1,2,2,4,0,1,2,2,1,3,0,1,2,0,0,0,2,0,2,2,0,1,0,0,1,3,0,0,0,6,2,0,1,0,1,2,1,1,1,0,4,0,0,5,2,0,0,0,4,1,2,2,2,2,0,5,3,2,4,5,0,5]

Not to be a bother, but please consider using one of the approaches from this meta discussion instead of truthy/falsy, as truthiness isn't a property of more than a couple languages used here often.

@LeakyNun Yes, otherwise the condition fails for those N for which N-1 is not present.

@Mr.Xcoder There's [2] too, but such cases should be falsy, yeah.

@FryAmTheEggman I hadn't seen that discussion, thanks for linking it. I'll keep this challenge as it is though, because I want to process the approaches discussed there for a while.

Sure, but I would like to keep the comment there, since I feel like a lot of people have missed it. It matters quite a lot, at least for me, in posting in languages like Retina.

Perl 6, 29 bytes
{bag(.grep(?*)X-1)⊆.squish}

Try it online!
Very nice challenge for Perl 6. Uses the subset operator on Bags (integer-weighted sets). Explanation:
{
    bag(           # Create bag of
        .grep(?*)  # non-zero elements,
        X- 1       # decremented by one.
    )
    ⊆              # Subset test.
    .squish        # "squish" removes repeated elements in each run.
                   # The result is implicitly converted to a bag
                   # counting the number of runs.
}

Beautiful. I saw the Bag+subset approach but stuck on the thing to compare to.

Perl 5 -p, 49 48 44 bytes
#!/usr/bin/perl -p
$z[$_+1]+=!/^$o$/;$z[$o=$_]--}{$_="@z"!~/.-/

Try it online!

JavaScript (ES6), 92 89 bytes
a=>a.map(n=>g(~n,n!=p&&g(p=n)),c=[j=0],p=g=n=>c[n]=-~c[n])&&!c.some((n,i)=>i-j++|n<c[~j])

Try it online!
How?
The array c[ ] is used to store both the number of runs and the number of integer occurrences. Runs are stored at non-negative indices and integer occurrences are stored at 1's-complement indices (c[-1] = number of 0's, c[-2] = number of 1's, etc.).
Negative indices are actually saved as properties of the underlying array object and .some() does not iterate over them.
a =>                        // given the input array a[]
  a.map(n =>                // for each value n in a[]:
    g(                      //   update c[]:
      ~n,                   //     increment c[~n] (# of integer occurrences)
      n != p && g(p = n)    //     if n != p, set p to n and increment c[n] (# of runs)
    ),                      //   end of c[] update
    c = [j = 0],            //   start with c = [0] and j = 0 (used later)
    p =                     //   initialize p to a non-numeric value
    g = n => c[n] = -~c[n]  //   g = helper function to increment c[n]
  )                         // end of map()
  && !c.some((n, i) =>      // for each value n at position i in c[]:
    i - j++ |               //   make sure that i == j++
    n < c[~j]               //   and n is greater than or equal to c[~j]
  )                         // end of some()

Jelly, 10 bytes
œ-ŒgḢ€‘ƊS¬

Try it online!
How it works
œ-ŒgḢ€‘ƊS¬  Main link. Argument: A (array)

       Ɗ    Drei; group the three links to the left into a monadic chain.
  Œg          Group consecutive, identical elements of A into subarrays.
    Ḣ€        Head each; pop the first element of each run.
      ‘       Increment the extracted integers.
            The resulting array contains n repeated once for each run of (n-1)'s.
œ-          Perform multiset subtraction, removing one occurrence of n for each
            run of (n-1)'s.
       S    Take the sum. If only 0's remain, the sum will be 0.
        ¬   Take the logical NOT, mapping 0 to 1 and positive integers to 0.

Jelly, 19 bytes
ŒgḢ€ċÐ€ṀḶ$<ċÐ€ṀR$$Ẹ

Try it online!

Python 3, 94 bytes
lambda a:all(sum(1for x,y in zip(a,a[1:]+[-1])if x==j!=y)>=a.count(j+1)for j in range(max(a)))

Try it online!

sum(1for ... if x==j!=y) => sum(x==j!=y for ...).

@Mr.Xcoder oh ofc. thanks!

Jelly, 17 bytes
ŒgḢ€ċ’}<ċ
çÐ€x⁸ẸṆ

Try it online!

Japt, 21 bytes
x o e@ó¥ mÌè¥X ¨Uè¥XÄ

Test it online!

Stax, 13 9 bytes
Dennis found a much better algorithm.  I've shamelessly ported it to stax.
ä╨²@┬↕OR♣

Run and debug it online
Unpacked, ungolfed, and commented, this is what it looks like.
c   copy input
:g  get run elements
{^m increment each
|-  multiset-subtract from original input
|M! get maximum from result, and apply logical not

Run this one
Old Answer:
║Ä|╤#╫∩▼cëózü

Run and debug it
It iterates over the input and checks the conditions:

Is the element > 0?
Is occurrences(element) >= runs(element - 1)?

If either of these conditions are true for an element, then that element is compliant.  Iff all elements are compliant, the result is 1.
Here's the unpacked, ungolfed, commented representation of the same program.
O           push 1 under the input
F           iterate over the input using the rest of program
  |c        skip this iteration of the value is 0
  x#        number of occurrences of this value in input (a)
  x:g _v#   number of runs of (current-1) in input (b)
  >!        not (a > b); this will be truthy iff this element is compliant
  *         multiply with running result

Run this one

Haskell, 80 bytes
import Data.List
o#l=[1|x<-l,x==o]
f x=and[(i-1)#(head<$>group x)>=i#x|i<-x,i>0]

Try it online!