title: An abundance of integers!

text:
# Question
Title: An abundance of integers!
An *Abundant number* is any number where the sum of its proper divisors is greater than the original number. For example, the proper divisors of 12 are:

```
1, 2, 3, 4, 6

```

And summing these results in 16. Since 16 is larger than 12, 12 is abundant. Note that this does *not* include "Perfect numbers", e.g. numbers that are *equal* to the sum of its proper divisors, such as 6 and 28.

Your task for today is to write a program or function that determines if a number is abundant or not. Your program should take a single integer as input, and output a truthy/falsy value depending on whether it is abundant or not. You can assume that the input will always be valid and greater than 0, so for bad inputs, undefined behavior is fine.

You may take your input and output in any reasonable format, for example STDIN/STDOUT, files, or arguments/return values would all be acceptable.

For reference, here are the abundant numbers up to 100:

```
12,
18,
20,
24,
30,
36,
40,
42,
48,
54,
56,
60,
66,
70,
72,
78,
80,
84,
88,
90,
96,
100

```

And more can be found on A005101

Since this is , standard loopholes are denied, and try to write the shortest possible code you can in whichever language you happen to choose!

# Answer
> 47 votes
# Regex (ECMAScript), ~~1085~~ ~~855~~ ~~597~~ ~~536~~ ~~511~~ ~~508~~ 504 bytes

Matching abundant numbers in ECMAScript regex is an entirely different beast than doing so in practically any other regex flavor. The lack of forward/nested backreferences or recursion means that it is impossible to directly count or keep a running total of anything. The lack of lookbehind makes it often a challenge even to have enough space to work in.

Many problems must be approached from an entirely different perspective, and you'll be wondering if they're solvable at all. It forces you to cast a much wider net in finding which mathematical properties of the numbers you're working with might be able to be used to make a particular problem solvable.

Back in March-April 2014 I constructed a solution to this problem in ECMAScript regex. At first I had every reason to suspect the problem was completely impossible, but then the mathematician teukon sketched an idea that made an encouraging case for making it look solvable after all – but he made it clear he had no intention of constructing the regex (he had competed/cooperated with my on constructing/golfing previous regexes, but reached his limit by this point and was content to restrict his further contributions to theorizing).

Solving unary mathematical problems in ECMAScript regex has been a fascinating journey for me, so in the past I put spoiler warnings in this post and others like it – in case others, especially those with an interest in number theory, wanted to take a crack at independently solving things like generalized multiplication. I am now removing the spoiler warnings though; they did not prove to be constructive.

Before posting my ECMAScript regex, I thought it would be interesting to analyze Martin Ender's .NET pure regex solution, `^(?!(1(?<=(?=(?(\3+$)((?>\2?)\3)))^(1+)))*1$)`. It turns out to be very straightforward to understand that regex, and it is elegant in its simplicity. To demonstrate the contrast between our solutions, here is a commented and pretty-printed (but unmodified) version of his regex:

```
# For the purpose of these comments, the input number will be referred to as N.

^(?!                  # Attempt to add up all the divisors. Since this is a regex and we
                      # can only work within the available space of the input, that means
                      # if the sum of the divisors is greater than N, the attempt to add
                      # all the divisors will fail at some point, causing this negative
                      # lookahead to succeed, showing that N is an abundant number.

  (1                  # Cycle through all values of tail that are less than N, testing
                      # each one to see if it is a divisor of N.

    (?<=              # Temporarily go back to the start so we can directly operate both
                      # on N and the potential divisor. This requires variable-length
                      # lookbehind, a .NET feature – even though this special case of
                      # going back to the start, if done left-to-right, would actually be
                      # very easy to implement even in a regex flavour that has no
                      # lookbehind to begin with. But .NET evaluates lookbehinds right
                      # to left, so please read these comments in the order indicated,
                      # from [Step 1] to [Step 7]. The comment applying to entering the
                      # lookahead group, [Step 2], is shown on its closing parenthesis.
      (?=             # [Step 3] Since we're now in a lookahead, evaluation is left to
                      #          right.
        (?(\3+$)      # [Step 4] If \3 is a divisor of N, then...
          (           # [Step 5] Add it to \2, the running total sum of divisors:
                      #          \2 = \2 + \3
            (?>\2?)   # [Step 6] Since \2 is a nested backref, it will fail to match on
                      #          the first iteration. The "?" accounts for this, making
                      #          it add zero to itself on the first iteration. This must
                      #          be done before adding \3, to ensure there is enough room
                      #          for the "?" not to cause the match to become zero-length
                      #          even if \2 has a value.
            \3        # [Step 7] Iff we run out of space here, i.e. iff the sum would
                      #          exceed N at this point, the match will fail, making the
                      #          negative lookahead succeed, showing that we have an
                      #          abundant number.
          )

        )
      )               # [Step 2] Enter a lookahead that is anchored to the start due to
                      #          having a "^" immediately to its right. The regex would
                      #          still work if the "^" were moved to the left of the
                      #          lookahead, but would be slightly slower, because the
                      #          engine would do some spurious matching before hitting
                      #          the "^" and backtracking.
      ^(1+)           # [Step 1] \3 = number to test for being a potential divisor – its
                      #               right-side-end is at the point where the lookbehind
                      #               started, and thus \3 cycles through all values from
                      #               1 to N-1.
    )
  )*1$                # Exclude N itself from being considered as a potential divisor,
                      # because if we included it, the test for proper abundance would be
                      # the sum of divisors exceeding 2*N. We don't have enough space for
                      # that, so instead what would happen if we did not exclude N as a
                      # divisor would be testing for "half-abundance", i.e. the sum of
                      # all divisors other than N exceeding N/2. By excluding N as a
                      # divisor we can let our threshold for abundance be the sum of
                      # divisors exceeding N.
)

```

Try the .NET regex online

Now, back to my ECMAScript regex. First, here it is in raw, whitespace-and-comment-free format:

`^(?=(((?=(xx+?)\3+$)(x+)\4*(?=\4$))+(?!\3+$)(?=(xx(x*?))\5*$)x)(x+))(?=\1(x(x*))(?=\8*$)\6\9+$)(?=(.*)((?=\8*$)\5\9+$))(?=(x*?)(?=(x\11)+$)(?=\12\10|(x))(x(x*))(?=\15*$)(?=\11+$)\11\16+$)(?=(x(x*))(?=\17*$)\7\18+$)((?=(x*?(?=\17+$)(?=\17+?(?=((xx(x*))(?=\18+$)\22*$))(x+).*(?=\17$)\24*(?=\24$)(?!(xx+)\25*(?!\22+$)\25$)\22+$)((?=(x\7)+$)\15{2}\14|)))(?=.*(?=\24)x(x(x*))(?=\28*$)\23\29*$)(?=.*(x((?=\28*$)\22\29+$)))(.*(?!\30)\20|(?=.*?(?!x\20)(?=\30*$)(x(x*))(?=\33*$)(?=\31+$)\31\34+$).*(?=\33\21$)))+$`

(change `\14` to `\14?` for compatibility with PCRE, .NET, and practically every other regex flavour that's not ECMAScript)

Try it online!
Try it online! (faster, 537 byte version of the regex)

And now a brief summary of the story behind it.

At first it was very non-obvious, to me at least, that it was even possible to match primes in the general case. And after solving that, the same applied to powers of 2. And then powers of composite numbers. And then perfect squares. And even after solving that, doing generalized multiplication seemed impossible at first.

In an ECMAScript loop, you can only keep track of one changing number; that number cannot exceed the input, and has to decrease at every step. My first working regex for matching correct multiplication statements A\*B=C was 913 bytes, and worked by factoring A, B, and C into their prime powers – for each prime factor, repeatedly divide the pair of prime power factors of A and C by their prime base until the one corresponding to A reaches 1; the one corresponding to C is then compared to the prime power factor of B. These two powers of the same prime were "multiplexed" into a single number by adding them together; this would always be unambiguously separable on each subsequent iteration of the loop, for the same reason that positional numeral systems work.

We got multiplication down to 50 bytes using a completely different algorithm (which teukon and I were able to arrive at independently, though it took him only a few hours and he went straight to it, whereas it took me a couple days even after it was brought to my attention that a short method existed): for A≥B, A\*B=C if and only if C is the smallest number which satisfies C≡0 mod A and C≡B mod A-1. (Conveniently, the exception of A=1 needs no special handling in regex, where 0%0=0 yields a match.) I just can't get over how neat it is that such an elegant way of doing multiplication exists in such a minimal regex flavour. (And the requirement of A≥B can be replaced with a requirement that A and B are prime powers of the same power. For the case of A≥B, this can be proven using the Chinese remainder theorem.) See this post for a more in-depth explanation.

If it had turned out that there was no simpler algorithm for multiplication, the abundant number regex would probably be on the order of ten thousand bytes or so (even taking into account that I golfed the 913 byte algorithm down to 651 bytes). It does lots of multiplication and division, and ECMAScript regex has no subroutines.

I started working on the abundant number problem tangentially in 23 March 2014, by constructing a solution for what seemed at the time to be a sub-problem of this: Identifying the prime factor of highest multiplicity, so that it could be divided out of N at the start, leaving room to do some necessary calculations. At the time this seemed to be a promising route to take. (My initial solution ended up being quite large at 326 bytes, later golfed down to 185 bytes.) But the rest of the method teukon sketched would have been extremely complicated, so as it turned out, I took a rather different route. It proved to be sufficient to divide out the largest prime power factor of N corresponding to the largest prime factor on N; doing this for the prime of highest multiplicity would have added needless complexity and length to the regex.

What remained was treating the sum of divisors as a product of sums instead of a straight sum. As explained by teukon on 14 March 2014:

> We're given a number n = p0a0p1a1...pk-1ak-1. We want to handle the sum of the factors of n, which is (1 + p0 \+ p02 \+ ... + p0a0)(1 + p1 \+ p12 \+ ... + p1a1)...(1 + pk-1 \+ pk-12 \+ ... + pk-1ak-1).

It blew my mind to see this. I had never thought of factoring the aliquot sum in that way, and it was this formula more than anything else that made the solvability of abundant number matching in ECMAScript regex look plausible.

In the end, instead of testing for a result of addition or multiplication exceeding N, or testing that such a result pre-divided by M exceeds N/M, I went with testing if a result of division is less than 1. I arrived at the first working version on 7 April 2014.

The full history of my golf optimizations of this regex is on github. At a certain point one optimization ended up making the regex much slower, so from that point on I maintained two versions. They are:

regex for matching abundant numbers.txt
regex for matching abundant numbers - shortest.txt

These regexes are fully compatible with both ECMAScript and PCRE, but a recent optimization involved using a potentially non-participating capture group `\14`, so by dropping PCRE compatibility and changing `\14?` to `\14` they can both be reduced by 1 byte.

Here is the smallest version, with that optimization applied (making it ECMAScript-only), reformatted to fit in a StackExchange code block with (mostly) no horizontal scrolling needed:

```
# Match abundant numbers in the domain ^x*$ using only the ECMAScript subset of regex
# functionality. For the purposes of these comments, the input number = N.
^
# Capture the largest prime factor of N, and the largest power of that factor that is
# also a factor of N. Note that the algorithm used will fail if N itself is a prime
# power, but that's fine, because prime powers are never abundant.
(?=
  (                      # \1 = tool to make tail = Z-1
    (                    # Repeatedly divide current number by its smallest factor
      (?=(xx+?)\3+$)
      (x+)\4*(?=\4$)
    )+                   # A "+" is intentionally used instead of a "*", to fail if N
                         #  is prime. This saves the rest of the regex from having to
                         #  do needless work, because prime numbers are never abundant.
    (?!\3+$)             # Require that the last factor divided out is a different prime.
    (?=(xx(x*?))\5*$)    # \5 = the largest prime factor of N; \6 = \5-2
    x                    # An extra 1 so that the tool \1 can make tail = Z-1 instead of just Z
  )
  (x+)                   # Z = the largest power of \5 that is a factor of N; \7 = Z-1
)
# We want to capture Z + Z/\5 + Z/\5^2 + ... + \5^2 + \5 + 1 = (Z * \5 - 1) / (\5 - 1),
# but in case Z * \5 > N we need to calculate it as (Z - 1) / (\5 - 1) * \5 + 1.
# The following division will fail if Z == N, but that's fine, because no prime power is
# abundant.
(?=
  \1                     # tail = (Z - 1)
  (x(x*))                # \8   = (Z - 1) / (\5 - 1); \9 = \8-1
  # It is guaranteed that either \8 > \5-1 or \8 == 1, which allows the following
  # division-by-multiplication to work.
  (?=\8*$)
  \6\9+$
)
(?=
  (.*)                   # \10 = tool to compare against \11
  (                      # \11 = \8 * \5  =  (Z - 1) / (\5 - 1) * \5; later, \13 = \11+1
    (?=\8*$)
    \5\9+$
  )
)
# Calculate Q = \15{2} + Q_R = floor(2 * N / \13). Since we don't have space for 2*N, we
# need to calculate N / \13 first, including the fractional part (i.e. the remainder),
# and then multiply the result, including the fractional part, by 2.
(?=
  (x*?)(?=(x\11)+$)      # \12 = N % \13; \13 = \11 + 1
  (?=\12\10|(x))         # \14 = Q_R = floor(\12 * 2 / \13)
                         #     = +1 carry if \12 * 2 > \11, or NPCG otherwise
  (x(x*))                # \15 = N / \13; \16 = \15-1
  (?=\15*$)
  (?=\11+$)              # must match if \15 <  \13; otherwise doesn't matter
  \11\16+$               # must match if \15 >= \13; otherwise doesn't matter
)
# Calculate \17 = N / Z. The division by Z can be done quite simply, because the divisor
# is a prime power.
(?=
  (x(x*))                # \17 = N / Z; \18 = \17-1
  (?=\17*$)
  \7\18+$
)
# Seed a loop which will start with Q and divide it by (P^(K+1)-1)/(P-1) for every P^K
# that is a factor of \17. The state is encoded as \17 * P + R, where the initial value
# of R is Q, and P is the last prime factor of N to have been already processed.
#
# However, since the initial R would be larger than \17 (and for that matter there would
# be no room for any nonzero R since with the initial value of P, it is possible for
# \17 * P to equal N), treat it as a special case, and let the initial value of R be 0,
# signalling the first iteration to pretend R=Q. This way we can avoid having to divide Q
# and \17 again outside the loop.
#
# While we're at it, there's really no reason to do anything to seed this loop. To seed
# it with an initial value of P=\5, we'd have to do some multiplication. If we don't do
# anything to seed it, it will decode P=Z. That is wrong, but harmless, since the next
# lower prime that \17 is divisible by will still be the same, as \5 cannot be a factor
# of \17.

# Start the loop.
(
  (?=
    (                    # \20 = actual value of R
      x*?(?=\17+$)       # move forward by directly decoded value of R, which can be zero
      # The division by \17 can be done quite simply, because it is known that
      # the quotient is prime.
      (?=
        \17+?            # tail = \17 * (a prime which divides into \17)
        (?=
          (              # \21 = encoded value for next loop iteration
            (xx(x*))     # \22 = decoded value of next smaller P; \23 = (\22-1)-1
            (?=\18+$)    # iff \22 > \17, this can have a false positive, but never a false negative
            \22*$        # iff \22 < \17, this can have a false positive, but never a false negative
          )
        )
        # Find the largest power of \22 that is a factor of \17, while also asserting
        # that \22 is prime.
        (x+)             # \24 = the largest power of \22 that is a factor of \17
        .*(?=\17$)
        \24*(?=\24$)
        (?!
          (xx+)\25*
          (?!\22+$)
          \25$
        )
        \22+$
      )
      (
        (?=(x\7)+$)      # True iff this is the first iteration of the loop.
        \15{2}\14        # Potentially unset capture, and thus dependent on ECMAScript
                         # behavior. Change "\14" to "\14?" for compatibility with non-
                         # ECMAScript engines, so that it will act as an empty capture
                         # with engines in which unset backrefs always fail to match.
      |
      )
    )
  )
  # Calculate \30 = (\24 - 1) / (\22 - 1) * \22 + 1
  (?=
    .*(?=\24)x           # tail = \24 - 1
    (x(x*))              # \28 = (\24 - 1) / (\22 - 1); \29 = \28-1
    (?=\28*$)
    \23\29*$
  )
  (?=
    .*(x(                # \30 = 1 + \28 * \22 = (\28 - 1) / (\22 - 1) * \22 + 1; \31 = \30-1
      (?=\28*$)
      \22\29+$
    ))
  )
  # Calculate \33 = floor(\20 / \30)
  (
    .*(?!\30)\20         # if dividing \20 / \30 would result in a number less than 1,
                         # then N is abundant and we can exit the loop successfully
  |
    (?=
      .*?(?!x\20)(?=\30*$)
      (x(x*))            # \33 = \20 / \30; \34 = \33-1
      (?=\33*$)
      (?=\31+$)          # must match if \33 <  \30; otherwise doesn't matter
      \31\34+$           # must match if \33 >= \30; otherwise doesn't matter
    )
    # Encode the state for the next iteration of the loop, as \17 * \22 + \33
    .*(?=\33\21$)
  )
)+$

```

# Answer
> 31 votes
# Python 2, ~~41~~ 40 bytes

```
n=k=j=input()
while~k<0:j-=1;k-=j>>n%j*n

```

Output is via exit code, so **0** is truthy and **1** is falsy.

Try it online!

### How it works

After setting all of **n**, **k**, and **j** to the input from STDIN, we enter the *while* loop. Said loop will break as soon as **-k - 1 = ~k ≥ 0**, i.e., **k ≤ -1** / **k \< 0**.

In each iteration, we first decrement **j** to consider only proper divisors of **n**. If **j** is a divisor of **n**, `n%j` yields **0** and **j \>\> n%j\*n = j/20 = j** gets subtracted from **k**. However, if **j** does *not* divide **n**, `n%j` is positive, so `n%j*n` is at least **n \> log2 j** and **j \>\> n%j\*n = j / 2n%j\*n = 0** is subtracted from **k**.

For abundant numbers, **k** will reach a negative value before or when **j** becomes **1**, since the sum of **n**'s proper divisors is strictly greater than **n**. In this case, we break out of the *while* loop and the program finishes normally.

However, if **n** is *not* abundant, **j** eventually reaches **0**. In this case, `n%j` throws a *ZeroDivisionError* and the program exits with an error.

# Answer
> 13 votes
# Brachylog, 5 bytes

```
fk+>?

```

Try it online!

### Explanation

```
f           Factors
 k          Knife: remove the last one (the input itself)
  +         Sum
   >?       Stricly greater than the Input

```

# Answer
> 11 votes
## Mathematica, 17 bytes

```
Tr@Divisors@#>2#&

```

## Explanation

```
Tr@                 The sum of the main diagonal of
   Divisors@         the list of divisors of
            #         the first argument
             >      is greater than
              2#      twice the first argument.
                &   End of function.

```

# Answer
> 10 votes
# Jelly, 3 bytes

```
Æṣ>

```

Try it online!

### How it works

```
Æṣ>  Main link. Argument: n

Æs   Get the proper divisor sum of n.
  >  Test if the result is greater than n.

```

# Answer
> 10 votes
# Python, 44 bytes

```
lambda n:sum(i*(n%i<1)for i in range(1,n))>n

```

**Try it online!**

# Answer
> 9 votes
# 05AB1E, ~~5~~ 4 bytes

-1 bytes thanks to scottinet

```
Ñ¨O‹

```

Try it online! or Try 0 to 100

# Answer
> 7 votes
## Retina, ~~50~~ 45 bytes

```
^(?!(1(?<=(?=(?(\3+$)((?>\2?)\3)))^(1+)))*1$)

```

Input in unary, output `1` for abundant numbers, `0` otherwise.

There is nothing Retina-specific about this solution. The above is a pure .NET regex which matches only abundant numbers.

Try it online! (Test suite that filters decimal input with the above regex.)

# Answer
> 6 votes
## Retina, 34 bytes

Byte count assumes ISO 8859-1 encoding.

```
M!&`(1+)$(?<=^\1+)
1>`¶

^(1+)¶1\1

```

Input in unary, output `1` for abundant numbers, `0` otherwise.

Try it online!

### Explanation

```
M!&`(1+)$(?<=^\1+)

```

We start by getting all divisors of the input. To do this, we return (`!`) all *overlapping* (`&`) matches (`M`) of the regex `(1+)$(?<=^\1+)`. The regex matches some suffix of the input, provided that the entire input is a multiple of that suffix (which we ensure by trying to reach the beginning fo the string using only copies of the suffix). Due to the way the regex engine looks for matches, this will result a list of divisors in descending order (separated by linefeeds).

```
1>`¶

```

The stage itself simply matches linefeeds () and removes them. However, the `1>` is a limit, which skips the first match. So this effectively adds together all divisors except the input itself. We end up with the input on the first line and the sum of all proper divisors on the second line.

```
^(1+)¶1\1

```

Finally, we try to match the at least one more `1` on the second line than we have on the first line. If that's the case, the sum of proper divisors exceeds the input. Retina counts the number of matches of this regex, which will be `1` for abundant numbers and `0` otherwise.

# Answer
> 6 votes
# x86 machine code, 25 bytes

```
00000000: 8bc8 d1e9 33db 33d2 50f7 f158 85d2 7502  ....3.3.P..X..u.
00000010: 03d9 7204 e2f0 3bc3 c3                   ..r...;..

```

Listing:

```
8B C8       MOV  CX, AX         ; counter starts at N / 2
D1 E9       SHR  CX, 1          ; divide by 2
33 DB       XOR  BX, BX         ; clear BX (running sum of factors)
    DIV_LOOP:
33 D2       XOR  DX, DX         ; clear DX (high word for dividend)
50          PUSH AX             ; save original dividend
F7 F1       DIV  CX             ; DX = DX:AX MOD CX, AX = DX:AX / CX
58          POP  AX             ; restore dividend (AX was changed by DIV)
85 D2       TEST DX, DX         ; if remainder (DX) = 0, CX is a divisor
75 02       JNZ  CONT_LOOP      ; if not, continue loop to next
03 D9       ADD  BX, CX         ; add number to sum
    CONT_LOOP:
72 04       JC   END_ABUND      ; if CF=1, BX has unsigned overflow it is abundant
E2 F0       LOOP DIV_LOOP
3B C3       CMP  AX, BX         ; BX<=AX -> CF=0 (non-abund), BX>AX -> CF=1 (abund)
    END_ABUND:
C3          RET                 ; return to caller

```

Callable function, input `N` in `AX`. Output `CF`=`1` if abundant, `CF`=`0` if not abundant.

Try it online!

Props:

* Fixed for 16-bit overflow (+5 bytes). Thanks @deadcode for the suggestions!
* Simplified return logic (-3 bytes). Thx to help from @deadcode once again.
* Use TEST instead of CMP (-1 byte). Thx to @l4m2, and make sure to upvote @l4m2's shorter x86 answer!
* Thx to @deadcode for the TIO link

# Answer
> 5 votes
# Actually, 5 bytes

```
;÷Σ½>

```

Try it online!

```
;     # Duplicate input
 ÷    # Get divisors
  Σ   # Sum
   ½  # Divide by 2 (float)
    > # Test is greater than input

```

# Answer
> 5 votes
**Java 8, 53 bytes ( a lot more if you include the ceremonial code )**

```
return IntStream.range(1,n).filter(e->n%e<1).sum()>n;

```

Try it online

Explanation :

```
IntStream.range(1,n) \\ numbers from 1 to n-1
filter(e->n%e<1)     \\ filter in numbers that perfectly divide the number n
sum()>n              \\ sum and compare to original number

```

# Answer
> 5 votes
# 05AB1E, 4 bytes

```
Ñ¨O‹

```

Try it online!

# How it works

```
Ñ        #list of divisors
 ¨       #remove last element (i.e the input from the list of factors)
  O      #sum the list
   ‹     #is this sum less than the input?

```

Sorry to post in old question, I was just going through old posts for practise and noticed my solution was shorter than the next best 05AB1E solution.

# Answer
> 5 votes
# Regex (Perl/PCRE+`(?^=)`RME), 36 bytes

```
(?=((\2x+?|^x)(?^=\2+$))+)(\2x+)\3+$

```

Try it on replit.com (RegexMathEngine)

Takes its input in unary, as the length of a string of `x`s.

This is based on my 43 byte .NET version; for the full explanation, see below. Lookinto, a new feature in RegexMathEngine, allows `(?<=(?=\2+$)^.*)` to be shortened to the equivalent `(?^=\2+$)`.

This is not just the shortest, but the fastest under RegexMathEngine, even though the 43 byte .NET regex it's based on is the slowest under .NET (beaten by both 44 byte regexes in speed).

# Regex (Java / .NET) / Retina, 43 bytes

```
(?=((\2x+?|^x)(?<=(?=\2+$)^.*))+)(\2x+)\3+$

```

Try it online! \- Java (very slow)
Try it online! \- Regex (.NET)
Try it online! \- Retina

This is 2 bytes shorter than Martin Ender's answer. Its structure is quite different, and it's more portable to different regex engines.

It works by first adding up as many proper divisors of N as it can, in strict order from smallest to largest, while having a sum not greater than N. Then it checks if there exists a larger proper divisor than the last one added to the sum; if there does, N is an abundant number.

```
# For the purpose of these comments, the input number will be referred to as N.

                      # No anchor needed, because \2 cannot be captured if
                      # matching is started anywhere besides the beginning.
(?=
    (                 # Add up all values of \2 until there is no more room in
                      # N to keep going
        (\2x+?|^x)    # \2 = the smallest value greater than the previous value
                      # of \2 which satisfies the following condition; if we're
                      # at the beginning, \2 = 1
        (?<=          # Lookbehind - evaluated from right to left
            (?=\2+$)  # Assert that N is divisible by \2
            ^.*       # Jump to the beginning of the input string, then execute
                      # the above lookahead
        )
    )+
)
(\2x+)                # Match if there exists another proper divisor of N, \3,
\3+$                  # such that \3 is greater than the last value of \2. If
                      # there does, that means there was insufficient room in N
                      # to add up all of its proper divisors, and N is abundant.

```

# Regex (Python`regex` / .NET) / Retina, 47 bytes

```
(?=((\3x+?|^x)(?<=(?=\2+$)^.*(\2)))+)(\2x+)\4+$

```

**Try it online! \- Python `import regex`**
Try it online! \- .NET
Try it online! \- Retina

This is a port of the 43 byte Java/.NET version, avoiding a nested backreference in order to add Python`regex` support. The way in which this is done (placing the copy inside the lookbehind) removes Java support.

# Regex (Perl / PCRE2 v10.35+), 49 bytes

This is a direct port of the .NET regex, emulating variable-length lookbehind using a recursive subroutine call.

```
(?=((\2x+?|^x)((?<=(?=^\2+$|(?3)).)))+)(\2x+)\4+$

```

Try it online! \- Perl (slow)
Attempt This Online! \- PCRE2 v10.40+

```
(?=
    (
        (\2x+?|^x)
        ((?<=          # (?3) calls this
            (?=        # Circumvent the constant-width limitation of lookbehinds
                       # in PCRE by using a lookahead inside the lookbehind
                ^\2+$  # This is the payload of the emulated variable-length
                       # lookbehind, same as the one in the .NET regex
            |
                (?3)   # Recursive call - this is the only alternative that can
                       # match until we reach the beginning of the string
            )
            .          # Go back one character at a time, trying the above
                       # lookahead for a match each time
        ))
    )+
)
(\2x+)
\4+$

```

# Regex (Java / Python`regex` / .NET) / Retina, 50 bytes

```
(?=((?=(\3|^))(\2x+?)(?<=(?=\3+$)^.*))+)(\3x+)\4+$

```

Try it online! \- Java (very slow)
Try it online! \- Python `import regex`
Try it online! \- .NET

This is a port of the 43 byte Java/.NET version, avoiding a nested backreference in order to add Python`regex` support, while keeping Java support.

# Regex (Perl / PCRE), 58 bytes

Porting the PCRE2 regex to PCRE1 requires working around some bugs:

```
(?=((?=(\3|^))(\2x+?)((?<=(?=z|^\3+$|(?4)).)))+)(\3x+)\5+$

```

The `(\2x+?|^x)` had to be changed to `(?=(\3|^))(\2x+?)`, copying `\3` into `\2` and `\2` into `\3` (emulating a nested backref using a forward backref), because using a backreference inside its own group forces that group to be atomic in PCRE1, and in PCRE2 up to v10.34. And a fake always-false alternative `z` had to be added to the recursive subroutine to prevent the error message "recursive call could loop indefinitely" in PCRE1.

Try it online! \- Perl (slow)
**Try it online! \- PCRE1
Try it online! \- PCRE2 v10.33**
Attempt This Online! \- PCRE2 v10.40+

---

# Regex (.NET) / Retina, 44 bytes

```
^(?!((?<=(?=(?(\3+$)((?>\2?)\3)))(^x*))x)*$)

```

Try it online! \- Regex (.NET)
Try it online! \- Retina

```
^(?!(x(?=(x*$)(?<=(?(^\2+)(\2(?>\3?))))))*$)

```

Try it online! \- Regex (.NET)
Try it online! \- Retina

This is based on Martin Ender's answer, but saving 1 byte by testing zero as a potential divisor of \\$n\\$ (it never will be, so this is harmless), thus skipping the need to explicitly exclude \\$n\\$ itself as a divisor. Another upshot of this is that we can extend the valid domain from `^\x+$` to `^\x*$`, giving the correct answer (non-match, i.e. false) for an input of zero.

I have included versions with both smallest-to-largest and largest-to-smallest divisor summing order. The length for both is 44 bytes. Only the largest-to-smallest version is commented below, because it's simpler to explain, and I already commented the original 45 byte smallest-to-largest version in my ECMAScript answer.

```
^(?!                  # Attempt to add up all the divisors. Since this is a regex and we
                      # can only work within the available space of the input, that means
                      # if the sum of the divisors is greater than N, the attempt to add
                      # all the divisors will fail at some point, causing this negative
                      # lookahead to succeed, showing that N is an abundant number.
  (x                  # Cycle through all positive values of tail that are less than N,
                      # testing each one to see if it is a divisor of N. Start at N-1.
    (?=               # Do the below operations in a lookahead, so that upon popping back
                      # out of it our position will remaing the same as it is here.
      (x*$)           # \2 = tail, a potential divisor; go to end to that the following
                      # lookbehind can operate on N as a whole.
      (?<=            # Switch to right-to-left evaluation so that we can operate both
                      # on N and the potential divisor \2. This requires variable-length
                      # lookbehind, a .NET feature. Please read these comments in the
                      # order indicated, from [Step 1] to [Step 4].
        (?(^\2+)      # [Step 1] If \2 is a divisor of N, then...
          (           # [Step 2] Add it to \3, the running total sum of divisors:
                      #          \3 = \3 + \2
            \2        # [Step 4] Iff we run out of space here, i.e. iff the sum would
                      #          exceed N at this point, the match will fail, making the
                      #          negative lookahead succeed, showing that we have an
                      #          abundant number.
            (?>\3?)   # [Step 3] Since \3 is a nested backref, it will fail to match on
                      #          the first iteration. The "?" accounts for this, making
                      #          it add zero to itself on the first iteration. This must
                      #          be done before adding \2, to ensure there is enough room
                      #          for the "?" not to cause the match to become zero-length
                      #          even if \3 has a value.
          )
        )
      )
    )
  )*                  # By using "*" instead of "+" here, we can avoid categorizing zero
                      # as an abundant number.
  $                   # We can only reach this point if all proper divisors of N, all the
                      # way down to \2 = 1, been successfully summed into \3, which would
                      # mean N is not an abundant number.
)

```

As far as speed goes, the smallest-to-largest version is faster than the largest-to-smallest version (both in .NET and their ports below). Both are faster than the 43 byte version under .NET.

## Regex (Perl/PCRE+`(?^=)`RME), 42 bytes

```
^(?!(x(?=(x*))(?^=(?(?=\2+$)(\3?+\2))))*$)

```

Try it on replit.com (RegexMathEngine)

This is a port of the largest-to-smallest 44 byte .NET regex, using lookinto instead of variable-length lookbehind. Although the Perl/PCRE syntax for lookahead conditionals is more verbose, this is compensated for by being able to use a possessive quantifier.

## Regex (Perl/PCRE+`(?^=)`RME), 44 bytes

```
^(?!((?^0=(x*))(?^=(?(?=\2+$)(\3?+\2)))x)*$)

```

Try it on replit.com (RegexMathEngine)

This is a port of the smallest-to-largest 44 byte .NET regex, again using lookinto instead of variable-length lookbehind. This one is less conducive to being ported, and I had to use `(?^0=)`, lookinto accessing the in-progress current match. I've not decided how to finalize the current behavior of this, so it's likely this version will not work with a future version of lookinto.

## Regex (PCRE2), 73 bytes

This is a direct port of the 44 byte .NET regex (based on Martin Ender's regex). It doesn't port well to PCRE, because it changes the value of a capture group inside the lookbehind – but upon the return of any subroutine in PCRE, all capture groups are reset to the values they had upon entering the subroutine. So the only way to port it is to change the main loop from iteration into recursion, resulting in a large and very slow regex:

```
^(?!(x(?=(x*$)((?<=(?=^(?(?=\2+$)(?=(\4?+\2))).*(?=\2$)(?1)|(?3)).)))|$))

```

Try it online! \- PCRE2 v10.33 (PHP)
Try it on regex101 \- PCRE2 v10.38+
Attempt This Online! \- PCRE2 v10.40+ (PHP)
Attempt This Online! \- PCRE2 v10.40+ (C++)

# Answer
> 5 votes
# Julia, 25 bytes

```
a(n,r=1:n)=(n.%r.<1)'r>2n
```

Attempt This Online!

# Answer
> 4 votes
# PARI/GP, 15 bytes

```
n->sigma(n)>2*n

```

The variant `n->sigma(n,-1)>2` is, unfortunately, longer.

# Answer
> 4 votes
# Powershell, ~~51~~ 49 Bytes

```
param($i)((1..$i|?{!($i%$_)})-join"+"|iex)-gt2*$i

```

I wish I could remove some brackets.

-2 thanks to AdmBorkBork, instead of not counting the input in the initial range, we just take it into account in the final check.

Loop through range of `1..` to the `$i`nput, minus 1, find where (`?`) the inverse modulo of input by the current number is `$true` (aka only 0) - then `-join` all of those numbers together with `+` and `iex` the resulting string to calculate it, then see if the sum of these parts is greater than the input.

```
PS C:\++> 1..100 | ? {.\abundance.ps1 $_}
12
18
20
24
30
36
40
42
48
54
56
60
66
70
72
78
80
84
88
90
96
100

```

# Answer
> 4 votes
# , ~~19 16~~ 15 bytes

```
{x<+/&~(!x)!'x}

```

Returns `1` for true, and `0` for false.

Try it online!

```
{             } /function(x)
       (!x)     /{0, 1, ..., x-1}
            '   /for each n in {0, 1, ..., x-1}:
           ! x  /    do (x mod n)
      ~         /for each, turn 0 -> 1, * -> 0 (map not)
     &          /get indices of 1's
   +/           /sum (fold add)
 x<             /check if x < the sum

```

# Answer
> 3 votes
# MATL, 6 bytes

```
Z\sGE>

```

Outputs 1 for abundant numbers, 0 otherwise.

## How it works

```
Z\      % list the divisors of the implicit input
s       % add them
G       % push the input again
E       % double it
>       % compare
        % implicitly display result

```

# Answer
> 3 votes
## QBIC, 22 bytes

```
:[a/2|~a%b|\p=p+b}?p>a

```

This is an adaptation to the QBIC primality test. Instead of counting the divisors and checking if it's less than three, this sums the proper divisors. This runs only along half of `1 to n`, where the primality test runs through `1 to n` completely.

Explanation:

```
:       Get the input number, 'a'
[a/2|   FOR(b=1, b<=(a/2), b++)
~a%b    IF a MOD b != 0  --> QBasic registers a clean division  (0) as false.
        The IF-branch ('|') therefor is empty, the code is in the ELSE branch ('\')
|\p=p+b THEN add b to runnning total p
}       Close all language constructs: IF/END IF, FOR/NEXT
?p>a    Print '-1' for abundant numbers, 0 otherwise.

```

# Answer
> 3 votes
# Pure Bash, 37 bytes

```
for((;k++<$1;s+=$1%k?0:k)){((s>$1));}

```

*Thanks to @Dennis for rearranging the code -- saving 6 bytes and eliminating the incidental output to stderr.*

The input is passed as an argument.

The output is returned in the exit code: 0 for abundant, 1 for not abundant.

Output to stderr should be ignored.

Test runs:

```
for n in {1..100}; do if ./abundant "$n"; then echo $n; fi; done 2>/dev/null
12
18
20
24
30
36
40
42
48
54
56
60
66
70
72
78
80
84
88
90
96
100

```

# Answer
> 3 votes
# Japt, 9 7 6 bytes

```
<Uâ1 x

```

Saved 2 bytes thanks to ETHproductions. Saved 1 byte thanks to obarakon.

Try it online!

# Answer
> 3 votes
# JavaScript (ES6), 33 bytes

```
let g =
x=>(f=n=>--n&&n*!(x%n)+f(n))(x)>x
```

```
<input type=number min=1 value=1 step=1 oninput="O.innerHTML=g(+value)"><br>
<pre id=O>false</pre>
```

# Answer
> 3 votes
# Cubix, 38 bytes

```
/..?%?(O;0I:^.<.>;rrw+s;rUO?-<...O0L.@

```

Try it here

```
      / . .
      ? % ?
      ( O ;
0 I : ^ . < . > ; r r w
+ s ; r U O ? - < . . .
O 0 L . @ . . . . . . .
      . . .
      . . .
      . . .

```

`0I:` \- sets up the stack with 0, n, n (s, n, d)
`^` \- start of the loop `)?` \- decrement d and test for 0. 0 exits loop
`%?` \- mod against n and test. 0 causes `;rrw+s;rU` which rotates s to top and adds d, rotates s to bottom and rejoins loop
`;<` \- Cleanup and rejoin the loop.
On exiting loop
`;<` \- Remove d from stack and redirect
`-?` \- Remove n from s and test, 0 `LOU@` turns left, outputs and exits, negatives `0O@` push zero, output and exits. positives `;O` remove difference and outputs n. The path then goes through to the left turn which redirects to the `@` exit

# Answer
> 3 votes
# APL (Dyalog Unicode), 11 bytesSBCS

-2 bytes thanks to @Adám

```
⊢<1⊥∘⍸0=⍳|⊢

```

Try it online!

Explanation:

```
⊢<1⊥∘⍸0=⍳|⊢ ⍝ Monadic function train
        ⍳   ⍝ Generate integers from 1 to input
        |⊢ ⍝ For each of the above, modulo the input
      0=   ⍝ Return a boolean vector where ones correspond
           ⍝ to zeroes
     ⍸      ⍝ Return the indices of the ones in the above vector
           ⍝ This results in a vector of the proper divisors of our input
  1⊥∘      ⍝ Composed with the above, decode into unary base.
           ⍝ This has the same effect as summing the vector, but is used
           ⍝ here to comply with the function train format.
⊢<         ⍝ Is the above sum greater than our input?

```

# Answer
> 3 votes
# Arn, 12 bytes

```
Ý░™€ºa^¬"/”&

```

Try it!

# Explained

Unpacked: `<(+\$v{!%v}1->`

```
  _                    Variable initialized to STDIN; implied
<                      Is less than
  (                    Begin expression
      \                Fold with
    +                  Addition
        $              Filtered list
          v{           Block with key of v
            !          Boolean not
                _      Implied
              %        Modulo
                v
           }           End of block
             1         Literal one
           ->          Exclusive range
             _         Implied
  )                    End of expression, implied

```

I should probably add a builtin fix for getting factors...

# Answer
> 2 votes
# RProgN, 8 Bytes

```
~_]k+2/<

```

## Explained

```
~_]k+2/<
~           # Zero Space Segment
 _          # Convert the input to an integer
  ]         # Duplicate the input on the stack
   k+       # Get the sum of the divisors of the top of the stack
     2/     # Divded by 2
       <    # Is the Input less than the sum of its divisors/2.

```

Try it online!

# Answer
> 2 votes
## Batch, 84 bytes

```
@set/ak=%1*2
@for /l %%j in (1,1,%1)do @set/ak-=%%j*!(%1%%%%j)
@cmd/cset/a"%k%>>31

```

Outputs `-1` for an abundant number, `0` otherwise. Works by subtracting all the factors from `2n` and then shifting the result 31 places to extract the sign bit. Alternative formulation, also 84 bytes:

```
@set k=%1
@for /l %%j in (1,1,%1)do @set/ak-=%%j*!(%1%%%%j)
@if %k% lss -%1 echo 1

```

Outputs `1` for an abundant number. Works by subtracting all the factors from `n` and then comparing the result to to `-n`. (`set/a` is Batch's only way of doing arithmetic so I can't easily adjust the loop.)

# Answer
> 2 votes
# Perl 6, ~~72~~ 24 bytes

```
{$_ <sum grep $_%%*,^$_}

```
* Program argument: a.
* Generate a list from `1..a`.
* Take all the numbers that are divisors of `a`.
* Sum them.
* Check if that sum is greater than `a`.

Thanks to @b2gills.

# Answer
> 2 votes
# Pyth, 11 bytes

```
>sPf!%QTS

```

Old:

```
L!%Qb>sPy#S

```

I can't use `!%` as a pfn for `#`, because it's two functions. Makes me sad :(.

---

```
L!%Qb>sPy#SQ    Program's argument: Q
L!%Qb           Define a lambda y, that takes b as an argument
 !%Qb           Return true if Q is divisible by b
          S     Make a range 1..Q
        y#      Filter that range with the lambda (y)
       P        Remove the last element (Q itself)
      s         Sum them
     >     Q    Check if that sum is greater than the program's argument

```

# Answer
> 2 votes
# Ruby, ~~39~~ 32 bytes

```
->n{n<(1...n).sum{|x|n%x>0?0:x}}

```

Try it online!

Updated to Ruby 2.6

# Answer
> 2 votes
# J, 19 bytes

Thanks to Conor O'Brien for cutting it to 19 bytes!

`<[:+/i.#~i.e.]%2+i.`

Previous: (34 bytes)

`f=:3 :'(+/((i.y)e.y%2+i.y)#i.y)>y'`

Returns 1 if it's abundant and 0 if it's not.

**Output:**

```
   f 3
0
   f 12
1
   f 11
0
   f 20
1

```

# Answer
> 2 votes
# Japt, 4 bytes

```
<âÔx

```

Try it online!

# Answer
> 2 votes
# , ~~32~~ 28 bytes

```
2*(n=scan())<(x=1:n)%*%!n%%x

```

Try it online!

Reads `n` from stdin, returns `TRUE` for abundant numbers and `FALSE` otherwise.

# Answer
> 2 votes
# C# (Visual C# Interactive Compiler), 48 bytes

```
x=>Enumerable.Range(1,x).Sum(y=>y<x&x%y<1?y:0)>x

```

Try it online!

Above is a LINQ based solution that creates a range of numbers slightly larger than the input number. Each element is tested for being a) being a proper divisor of the input and b) being less than the input. If both checks pass, it is added to a sum which is compared to the input.

Below is a a recursive solution that uses an inner function to calculate the summation. While this one seems the most interesting to me, I think the LINQ based approach will not be beat.

# C# (Visual C# Interactive Compiler), 60 bytes

```
x=>{int g(int y)=>(x%y<1?y:0)+(++y<x?g(y):0);return g(1)>x;}

```

Try it online!

Finally, we have an iterative solution which currently is between the LINQ based approach and the recursive one.

# C# (Visual C# Interactive Compiler), 53 bytes

```
x=>{int y=0,z=0;for(;++y<x;z+=x%y<1?y:0);return z>x;}

```

Try it online!

# Answer
> 2 votes
# PowerShell, 43 bytes

```
param($n)1..$n|%{$s+=$_*!($n%$_)}
$s-gt2*$n

```

Try it online!

# Answer
> 2 votes
# Common Lisp, 63 bytes

```
(lambda(n)(>(loop for i from 1 below n if(=(mod n i)0)sum i)n))

```

Try it online!

# Answer
> 2 votes
## F#, 51 bytes

```
let f n=Seq.filter(fun x->n%x=0){1..n-1}|>Seq.sum>n

```

Try it online!

Filters out all the numbers that don't divide evenly into `n`, then sums them and compares them against `n`.

# Answer
> 2 votes
# x86 opcode edited from 179016, 20 bytes

```
f:      mov ecx, eax       ; copy input number N into ECX
        lea ebx, [eax+eax] ; copy input number 2N into EBX
.a:     cdq                ; clear DX (high word for dividend)
        push eax           ; save original dividend
        div ecx            ; divide DX:AX / CX
        pop eax            ; restore dividend
        test edx, edx      ; if remainder = 0, it divides evenly and is a divisor of N
        jnz .b             ; if not, continue loop
        sub ebx, ecx       ; Subtract divisor from EBX; this simultaneously changes the
                           ; running total, and sets the flags for the return value.
        jc .c              ; If CF=1, the sum of divisors subtracted from N has exceeded
                           ; N, thus N is abundant, and we need to exit the loop now to
                           ; return this result in CF.
.b:     loop .a
.c:                        ; return value: CF=0 (non-abundant), CF=1 (abundant)

```

Try it online!

Saved from the reverse working

# Answer
> 2 votes
# Whispers v2, 49 bytes

```
> Input
>> ∤1
>> ∑2
>> 3-1
>> 4>1
>> Output 5

```

Try it online!

## How it works

Whispers is a non-linear language, where numbers don't refer to their numerical value; rather they reference the result of that line in the program. Execution always starts at the last line, and branches through these references.

Program structure tree (green are nilad lines):

Therefore, we start on line **6** by outputting the result of line **5**, which is

```
>> 4>1

```

which calls lines **4** and **1** and compares the results.

Line **1** is the odd line out in the program: as it starts with a single `>`, rather than a double `>>`, it is a *nilad* line. This means it returns its value interpreted literally. Numbers return their numeric value, and `Input` is preprocessed at the start of execution, being replaced with the first input on STDIN. Therefore, line **5** checks if the result for line **4** is greater than the input.

Line **4**, `>> 3-1`, subtracts the input from line **3**'s result, while line **3**, `>>∑2`, sums the values on line **2**. Line **2**, `>> ∤1`, generates the list of the input's divisors. Therefore, together, the program generates a list of the input's divisors (including the input), sums them, then subtracts the input (in order to account for the input being included in the list of divisors). Finally, we compare the sum to the input, and output the result.

# Answer
> 2 votes
# Zsh, 39 bytes

```
for ((;++b<$1;t+=$1%b?0:b)):
<<<$[t>$1]

```

Try it online!

# Answer
> 2 votes
# Vyxal, 3 bytes

```
∆K<

```

Try it Online!

# Answer
> 2 votes
# Lua (~~71~~ 68 bytes)

Thank to @Deadcode for finding a typo in the byte length and for suggesting shorter code.

```
function A(n)z=0 for i=1,n-1 do z=z+i*#{[n%i+1]=0}end return z>n end

```

# Answer
> 1 votes
# \>\<\>, ~~47+3~~ ~~46+3~~ 39+3 = 42 bytes

```
:l)?!v}l:{:}$%0=*{
 v-$0<
l<+v?=1
)n;>0

```

Expects the input number to be present on the stack at program start, so +3 bytes for the `-v` flag. Try it online!

*Edit: Golfed 1 byte from 3rd line: `-\~0$` =\> `-\:+`*

*Edit 2: Near complete rewrite, previous version:*

```
1v
}/!?)@:{:}+1r~?$r}:}%@:{:
-\:+
?\+l1=
;>0)n

```

# Answer
> 1 votes
# JavaScript ES6, 61 50 bytes

```
a=>[...Array(a).keys()].reduce((b,c)=>a%c?b:b+c)>a

```

```
f=a=>[...Array(a).keys()].reduce((b,c)=>a%c?b:b+c)>a;

console.log(f(11));
console.log(f(12));
console.log(f(17));
console.log(f(18));
```

# Answer
> 1 votes
# Haskell, 34 bytes

```
a n=n<sum[a|a<-[1..n-1],mod n a<1]

```

Try it online! Usage example: `a 12` returns `True`.

# Answer
> 1 votes
# Pyth, 8 bytes

```
>s{*MPyP

```

Try it online here.

```
>s{*MPyPQQ   Implicit: Q=eval(input())
             Trailing QQ inferred
       PQ    Prime factors of Q
      y      Take the powerset of the above
     P       Discard the last one (i.e. the original set itself)
   *M        Take the product of each list
  {          Deduplicate
 s           Take the sum
>        Q   Is the above greater than Q? Implicit print

```

# Answer
> 1 votes
# C# (.NET Core), ~~59~~, 53 bytes

Without LINQ.

EDIT: Thanks to ASCII-only for pointing out `for(;++k<p;)` instead of `for(;k<p;k++)`.

# C# (.NET Core), 53 bytes

```
p=>{int k=0,n=0;for(;++k<p;)n+=p%k<1?k:0;return n>p;}

```

Try it online!

# Answer
> 1 votes
# PHP, 63 bytes

```
function a($x){for($i=1;$i<$x;$i++){$s+=$x%$i?0:$i;}echo$s>$x;}

```

Usage: `a(12);`

# Answer
> 1 votes
# APL(NARS) 11 chars, 22 bytes

```
{⍵<2÷⍨11π⍵}

```

11π is the function sum divisor, so sum proper divisor would be: {(-⍵)+11π⍵}; test:

```
  f←{⍵<2÷⍨11π⍵}
  {1=f ⍵:⍵⋄⍬}¨1..100
12  18  20  24  30  36  40  42  48  54  56  60  66  70  72  78  80  84  88  90  96  100

```

# Answer
> 1 votes
# Forth (gforth), 45 bytes

```
: f 0 over 1 ?do over i mod 0= i * - loop < ;

```

Try it online!

### Explanation

Loops over every number from 1 to n-1, summing all values that divide n perfectly. Returns true if sum is greater than n

### Code Explanation

```
: f                \ start word definition
  0 over 1         \ create a value to hold the sum and setup up the bounds of the loop
  ?do              \ start a counted loop from 1 to n. (?do skips if start = end)
    over           \ copy n to the top of the stack
    i mod 0=       \ check if i divides n perfectly
    i * -          \ if so, use the fact that -1 = true in forth to add i to the sum
  loop             \ end the counted loop
  <                \ check if n is less than the sum
;                  \ end the word definition

```

# Answer
> 1 votes
# Perl 5 `-MList::Util=sum -pa`, 32 bytes

```
$_=$_<sum grep!("@F"%$_),1..$_-1

```

Try it online!

# Answer
> 1 votes
# Python 3, 45 bytes

```
lambda n:sum(i for i in range(1,n)if n%i<1)>n

```

Try it online!

# Answer
> 1 votes
# Factor \+ `project-euler.common`, 9 bytes

```
abundant?

```

Try it online!

Builtin, lol

# Answer
> 1 votes
# C (clang), 47 bytes

```
g,o;l(f){for(g=o=f;--o;)g-=f%o?0:o;return g<0;}

```

Try it online!

# Answer
> 1 votes
# cQuents, 6 bytes

```
$<U\z$

```

Try it online!

Outputs 1 for true and 0 for false. If no input given, outputs the 1-indexed sequences of 1/0 for whether each index is an abundant number.

## Explanation

```
        each term in the sequence equals
$       index
 <            <
  U             sum (                           )
   \z                 proper divisors (       )
     $                                  index

```

# Answer
> 1 votes
# Pyt, 7 bytes

```
ĐĐð⇹\Ʃ<

```

Try it online!

```
ĐĐ          implicit input (n); duplicate on stack twice
  ð         get all factors of n
   ⇹\       remove n from list of factors (i.e. reduce list to proper divisors)
     Ʃ      sum proper divisors
      <     is the sum greater than n?; implicit print

```

# Answer
> 1 votes
# Arturo, 26 bytes

```
$[n]->n<sum chop factors n

```

Try it

# Answer
> 0 votes
# Java 7, ~~69~~ 68 bytes

```
Object c(int n){int s=0,i=1;for(;++i<=n/2;s+=n%i<1?i:0);return s>n;}

```

**Explanation:**

```
Object c(int n){                       // Boolean method with integer parameter
   int s = 0,                          // sum initialization
       i = 1;                          // counter initialization (starts at 2: i=1 and ++i becomes i=2)
   for(; ++i <= n/2; s += n % i < 1    // loop while (i <= n/2)
                           ? i         //   if (n % i == 0)
                           : 0);       //     r = r + i
   return s > n;                       // return sum > input
 }

```

**Test code:**

Try it here.

```
class M{
  static Object c(int n){int s=0,i=1;for(;++i<=n/2;s+=n%i<1?i:0);return s>n;}

  public static void main(String[] a){
    for(int i = 0; i <= 100; i++){
      System.out.print(i+": "+c(i) + ";  ");
    }
  }
}

```

**Output:**

```
0: false;  1: false;  2: false;  3: false;  4: false;  5: false;  6: false;  7: false;  8: false;  9: false;  10: false;
11: false;  12: true;  13: false;  14: false;  15: false;  16: false;  17: false;  18: true;  19: false;
20: true;  21: false;  22: false;  23: false;  24: true;  25: false;  26: false;  27: false;  28: false;  29: false;
30: true;  31: false;  32: false;  33: false;  34: false;  35: false;  36: true;  37: false;  38: false;  39: false;
40: true;  41: false;  42: true;  43: false;  44: false;  45: false;  46: false;  47: false;  48: true;  49: false;
50: false;  51: false;  52: false;  53: false;  54: true;  55: false;  56: true;  57: false;  58: false;  59: false;
60: true;  61: false;  62: false;  63: false;  64: false;  65: false;  66: true;  67: false;  68: false;  69: false;
70: true;  71: false;  72: true;  73: false;  74: false;  75: false;  76: false;  77: false;  78: true;  79: false;
80: true;  81: false;  82: false;  83: false;  84: true;  85: false;  86: false;  87: false;  88: true;  89: false;
90: true;  91: false;  92: false;  93: false;  94: false;  95: false;  96: true;  97: false;  98: false;  99: false;  100: true;

```

# Answer
> 0 votes
# Scala, 39 bytes

```
(n:Int)=>(1 until n filter{n%_<1}sum)>n

```

# Answer
> 0 votes
# Javascript, 47 Bytes

```
a=>{s=d=0;while(a>d){s+=a%d?0:d;d++}return s>d}

f=a=>{s=d=0;while(a>d){s+=a%d?0:d;d++}return s>d};
console.log(f(11));
console.log(f(12));
console.log(f(15));
console.log(f(18));
```

Quite straight forward: check all numbers smaller than the input, if the input is divisible by them add them to the sum, and return whether the sum is bigger than the input

# Answer
> 0 votes
# C, 68 bytes

```
int s,x;main(i){scanf("%d",&x);while(++i<x)s+=x%i^0?0:i;return s>x;}

```

# Answer
> 0 votes
# Racket, 46 bytes

That's 46 bytes including the `(require math)`.

```
(λ(n)(>(-(sum(divisors n))n)n))

```

The function produces booleans.

Try it online!

It's pretty simple, uses the `divisors` function to produce a list of all divisors of `n`. Since the list includes `n` itself, we need to remove it after summing.

# Answer
> 0 votes
# Java 8, 66 bytes

```
n->java.util.stream.IntStream.range(1,n).filter(i->n%i==0).sum()>n

```

Try it online!

# Explanation

```
n->                                       // define a lambda function
    java.util.stream.IntStream.range(1,n) // create a stream of integers from 1 to n
    .filter(i->n%i==0)                    // filter out non-factors
    .sum()                                // sum the factors
>n                                        // compare the sum to the original number n
                                          // implicit return

```

Edit: Looks like someone already did this 2 years ago and got 1 byte shorter

# Answer
> 0 votes
# Javascript,72bytes

```
var n=prompt(),div=0,i=1;while(++i<=n/2){div+=n%i?0:i}console.log(div>n)

```

# Answer
> 0 votes
# TI-BASIC (TI-84), 23 bytes

```
:2Ans<sum(seq(Ans/Xnot(remainder(Ans,X)),X,1,Ans,1

```

This answer is very similar to my answer here.
Input is in `Ans`.
Output is in `Ans` and is automatically printed out when the program completes.

**Explanation:**
(TI-BASIC doesn't have comments, so just assume that `;` makes a comment)

```
:2Ans=sum(seq(Ans/Xnot(remainder(Ans,X)),X,1,Ans    ;Full program

 2Ans                                               ;double the input
          seq(                                      ;generate a list
                                         X,          ;using the variable X,
                                           1,        ;starting at 1,
                                             Ans     ;and ending at the input
                                                     ;with an implied increment of 1
              Ans/X                                 ;from the input divided by X
                   not(                ),           ;multiplied by the negated result of
                       remainder(Ans,X)              ;the input modulo X
                                                     ;(result: 0 or 1)
      sum(                                          ;sum up the elements in the list
     <                                              ;is the sum greater than double the input?

```

**Example:**

```
12
           12
prgmCDGF4
            1
6
            6
prgmCDGF4
            0

```

---

**Note:** The byte count of a program is evaluated using the value in **\[MEM\]**\>**\[2\]**\>**\[7\]** (36 bytes) then subtracting the length of the program's name, `CDGF2`, (5 bytes) and an extra 8 bytes used for storing the program:

36 - 5 - 8 = 23 bytes

# Answer
> 0 votes
# Kotlin, 37 bytes

```
{i->(2..i-1).filter{i%it==0}.sum()>i}

```

Expanded:

```
{ i -> (2..i - 1).filter { i % it == 0 }.sum() > i }

```

Explanation:

```
  {i->                      start lambda with parameter i
    (2..i-1)                create a range from 2 until i - 1 (potential divisors)
      .filter{i%it==0}      it's a divisor if remainder = 0; filter divisors
        .sum()              add all divisors
          >i                compare to the original number

```

Try it online!

# Answer
> 0 votes
# TI-BASIC, 21 bytes

```
seq(I,I,1,A-1
A<sum(Ansnot(fpart(A/Ans

```

TI-BASIC usually has a builtin for this kind of thing, but nothing fits that well here. Takes input from the A variable and outputs 1 or 0 if the number is or isn't abundant.

seq( generates a list of numbers from a function. Here it executes the function I on the I variable from one to one less than the input. Then working backward from the next line, we divide our input by the list we generated (stored in Ans) and take the fractional part so we have a new list of remainders for each potential divisor. We then build a list of booleans by taking not( on the remainder list and multiply that by the original list in Ans implicitly to get a list of proper divisors. Then we just sum the list of proper divisors and compare that to the input.

This was 24 bytes, golfed down to 21 using not( instead of \*(0=

# Answer
> 0 votes
# tinylisp, 78 bytes

```
(load library
(q((N)(l N(sum(filter(partial divides?(q D)(list(q _)N))(range N

```

Try it online!

Start with a list of each `D` from 0 through `N` \- 1; filter it for the values of `D` that exactly divide `N`. Sum the results. Iff `N` is less than that sum, `N` is abundant.

# Answer
> 0 votes
# Excel, 46 bytes

```
=LET(s,SEQUENCE(A3-1),SUM((MOD(A3,s)=0)*s)>A3)

```

Works for numbers up to 2^20 + 1 (1,048,577).

This 90 byte version works for numbers up to (2^20 + 1) ^ 2 - 1 (1,099,513,724,928).

```
=LET(s,SEQUENCE(SQRT(A2)),m,(MOD(A2,s)=0)*s,g,IFERROR(A2/m,0),SUM(m,g)-A2-SUM((m=g)*m)>A2)

```

# Answer
> 0 votes
# Thunno 2, 4 bytes

```
FṫS<

```

Attempt This Online!

#### Explanation

```
FṫS<  # Implicit input      ->  12
F     # Factors             ->  [1, 2, 3, 4, 6, 12]
 ṫ    # Tail remove         ->  [1, 2, 3, 4, 6]
  S   # Sum the list        ->  16
   <  # Compare with input  ->  1
      # Implicit output

```

---
Tags: code-golf, math, sequence, decision-problem
---


title: Random Capitalization

text:
# Question
Title: Random Capitalization
**The Task**

Your task is to create a program or a function that, given an input, outputs the input text with random letters capitalized, while keeping already capitalized letters capitalized.

Every combination of capitalizations of the lowercase letters should be possible. For example, if the input was `abc`, there should be a non-zero probability of outputting any of the following combinations: `abc`, `Abc`, `aBc`, `abC`, `ABc`, `AbC`, `aBC` or `ABC`.

**Input**

Your input is a string, containing any number of printable ASCII characters, for example `Hello World`. The outputs for that input include `HeLLo WoRlD`, `HElLO WOrld`, etc.

**Scoring**

This is code-golf, so the shortest answer in each language wins!

# Answer
> 14 votes
# TI-Basic (83 series), 137 bytes

```
For(I,1,length(Ans
Ans+sub(sub(Ans,I,1)+"ABCDEFGHIJKLMNOPQRSTUVWXYZ",1+int(2rand)inString("abcdefghijklmnopqrstuvwxyz",sub(Ans,I,1)),1
End
sub(Ans,I,I-1

```

Takes input in `Ans`, as illustrated in the screenshot below:

(If the screenshot looks scrambled, as it sometimes does for me, try opening it in a new tab?)

TI-Basic (at least the TI-83 version... maybe I should branch out into TI-89 golfing) is a terrible language to try to golf this challenge in, since:

1. It provides absolutely no support for any arithmetic with characters, knowing the uppercase version of a lowercase character, or even knowing the alphabet.
2. Every single lowercase character takes 2 bytes to store. (In fact, I had to use an assembly script just to be able to type the lowercase letters.)

The result is that 78 bytes of this program (more than half) are just storing the alphabet, *twice*.

Anyway, the idea is that we loop through the string, with a chance of turning lowercase characters into uppercase ones as we go, and adding the result onto the end of the string so that both the input and the output are stored in `Ans`. When we leave the `For(` loop, `I` is one more than the length of the original string, so taking the `I-1` characters starting at `I` gives the output.

# Answer
> 13 votes
# Python 2, 66 65 bytes

```
lambda s:`map(choice,zip(s.upper(),s))`[2::5]
from random import*

```

Try it online!

# Answer
> 12 votes
# Japt, 6 bytes

```
®m`«`ö

```

Test it online!

### Explanation

```
®m`«`ö   Implicit input
®        Map each char in the input by
 m         mapping each char in this char through
  `«`ö       a random character of "us". (`«` is "us" compressed)
             The u function converts to uppercase, and s is slice, which does nothing here.
         Implicit output

```

# Answer
> 10 votes
# C,  ~~47~~  46 bytes

*Thanks to @l4m2 for saving a byte!*

```
f(char*s){for(;*s++-=(*s-97u<26&rand())*32;);}

```

Try it online!

**Would be 42 bytes, if it could be assumed that `{|}~` don't appear in the input:**

```
f(char*s){for(;*s++-=(*s>96&rand())*32;);}

```

Try it online!

# Answer
> 9 votes
# Jelly, 5 bytes

*Another one bytes the dust thanks to dylnan.*

```
żŒuX€

```

Try it online!

## Explanation

```
żŒuX€  main link: s = "Hello world"

żŒu    zip s with s uppercased  ["HH", "eE", "lL", "lL", "oO", "  ", ...]
   X€  map random choice        "HeLLo woRlD"

```

# Answer
> 8 votes
# Perl 5, 23 bytes

**22 bytes code + 1 for `-p`.**

```
s/./rand>.5?uc$&:$&/ge

```

Try it online!

# Answer
> 7 votes
# JavaScript (ES6), 56 bytes

```
s=>s.replace(/./g,x=>Math.random()<.5?x.toUpperCase():x)

```

If uniform randomness is not required, we can save 6 bytes by using the current time as the source of randomness:

```
s=>s.replace(/./g,x=>new Date&1?x.toUpperCase():x)

```

This tends to either uppercase or leave alone all letters at once.

# Answer
> 7 votes
# , 66 bytes

```
for(i in el(strsplit(scan(,""),"")))cat(sample(c(i,toupper(i)),1))

```

Try it online!

Another  answer.

# Answer
> 6 votes
# Charcoal, ~~8~~ 7 bytes

```
⭆Ｓ‽⁺↥ιι

```

Try it online! Link is to verbose version of code. Explanation:

```
 Ｓ          Input string
      ι     Character
    ↥ι      Uppercase character
   ⁺        Concatenate
  ‽         Random element
⭆           Map over each character and join the result
            Implicitly print

```

# Answer
> 6 votes
# Excel VBA, <sub>~~74~~ ~~71~~</sub> 64 Bytes

~~The `Randomize` call always makes random output costly in VBA :(~~

Anonymous VBE immediate window function that takes input from range `[A1]` and outputs to the VBE immediate window. Produces a 50% (on average) `UCase`d output.

```
For i=1To[Len(A1)]:a=Mid([A1],i,1):?IIf(Rnd>.5,a,UCase(a));:Next

```

# Answer
> 4 votes
# Ruby, 40 Bytes

Lambda function that takes a string. Saved 1 byte thanks to Arnauld. Saved 5 bytes thanks to Snack.

```
->s{s.gsub(/./){|x|[x,x.upcase].sample}}

```

# Answer
> 3 votes
# , ~~89~~ 88 bytes

*outgolfed by djhurio!*

```
cat(sapply(el(strsplit(scan(,""),"")),function(x)"if"(rt(1,1)<0,toupper,`(`)(x)),sep="")

```

Try it online!

This program takes each character, and with probability 1/2 converts it to uppercase or leaves it alone. It's possible to tweak this probability by playing with different values of `df` and `0`.

`rt` draws from the Student's t-distribution, which has median 0 with any degree of freedom (I selected `1` since it's the smallest number possible).

# Answer
> 3 votes
# APL+WIN, 37 bytes

```
⎕av[c-((n÷2)<n?n←⍴s)×32×s←98<c←⎕av⍳⎕]

```

Prompts for screen input, identifies lower case letters and randomly converts them to upper case.

# Answer
> 3 votes
# Java 8, 46 bytes

This lambda is from `IntStream` to `IntStream` (streams of code points).

```
s->s.map(c->c>96&c<'{'&Math.random()>0?c-32:c)

```

Try It Online

## Capitalization distribution

Whether to capitalize a letter used to be the quite sensible condition that `Math.random()<.5`, which was satisfied about half the time. With the current condition of `Math.random()>0` (which saves a byte), capitalization occurs virtually every time, which makes a test program kind of pointless. But it does satisfy the randomness requirement.

## Acknowledgments

* -1 byte thanks to Olivier Grégoire

# Answer
> 3 votes
# Wolfram Language (Mathematica), ~~52~~ ~~49~~ 44 bytes

```
StringReplace[c_/;Random[]<.5:>Capitalize@c]

```

Try it online!

Uses the operator form of `StringReplace`: providing it a rule (or a list of rules) but no string gives a function which applies that rule to any string you give it as input.

We could do a lot better (`RandomChoice@{#,Capitalize@#}&/@#&` is 34 bytes) if we decided to take as input (and produce as output) a list of characters, which people sometimes argue is okay in Mathematica because it's the only kind of string there is in other languages. But that's no fun.

---

*-5 bytes thanks to M. Stern*

# Answer
> 3 votes
# 05AB1E, ~~6~~ 5 bytes

*Thank you Adnan for -1 byte*

```
uø€ΩJ

```

Try it online!

**Explanation**

```
uø€ΩJ
u      Upper case of top of stack. Stack: ['ZZZAA']
 ø     Zip(a,b) (uses implicit input). Stack: ['zZ', 'zZ', 'zZ', 'AA', 'AA']
  €    Following operator at each element of its operand
   Ω   Random choice. Stack: ['z', 'Z', 'z', 'A', 'A'] (for example)
    J  Join a by ''. Stack: 'zZzAA'
       Implicit output

```

Method taken from @totallyhuman's answer

# Answer
> 3 votes
# Swift 4, 86 bytes

```
s.map{let s="\($0)",u=s.uppercased();return u==s ? u:arc4random()%2==0 ? u:s}.joined()

```

# Answer
> 3 votes
# Ruby, 39 bytes

`->s{s.gsub(/./){[$&,$&.upcase].sample}}`

Largely inspired from displayname's answer. (I couldn't comment to suggest this one-byte-less version for lack of reputation, sorry displayname)

# Answer
> 3 votes
# Funky, 55 bytes

```
s=>s::gsub("."c=>{0s.upper,s.lower}[math.random(2)](c))

```

Try it online!

Thanks to optional commas, it's one byte shorter to do `0s.upper` in the table definition, which means the `math.random` will randomly pick either `1` or `2`, than to do `math.random(0,1)` in the random and not have the `0`.

# Answer
> 3 votes
# , ~~60 59 58 57 56~~ 63 bytes

```
intToUtf8((s=utf8ToInt(scan(,"")))-32*rbinom(s,s%in%97:122,.5))

```

Try it online!

Different approach from the other two R answers here and here. Improved and fixed thanks to Giuseppe!

# Answer
> 3 votes
# Dyalog APL, ~~23~~ ~~18~~ ~~17~~ 14 bytes

This is a function which takes a string and returns it with random capitalization (as specified in the question).

```
{(?2)⌷⍵,1⎕C⍵}¨

```

**Edits:** Answer improved using suggestions by @LdBeth and @EliasMårtenson at the APL Orchard.

**New Edit:** Answer improved using suggestion by @Adam at APL Orchard.

# Answer
> 2 votes
## Alice, ~~17~~ 15 bytes

*Thanks to Leo for saving 2 bytes.*

```
/uRUwk
\i*&o.@/

```

Try it online!

### Explanation

```
/...
\...@/

```

This is the usual framework for largely linear programs operating entirely in Ordinal mode.

```
i    Read all input as a string.
R    Reverse the input.
&w   Fold w over the characters of the string. w is nullary which means it
     doesn't actually use the individual characters. So what this does is that
     a) it just splits the string into individual characters and b) it invokes
     w once for each character in the string. w itself stores the current
     IP position on the return address stack to begin the main loop which
     will then run N+1 times where N is the length of the string. The one
     additional iteration at the end doesn't matter because it will just
     output an empty string.
.    Duplicate the current character.
u    Convert it to upper case (does nothing for characters that aren't
     lower case letters).
*    Join the original character to the upper case variant.
U    Choose a character at random (uniformly).
o    Print the character.
k    If the return address stack is not empty yet, pop an address from it
     and jump back to the w.
@    Terminate the program.

```

I first tried doing this entirely in Cardinal mode, but determining if something is a letter just based on character code would probably take more bytes.

# Answer
> 2 votes
# Pyth, ~~10~~ ~~7~~ 6 bytes

```
smO,r1

```

Saved 3 bytes thanks to ovs and 1 thanks to Steven H.

Try it online

### Explanation

```
smO,r1
 m      Q   For each character in the (implicit) input...
   ,r1dd    ... get the capitalized version and the (implicit) character, ...
  O         ... and pick one at random.
s           Concatenate the result.

```

# Answer
> 2 votes
# Ouroboros, 25 bytes

```
i.b*)..96>\123<*?2*>32*-o

```

Try it here

The only fancy part is the control flow, `.b*)`. Let's talk about the rest first.

```
i..                    Get a character of input, duplicate twice
   96>                 Test if charcode greater than 96
      \                Swap with copy #2
       123<            Test if charcode less than 123
           *           Multiply the two tests (logical AND): test if it is lowercase letter
            ?          Random number between 0 and 1
             2*        Times 2
               >       Is lcase test greater? If test was 1 and rand*2 < 1, then 1, else 0
                32*-   Multiply by 32 and subtract from charcode to ucase lcase letter
                    o  Output as character

```

We then loop back to the beginning of the line. Control flow involves changing where the end of the line is; if it is moved to the left of the IP, execution terminates. Thus:

```
 .     Duplicate input charcode
  b*   Push 11 and multiply
    )  Move end of line that many characters to the right

```

When the charcode is positive, `)` is a no-op, since the end of the line is as far right as it can go. But when all characters have been read, `i` gives `-1`. Then we move the end of the code `-11` characters to the right--that is, 11 characters to the left. It takes a couple iterations, but eventually the IP is past the end of the code and the program halts.

# Answer
> 2 votes
# MATL, ~~12~~ 11 bytes

```
"@rEk?Xk]v!

```

Try it online!

Saved 1 byte thanks to @LuisMendo

# Answer
> 2 votes
# Brachylog, 5 bytes

```
ụᶻṛᵐc

```

Try it online!

### Explanation

```
Example input: "Test"

ụᶻ        Zip uppercase:      [["T","T"],["e","E"],["s","S"],["t","T"]]
  ṛᵐ      Map random element: ["T","e","S","T"]
    c     Concatenate:        "TeST"

```

# Answer
> 2 votes
# PowerShell, ~~57~~ 56 bytes

```
-join([char[]]"$args"|%{(("$_"|% *per),$_)[(Random)%2]})

```

Try it online!

*-1 byte thanks to briantist*

Takes input as a string, explicitly casts the `$args` array to a string, casts it as a `char`-array, then feeds the characters through a loop. Each iteration, we 50-50 either output the character as-is `$_` or convert it to upper-case `"$_".ToUpper()` (that's the `("$_"|% *per)` garbage). That's chosen by getting a `Random` integer and taking it mod `2`.

Those characters are left on the pipeline and then `-join`ed back together into a single string, which is itself left on the pipeline and output is implicit.

# Answer
> 2 votes
# PHP, ~~63~~ 53 bytes

```
while($a=$argv[1][$i++])echo rand()%2?ucfirst($a):$a;

```

Managed to reduce the code with 10 bytes by (partialy) following Titus' suggestion.

# Answer
> 2 votes
# Julia, 35 bytes

```
s->map(c->rand([c,uppercase(c)]),s)

```

Try it online!

Still pretty easy to read as a human. In Julia rand(A) returns a random element from A.

# Answer
> 2 votes
# APL (Dyalog Unicode), 28 bytes

28 bytes (https://github.com/abrudz/SBCS/)
50 bytes (UTF-8)

```
{1(819⌶)@(?n⍴⍨?n←≢⍸~⍵∊⎕A)⊢⍵}

```

Inspired by Graham's APL+Win solution

Try it online!

# Answer
> 2 votes
# Vyxal `s`, ~~6 5~~ 4 bytes

```
⇧Zv℅

```

#### Explanation:

```
⇧Zv℅    # main program

⇧       # converts the input to uppercase
 Z      # zips the implicit input with the uppercase version
  v℅    # vectorized choose over the list

s flag  # concats the stack and prints

```

Try it Online!

-2 (and fixed) thanks to @lyxal

# Answer
> 2 votes
# Python 3, ~~74~~ 66 bytes

*-8 bytes thanks to @Jakque*

```
lambda s:"".join(map(choice,zip(s.upper(),s)))
from random import*

```

Try it online!

# Answer
> 1 votes
# Rebol, 61 bytes

```
u:func[t][n: random length? t t/(n): uppercase t/(n) print t]

```

Test:

```
>>c: "Test sTring"
>>u c
Test sTriNg

```

# Answer
> 1 votes
# Jelly, 16 bytes

```
2ḶXø³L¤Ð¡ḊT
Œu¢¦

```

Try it online!

**Explanation**

```
2ḶXø³L¤Ð¡ḊT    First Link
2Ḷ             The list [0,1]
  X            Random element (1 is truthy, 0 is falsy)
   ø           Begin nilad
    ³L         Length of first input (the string)
      ¤        End nilad
       Ð¡      Random([0,1]) for each character in the input string and collect.
         Ḋ     The list had an extra None at the beginning. Don't know why. This removes it (the first element of the list)
          T    Get indices of all truthy

Œu¢¦           Main Link
Œu             Capitalize
   ¦           At the indices in the list:
  ¢            The first link as a nilad (list of indices)

```

I couldn't get this to work in a single line. I also don't know why, but `2ḶXø³L¤Ð¡` gives the list `[None,1,0,..,1]` with `0`s and `1`s chosen randomly. The `None` is the reason for the  in the first link.

# Answer
> 1 votes
# Pyth, 5 bytes

```
sOVr1

```

Try it here!

A translation of totallyhuman's Jelly answer.

Explanation:

```
sOVr1QQ  Implicit inputs.
   r1Q   Upper(input)
  V   Q  Zip with itself and map...
 O       Random choices between r1Q and Q.
s        Sum the results back into a string.

```

# Answer
> 1 votes
# Perl 6, 28 bytes

```
{S:g/.<?{rand>.5}>/{$/.uc}/}

```

Try it online!

`S:g/./{$/.uc}/` itself would convert every individual character to uppercase. Including the regex assertion `<?{rand > .5}>` assures that the replacement happens only half of the time.

# Answer
> 1 votes
# APL (Dyalog), 16 bytes

Tacit prefix function. Requires `⎕IO` (**I**ndex **O**rigin) to be `0`, which is default on many systems.

```
{?2:⍵⋄1(819⌶)⍵}¨

```

Try it online!

`{` apply the following function on each character:

`?2:` if random 0 or 1:

return the argument unmodified

else:

`1(``)⍵` apply the following function with 1 and the argument as arguments:

`819⌶` case-fold (left argument 1 means uppercase)

# Answer
> 1 votes
# Kotlin, 54 bytes

```
{it.map{if(Math.random()<.5)it else it.toUpperCase()}}

```

Try it online!

The type of this function is `(List<Char>) -> List<Char>`.

# Answer
> 1 votes
# Octave, 44 bytes

```
@(x)['',x-32*(x<123&x>96&rand(size(x))>.5)];

```

Try it online!

# Answer
> 1 votes
# Factor, 70 bytes

Oh, Factor, so awesomely verbose...

```
USING: sequences ascii random ; [ dup ch>upper 2array random ] map

```

It's a quotation (lambdas did count as functions, right?), takes a string in the stack, `call` (or `call( a -- b )` does its thing. Its thing is leaving a new string on the stack, with random capitalization.

```
"Capitalize on my Capitals in the Capital" swap call .
 -> "CaPItALIZe oN mY CAPitaLs iN The CAPiTAl"
"Capitalize on my Capitals in the Capital" swap call .
 ->"CaPItAliZe ON mY CApItAls in ThE CapiTal"
...

```

---

As a word with comments (because why not!):

```
USING: sequences ascii random ; ! import the relevant vocabs (factor does it for you in the
                                ! listener, but the rules)
: random-case ( s -- s' )   ! declaration: string -> string'
   [ dup                    ! make a quotation to:
     ch>upper               !  dup a character and make the dup upper
     2array                 !  put them in an array
     random ]               !  and picks one at random
   map ;                    ! now use that to do the thing

"The confusing case of mixed cases in a case!" random-case
 -> "The coNFUsinG case OF Mixed caSes In A CASE!"

```

# Answer
> 1 votes
# Python 3, 92 bytes

```
lambda x:''.join([i.upper() if getrandbits(1) else i for i in list(x)])
from random import*

```

I tried it out using list comprehension and `getrandbits` for a random sort. I'm not sure if there is a shorter way to get a random boolean, but I'd love to know because `getrandbits` looks ugly to me and with the import takes up a lot of bytes.

Try it online!

# Answer
> 1 votes
# Taxi,  ~~1183~~  1151 bytes

```
0 is waiting at Starchild Numerology.2 is waiting at Starchild Numerology.Go to Starchild Numerology: w 1 l 2 r, 1 l, 1 l, 2nd l.Pickup a passenger going to Firemouth Grill.Pickup a passenger going to Firemouth Grill.Go to Firemouth Grill: w 1 r 2 r 1 l 1 r.Go to Post Office: e 1 r.Pickup a passenger going to Chop Suey.[l]Go to Firemouth Grill: n 1 l.Pickup a passenger going to Cyclone.Go to Cyclone: w 1 l 1 r 2 r.Pickup a passenger going to Firemouth Grill.Pickup a passenger going to The Underground.Go to Zoom Zoom: n.Go to Firemouth Grill: w 3 l 2 l, 1 r.Go to The Underground: e 1 l.Switch to plan "k" if no one is waiting.Pickup a passenger going to Riverview Bridge.Go to Riverview Bridge: n 3 l.Go to Chop Suey: e 2 r.Pickup a passenger going to Auctioneer School.Go to Auctioneer School: s 1 r 1 l 3 r 1 l 1 l.Pickup a passenger going to Post Office."\0" is waiting at Writer's Depot.Go to Writer's Depot: n 1 l 1 r.Pickup a passenger going to Chop Suey.Go to Post Office: n 1 r 2 r 1 l.Switch to plan "l".[k]Go to Chop Suey: n, 2 r 1 l.Pickup a passenger going to Post Office.Go to Post Office: south, 1 r 1 l 2 r 1 l.Switch to plan "l".

```

Errors at end of input.

Try it online!

Ungolfed:

```
0 is waiting at Starchild Numerology.
2 is waiting at Starchild Numerology.
Go to Starchild Numerology: west, 1st left, 2nd right, 1st left, 1st left, 2nd left.
Pickup a passenger going to Firemouth Grill.
Pickup another passenger going to Firemouth Grill.
Go to Firemouth Grill: west, 1st right, 2nd right, 1st left, 1st right.
Go to Post Office: east, 1st right.
Pickup a passenger going to Chop Suey.
[loop]
Go to Firemouth Grill: north, 1st left.
Pickup a passenger going to Cyclone.
Go to Cyclone: west, 1st left, 1st right, 2nd right.
Pickup a passenger going to Firemouth Grill.
Pickup a passenger going to The Underground.
Go to Zoom Zoom: north.
Go to Firemouth Grill: west, 3rd left, 2nd left, 1st right.
Go to The Underground: east, 1st left.
Switch to plan "don't capitalize" if no one is waiting.
Pickup a passenger going to Riverview Bridge.
Go to Riverview Bridge: north, 3rd left.
Go to Chop Suey: east, 2nd right.
Pickup a passenger going to Auctioneer School.
Go to Auctioneer School: south, 1st right, 1st left, 3rd right, 1st left, 1st left.
Pickup a passenger going to Post Office.
"\0" is waiting at Writer's Depot.
Go to Writer's Depot: north, 1st left, 1st right.
Pickup a passenger going to Chop Suey.
Go to Post Office: north, 1st right, 2nd right, 1st left.
Switch to plan "loop".
[don't capitalize]
Go to Chop Suey: north, 2nd right, 1st left.
Pickup a passenger going to Post Office.
Go to Post Office: south, 1st right, 1st left, 2nd right, 1st left.
Switch to plan "loop".

```

Tricky things:

1. Although one cannot declare an empty string waiting, one can declare a null byte waiting, and that gets turned into an empty string, where it gets harmlessly dropped off at Chop Suey.
2. The whole hack is needed anyway to avoid running out of gas, because Auctioneer School is SO FAR AWAY from the rest of Townsburg.

# Answer
> 1 votes
# Japt `-m`, ~~5~~ 4 bytes

```
pu ö

```

Try it

```
pu ö     :Implicit map of each character of input string
p        :Append
 u       :  Uppercase
   ö     :Select random character

```

# Answer
> 1 votes
# Python 3, 59 bytes

```
i=input()
while i:print(end={i,i.upper()}.pop()[0]);i=i[1:]

```

Try it online!

Uses `set.pop()` to randomize. Note that this will only be random when used in a full program. Learn more.

The code can be reduced to a 47-byte function, but then it is only randomized once per input per session.

```
f=lambda i:i and{i,i.upper()}.pop()[0]+f(i[1:])

```

Try it online!

---

Or, alternatively, as a reusable function:

# Python 3, 70 bytes

```
from random import*
f=lambda i:i and choice((i,i.upper()))[0]+f(i[1:])

```

Try it online!

# Answer
> 1 votes
# Python 3, 114 107 bytes

```
from random import *
for i in input():
	if random()>0.5:
		print(i.upper(),end="")
	else:
		print(i,end="")

```

Try it online!

# Answer
> 1 votes
# Poetic \- 735 bytes

```
alphabet:a-z
words i say,i spell
i say a letter of ABCs
i do know A,i sorta do
then it begins to turn fuzzy or vague-it was never clear
is the after-A letter B
the thing after B?gosh,i am stupid
i say C
D after C?yes,i nailed it
i keep a tally
if i try,i am great
i say a letter,all in order of a song
i heard it,how a letter is in there:A,B,then C
vowels are not a worry for me
vowels are easy
i wrote a huge E in upper-case,and a letter F
i failed with consonant G
still,i say,i penned a big H,I,and J
after J came K,or maybe L
i almost am half completed with everything
just need this difficult novel to read
o sorry,i am stupid,it is truly quite long
M is after L
N,then O
after O is harder letters
letters which really confused me

```

Try it online!

Poetic is an esolang I made in 2018 for a class project. It's basically brainfuck with word-lengths instead of symbols.

The point of the language is to allow for programs to be written in free-verse poetry. I made this poem about being confused about the alphabet, because it sounds funny.

There is a command that generates a random byte from 0 to 255, but the hard part was calculating that byte mod 2, and capitalizing or not capitalizing based on the result. This is a slow way of doing it, and it takes a while to run in the online interpreter.

# Answer
> 1 votes
# 05AB1E, 4 bytes

*Ties Shaggy's Japt answer and Underslash's Vyxal answer for #1.*

```
uø€Ω

```

Try it online! Outputs as a list of characters.

```
uø€Ω  # full program
   Ω  # random character of...
  €   # each element of...
      # implicit input...
 ø    # with each character paired with corresponding character in...
      # implicit input...
u     # in uppercase
      # implicit output

```

# Answer
> 1 votes
# Ly, 42 bytes

```
&ir[:(123)Lf'`Gfp*:[pp509?Gfp0]p[p' -0]po]

```

Try it online!

Pretty straightforward logic here... For each character, checks to see if it's in `a-z`. If so, then it generates a random number in `0-9` and if that's less than `5`, it converts the character to uppercase.

```
&ir[:(123)Lf'`Gfp*:[pp509?Gfp0]p[p' -0]po] #
&ir                                        # Read input into stack, and reverse it
   [                                    o] # Loop over each, printing to consume from stack
    :(123)L                                # Duplicate char, push ("z"+1) and compare
           f                               # Flip top two, to pull char to top
            '`G                            # Push ("a"-1) and compare
               fp*                         # Flip, pop char, combine test results
                  :[         0]p           # "If/Then" codeblock, test is "ch in a-z"
                    pp                     # Clean up stack
                      509?G                # Generate random number, compare to 5
                           fp              # Flip and pop to delete the 5
                                [p   0]p   # "If/Then" codeblock, test is "rand<5"
                                  ' -      # Subtract 32 " " from char to make uppercase
                                        o  # Print the current codepoint as a character

```

# Answer
> 1 votes
# Knight, 42 bytes

```
;=xP Wx=xSxO+A-Ax*%R2*32&<96Ax>123Ax"\"T""

```

Try it online!

```
; = line PROMPT
# loop while line is non-empty
: WHILE line {
   ; OUTPUT(
     + ASCII(
         # Subtract from the ASCII of the first char of line
         - ASCII(line)
           # the product of
           *
             # rand() % 2
             % RANDOM 2
             # and the product of
             *
               # 'a' - 'A'
               32
                 # and islower(x) coerced to Number
                 & < 96 ASCII(x) > 123 ASCII(x)
          # or in short, islower(x) ? rand() % 2 * 32 : 0
      )
      # Backslash to suppress newline
      "\" # " # this comment is brought to you by SE syntax highlighting
    )
  # Then pop the first char from line
  # We actually abuse the NULL return value from
  # OUTPUT to shorten stuff.
  : = line SUBSTITUTE(line 0 1 "")
}

```

# Answer
> 1 votes
# Mathematica, 56 bytes

Thanks to @ovs's feedback, the answer was cut down to 56 bytes by mapping `Characters` over `ToUpperCase`.

```
""<>RandomChoice/@Thread[Characters/@{ToUpperCase@#,#}]&

```

**~~Mathematica, 60 bytes~~**

I feel like this can be shortened, especially the logic around `ToUpperCase` and `Characters`.

We save bytes by aliasing `Characters`, using `""<>"` over `StringJoin`, and using prefix notation.

```
c=Characters;""<>RandomChoice/@Thread@{c@ToUpperCase@#,c@#}&

```

Try it online!

# Answer
> 1 votes
# MathGolf, ~~7~~ 5 bytes

```
{_δαw

```

-2 bytes thanks to *@ovs*.

Try it online.

**Explanation:**

```
{      # Foreach over the characters in the (implicit) input-string:
 _     #  Duplicate the current character
  δ    #  Titlecase it
   α   #  Pair the two characters together
    w  #  Pop and push a random character from this pair
       # (after the loop, the entire stack is joined together and output implicitly)

```

# Answer
> 0 votes
# SOGL V0.12, 6 bytes

```
{1ψ⌡Up

```

Try it Here! \- the rest of the code there is the name of the function and calling of the function, as this expects the input on the stack.

Explanation:

```
{       for each character
 1ψ       push a random number from 0 to 1
   ⌡      that many times
    U       uppercase the letter
     p    print that character

```

# Answer
> 0 votes
# Pip, ~~12~~ 9 bytes

```
RC_.UC_Mq

```

Takes input from stdin. Try it online!

### Explanation

```
        q  Read a line of stdin
       M   Map this function to its characters:
RC           Random choice from
  _          The character
   .         Concatenated to
    UC_      The character, uppercased
           Autoprint the resulting list, by default joined into a string

```

# Answer
> 0 votes
# Haskell, 112 bytes

Two really expensive imports and one annoying type annotation :(

```
import Data.Char
import System.Random
mapM(\(b,c)->(c#)<$>randomRIO b).zip(repeat(0::Int,1))
a#1=toUpper a
a#_=a

```

Try it online!

# Answer
> 0 votes
# Befunge, 2x21 = 42 Bytes

```
~:1+!v >-# " "$#?+#_,
    @_::"`"`\"{"\`*^

```

Try It Online

### How it works:

```
~:1+!v
    @_

```

Gets input and ends program if empty.

```
      ::"`"`\"{"\`*^

```

Duplicates the input and checks whether it is in-between "\`" and "{", i.e the lowercase letter range

```
       >-# " "$#?+#_,

```

Randomly chooses between subtracting a " " to make it uppercase, or just printing the character as is before returning to the start

# Answer
> 0 votes
# Scala, 44 bytes

```
s.map(c=>if(math.random<.5)c.toUpper else c)

```

# Answer
> 0 votes
# AWK, ~~100~~ ~~79~~ 73 bytes

```
BEGIN{FS="";srand()}{for(;i++<=NF;){rand()>.5?$i=toupper($i):i;printf$i}}

```

Try it online!

# Answer
> 0 votes
# Cubix, 54 bytes

```
;'aW..@;.'zi?>o....;.;?-/..>;.>D<.\;>^u?-/.W;-;/S.;..u

```

Try it online!

Watch the interpreter in action!

The cost of checking whether a character is a lowercase letter or not in Cubix is quite high, but I'm happy I finally got to use `D` in a program!

For each lowercase letter in the input, there is a 50% chance that it will be uppercased, and a 50% chance it will be left alone.

Expands to the following cube:

```
      ; ' a
      W . .
      @ ; .
' z i ? > o . . . . ; .
; ? - / . . > ; . > D <
. \ ; > ^ u ? - / . W ;
      - ; /
      S . ;
      . . u

```

And a brief explanation of code flow is as follows:

```
'z               : push ascii z (122)
i                : read in input as code point, or -1 if end of input
?                : turn left if negative, turn right otherwise
 negative:
  @              : end program
/-               : reflect and subtract, result is negative if input is after z, positive if less, zero otherwise
?                : left if negative, right if positive, straight if zero
 negative:
  \;>^.          : pop top of stack and then head to output step
 positive:
  z              : no-op
  W              : jump left
  ;'a            : pop top of stack and push ascii a (97)
  /-             : reflect and subtract. Result is positive if input is between a-z exclusive, negative if before a and zero if a
  ?              : left if negative, right if positive, straight if zero
   negative:
    \;u;^        : stack manipulation and head to output step
   zero:
    u            : u-turn and head to positive branch
   positive:
    >            : point right
    ;            : pop top of stack
    >            : go right
    D            : D points IP in a random direction
    if D goes left or right it hits > or < respectively and re-enters the random phase
    if D goes down:
     W;          : jump left, pop top of stack
     S-          : push 32 (space) and subtract (convert to uppercase)
     >^          : ip directions to enter the output step
    if D goes up:
     ;           : pop top of stack
     '.;         : push . (46) then pop it immediately, then enter the output step
output:
 o.....;.        : output top of stack as char code and then goto beginning of program.

```

# Answer
> 0 votes
# APL NARS ~~81~~ ~~77~~ 54 characters

```
{1<⍴⍴⍵:¯1⋄⍬≡0↑⍵:¯1⋄⍵≡'':⍵⋄{26<c←⎕a⍳⍵:⍵⋄1=?2:c⌷⎕A⋄⍵}¨⍵}

```

This can run only in NARS, because it has defined both alphabet array ⎕A for 'A..Z' and ⎕a for 'a..z'. It is 90% sure I wrote something wrong because it is the 4 or 5th function I write in APL; if you note some error please report. I like this language, a little too much path idiomatic. Comments:

```
h←{1<⍴⍴⍵:¯1⋄⍬≡0↑⍵:¯1⋄⍵≡'':⍵⋄{26<c←⎕a⍳⍵:⍵⋄1=?2:c⌷⎕A⋄⍵}¨⍵}

h←          assign to name h its function, h return -1 for error
{1<⍴⍴⍵:¯1   if the argument ⍵ of h is  matrix or tensor return -1
 ⍬≡0↑⍵:¯1   if the argument ⍵ of h is a scalar numeric or vector numeric return -1
 ⍵≡'':⍵     if the argument ⍵ of h is the void string '' return it
  {   define one anonimous function in h with argument ⍵
        find in the vector ⎕a=a..z the index char ⍵, assign it to c
   26<c←⎕a⍳⍵:⍵
        if that index not exist [in this case must be c=27]return unchanged ⍵
   1=?2:c⌷⎕A
        now index is in 1..26, ⍵ is in a..z; if rand() in 1..2 is 1, return ⎕A[c] where ⎕A is A..Z
   ⋄⍵   else return the argument unchanged
¨⍵}         for each character argument ⍵ of h, apply anonimous function
            for build the result string and return it

```

results

```
  h
SYNTAX ERROR
  h
  ∧
  h 1
¯1
  h 1.23
¯1
  h 1 2 3
¯1
  h 2 3⍴1 2 3
¯1
  h ''

  h ' '

  h '  '

  h 'Hello World'
HElLo WOrlD
  h 'Hello World'
HELlo WoRlD
  h 'Hello World'
HELlO WoRLD
  h 'Hello World'
HeLLO WOrld
  h 'Hello World'
HEllO WORld

```

these it seems are scalars chars and some vector

```
  h 'a'
A
  h 'a'
a
  h 'a'
a
  h 'a'
a
  h ,'a'
A
  h ,'a'
A
  h ,'a'
a
  h ,''

```

# Answer
> 0 votes
# Julia, 56 bytes

```
f(s)=join(map(x->(rand(Bool)?uppercase:lowercase)(x),s))

```

Try it online!

# Answer
> 0 votes
# \>\<\>, 37 bytes

```
i:0(?;::84*\{?$~-o
+){$({"za" /0~x<0}

```

Try it online!

This program works by randomly selecting either 32 or 0, which will only be subtracted from the value of the letter if is in the range \[a-z\].

The program mostly linear, but I have 'folded' it to allow reuse of an `$` token. Here it is unfolded:

```
i:0(?;::84*"az"{(${)+}0>x~0{?$~-o
                        $

```

The `x` token causes the instruction pointer to move in one of the four cardinal directions, chosen at random. When the IP reaches the `x` token, the top of the stack has 0 and 32 on it. If the IP moves left, it hits a `>` which immediately returns the IP to the `x`. If it moves up or down, it hits the `$`, which swaps the 0 and 32 around, then returns to the `x`. If it moves right, it hits the `~`, discarding the value on the top of the stack and continuing with program execution.

To save on lots of wasted characters, the program is split, the middle flipped, and a reflector put inbetween:

```
i:0(?;::84*"az"{(${)+}0>x~0{?$~-o

i:0(?;::84*                {?$~-o
           "az"{(${)+}0>x~0

i:0(?;::84*                {?$~-o
           +){$({"za"0~x<0}

i:0(?;::84*\{?$~-o
+){$({"za" /0~x<0}

```

This puts a `$` directly above the `x`, recreating the program flow as described in the unfolded version.

# Answer
> 0 votes
## Bash, 65

`while IFS= read -N1 L;do((RANDOM%2))&&L="${L^}";echo -n "$L";done`

Example:

`while IFS= read -N1 L;do((RANDOM%2))&&L="${L^}";echo -n "$L";done<<<"Word string with spaces! and symbols if Desired."`

\> `WoRD stRINg WITh SPacEs! AND SymbOlS IF DESiRed.`

# Answer
> 0 votes
## F#, 104 bytes

```
open System
let r=Random()
let f=Seq.fold(fun a x->a+string(if r.Next 4=0 then Char.ToUpper x else x))""

```

Try it online!

Pretty straight-forward. Start with an empty string, then keep adding characters to it. Each character has a 1-in-4 chance of being capitalised.

I'm pretty sure I can get it under 100 bytes, but I can't see how...

# Answer
> 0 votes
# Prolog (SWI), 65 bytes

```
[H|T]-[I|U]:-T-U,(H>97,H<123,random(0,2,1),I is H-32;I=H).
[]-[].

```

Try it online!

# Answer
> 0 votes
# Common Lisp, ~~112~~ 91 bytes

```
(defun f(s)(map'string(lambda(c)(if(>(random 2(make-random-state t))0)(char-upcase c)c))s))

```

Try it online!

:| Lisp's `random` isn't seeded by default

# Answer
> 0 votes
# Gaia, 6 bytes

```
⌉,†ṛ¦$

```

Try it online!

### Explanation

```
⌉       Uppercase the string
 ,†     Vectorize pair the uppercase with the original string (creates pairs of corresponding chars)
   ṛ¦   Randomly choose one character from each pair
     $  Join
        Implicit output

```

# Answer
> 0 votes
# Factor, 33 bytes

```
[ [ .5 [ ch>upper ] whenp ] map ]

```

Try it online!

* `[ ... ] map` Transform each character in the input string using a quotation.
* `.5 [ ch>upper ] whenp` Call `ch>upper` with probability 0.5. `ch>upper` capitalizes a code point.

# Answer
> 0 votes
# Lua, 83 bytes

```
print((io.read():gsub(".",function(x)return.5>math.random()and x:upper()or x end)))

```

Try it online!

# Answer
> 0 votes
# Thunno 2 `J`, 4 bytes

```
RZ€ɼ

```

Attempt This Online!

Port of totallyhuman's Jelly answer.

#### Explanation

```
RZ€ɼ  # Implicit input  ->  "Hello World"
R     # Uppercase       ->  "HELLO WORLD"
 Z    # Zip with input  ->  ["HH","eE","lL","lL","oO","  ","WW","oO","rR","lL","dD"]
  €   # To each pair:
   ɼ  #  Random choice
      # Implicit output, joined

```

---
Tags: code-golf, string, random
---