title: Generate this expanding series

text:
# Question
Title: Generate this expanding series
# Challenge

Your task is to generate a string using this sequence:

```
1,1,2,1,1,2,3,2,1,1,3,2,4,2,3,1,....

```

Which is more understandable in this format:

```
1
1 2 1
1 2 3 2 1
1 3 2 4 2 3 1
1 4 3 2 5 2 3 4 1

```

The pattern increases the number of Digits in the string by two for each increment in the Value of N

**For each integer value up to the total N, *aside from 1*** the string is centred on the current value of N and bookended by the previous values of N in decreasing order on the left, and increasing order on the right - with the exception of the value 1, which bookends the entire string.

# Input

Number of steps

# Output

The series separated by comma

# Answer
# 05AB1E, 7 bytes

Port of the Jelly answer.

```
L¦ÁR1šû

```

Try it online!

# Explanation

```
L       1 .. N
 ¦      Tail
  Á     Shift right
   R    Reverse
    1š  Prepend 1
      û Palindromize

```

# 05AB1E, 9 bytes

If the whole format is necessary, here's one with 9 bytes. (Question: Does 05AB1E have any sort of implicit range?)

```
LεL¦ÁR1šû

```

Try it online!
> 3 votes

# Answer
# Jelly, ~~10~~ 10 ?8 bytes

```
Ḋṙ-U1;ŒB

```

Try it online!

I’m assuming you want the \\$n\\$th row of the pyramid. If you actually want the full sequence for the \\$n\\$th step, then it would be 10 bytes.

A monadic link taking an integer and returning a list of integers.

## Explanation

```
Ḋ        | List 1..(n-1)
 ṙ-      | Rotate right 1
   U     | Reverse list
    1;   | Prepend 1
      ŒB | Bounce (mirror

```
> 2 votes

# Answer
# Python 3.8 (pre-release), ~~86~~ ~~81~~ ~~58~~ 53 bytes

```
lambda n:[[1],[1,*(l:=range(2,n))[::-1],n,*l,1]][n>1]

```

Try it online! Hats off to @Noodle9 for saving me a *whooping* 23 bytes and thanks to @squid for saving me 5 bytes!
> 2 votes

# Answer
# Erlang (escript), 182 bytes

Unfortunately this became the longest solution over here...

```
q(I)->lists:join(" ",[integer_to_list(X)||X<-lists:seq(2,I-1)]).
x(0)->"";x(I)->x(I-1)++"\n"++if I>1->"1 "++lists:reverse(q(I))++" "++integer_to_list(I)++" "++q(I)++" 1";1<2->"1"end.

```

Try it online!
> 1 votes

# Answer
# JavaScript (ES6),  ~~68~~  65 bytes

Returns the whole sequence after \\$n\\$ iterations.

```
f=n=>--n?[...f(n),1,...(g=k=>k>1?[k,...g(k-1),k]:[n+1])(n),1]:[1]

```

Try it online!

---

# JavaScript (ES6),  ~~53~~  46 bytes

Returns the \\$n\\$th row of the pyramid.

```
n=>(g=k=>k>1?[k%n||1,...g(k-1),k%n||1]:[n])(n)

```

Try it online!
> 1 votes

# Answer
# C# (Visual C# Interactive Compiler), 145 bytes

```
n=>{var s= "";for(int i=0;i++<n;){for(int j=1;++j<=i;)s+=(j>2?i-j+2:1)+",";s+=i;for(int j=i;j-->1;)s+=","+(j>1?i-j+1:j);s+=i<n?",":"";}return s;}

```

Try it online!

Function generating whole series.
> 1 votes

# Answer
# Jelly, 11 bytes

(9 if we only require the \\$n^{\text{th}}\\$ row of the "understandable format" - remove `)F`)

```
,2œṖRUFŒB)F

```

A monadic link accepting an integer, the number of steps, which yields a list of integers, the series up to and including that step.

**Try it online!**
> 1 votes

---
Tags: code-golf, math
---


title: Bot Factory KoTH

text:
# Question
Title: Bot Factory KoTH
**Note:** Bot Factory KoTH (2.0) is now posted; you're probably looking for that one instead!

In this challenge, bots (consisting of JS functions) move around an infinite factory (playing field), collecting characters (UTF-16). These characters can be used to build worker bots, or droppedfor other bots to pick up.

## Results

Average number of characters collected per game (20k rounds)

```
[1484.5] The Forsaken Farmer
[1432.9] The Replicator
[957.9] Safe Player V2
[739.1] Hunter
[101.65] First
[9.75] IDKWID

```

## The Factory

All bots start out randomly placed around the center of the factory, `[0, 0]`, where coordinates are arrays `[x, y]`. North is -Y, and west is -X. Each round consists of up to 100000 turns. A bot may move one space in any cardinal direction (or build a worker, or drop a character) per turn.

Bots can move by returning `north()`, `east()`, `south()`, or `west()`.

## Characters

Characters will be randomly distributed, centered around `[0, 0]`. There are always up to a total of 4 characters per bot at any given time (excluding those from dead bots).

Character's positions may overlap, and their character value (such as `a` or `(`) is selected from a pool of the source code of every bot and worker currently in the factory.

Bots collect characters by moving into the same position in the factory, and these collected characters are stored within the bot.

Bots may also drop a character they have previously collected in any of the four cardinal directions. This character is then removed from the bot's collected characters array.

Bots drop characters by returning `drop.north(c)`, `drop.east(c)`, `drop.south(c)`, or `drop.west(c)`, where `c` is a string.

## Score

Bots have a score, which is initially `-floor(sqrt(LEN))`, where `LEN` is the length of the bot's source code in characters. Worker bots start with a score of 0 regardless of their length.

Whenever a character is collected, this score value increments; when a character is dropped, it decrements.

## Collisions

When two or more bots collide (occupy the same position), whichever has the highest score survives (if there is a tie, none survive). All bots that die "drop" the characters they have collected, which are randomly distributed centered around the position they collided in.

Bots can switch places by moving into each others' previously occupied positions without colliding.

## Workers

Bots can use the characters they have collected to build a worker bot. A worker bot's source code (provided as a function or arrow function) must be entirely made up of characters its owner has collected, which are then removed. Half of the length of the worker's source code is deducted from the owner's score.

Worker bots are placed randomly around the position of their owner, using the same system as characters, and are not immune to collision. Worker bots can also build worker bots, whose owner would be the worker.

Workers can be built by returning the result of the function `build(source)`, where `source` is a string. If the bot cannot be built (such as not having all necessary characters), nothing happens.

## Functions

All bots are functions. They are provided a single argument, an object that can be used for storage, and can access information about other bots and characters using the following functions:

* `bots()`: Returns an array of bots (as objects)
* `chars()`: Returns an array of characters (as objects)
* `self()`: Returns the bot that called it (as an object)
* `owner()`: Returns the owner of the bot that called it (as an object, `null` if owner is dead, or `self()` if no owner)

A bot object has the following properties:

* `uid`: An integer ID unique to each bot, randomly selected
* `owner`: The UID of the bot's owner
* `score`: The score of the bot
* `pos`: The position of the bot formatted as `[x, y]`

A bot object also has the following properties if it is the owner or worker of the bot:

* `chars`: An array of characters the bot has collected
* `source`: A string with the bot's source code

A character object has the following properties:

* `char`: A string
* `pos`: The position of the character formatted as `[x, y]`

There are also the following library functions:

* `center()`: Get average of bots' positions weighted by score
* `turn()`: Get current turn (starts at 0)
* `dir(from, to)`: Get direction from `from` to `to`, which should be arrays formatted `[x, y]`
* `dirTo(pos)`: Same as `dir`, uses `self().pos` as `from`
* `dist(from, to)`: Get taxicab distance from `from` to `to`, which should be arrays formatted `[x, y]`
* `distTo(pos)`: Same as `dist`, uses `self().pos` as `from`

## Winning

Once all surviving bots are direct or indirect workers of the same initial bot, characters will no longer generate. Games automatically end when all characters are collected.

The winner is the bot which, after some number of rounds, has collected (or had workers collect) the most characters.

## Rules

* Bots may not use global variables in a way which produces side effects other than intended (such as to sabotage other bots or the controller)
* Bots which error will be killed and drop their characters
* Bots may only attempt to build workers which are valid functions
* Bots may not take an unnecessarily long time to run (no hard limitation, but be reasonable)
* Bots may not team with other which do not originate from the same owner (directly or not)

## Technical Notes

* Character and bot spawning radius is based on a geometric distribution (`p=0.1`), with a random angle. The resulting coordinates are truncated to integers. Repeated until a position is found with no bots within a taxicab distance of 4
* For dead bots' drops, `p=0.2` and there is no distance requirement
* For worker bot spawning, minimum taxicab distance is 3 for the owner
* Every time a character is picked up, one attempt is made to generate another. An attempt will only fail if there are already `4 * botCount` characters not dropped by a bot (or a bots' death), where `botCount` is the total number of alive bots (including workers). `4 * botCount` characters are generated at the start.

## Example Bot

ExampleBot uses an arrow function to keep its starting score higher, but still isn't well golfed. It likes characters which are in the middle of the action, which it finds by sorting the `chars()` array and using the `dist` and `center` library functions. It will not be included in the competition game.

```
() => dirTo(chars().sort((a, b) => dist(center(), a.pos) - dist(center(), b.pos))[0].pos)

```

**Controller:** https://gist.github.com/Radvylf/31408373bae12843bfbf482188653a42

**Edit:** Fixed the controller. Made a few changes before putting it in the gist to clean up some debugging and deleted a few things by mistake. Sorry about that, should be up and running!

**Due Date:** Challenge completed

**Prize:** Bounty (100 reputation)

**Chatroom:** https://chat.stackexchange.com/rooms/105613/bot-factory-koth

# Answer
# The Forsaken Farmer

This entry finds the nearest character and then proceeds to repeatedly drop it and pick it up, netting a total of 1 score per two moves... except it doesn't, because the spec was updated to account for that. No matter, though - winning is dependent on character pick up count, not score.

```
_=>(c=self().chars).length?drop.west(c[0]):dirTo(chars().sort((a,b)=>(d=distTo)(a.pos)-d(b.pos))[0].pos)

```
> 1 votes

# Answer
# Safe Player V2

```
_=>dirTo((f=(t,z)=>chars().flatMap(c=>t.reduce((a,b)=>a-(dist(b.pos,p=c.pos)<=(d=distTo)(p)),z)?[]:[p]).sort((a,b)=>d(a)-d(b))[0])(a=bots(),1)||f(a.filter(b=>b.score>self().score),0)||[0,0])

```

Finds the closest character that it can get to first and goes towards it. If no such character exists, it repeats the process but this time ignoring bots with a lower score than itself. Goes to the center if it still can't lock onto any character.
> 2 votes

# Answer
# IDKWID

Short for "I don't know what I'm doing".

```
_=>dirTo(chars().sort(distTo)[0].pos)

```

~~Greedily tries to get the closest character to it. I think.~~ A couple of minutes of thinking have led me to believe that this is not the case. It does something stupid instead. Often loses to Example Bot.
> 1 votes

# Answer
# The Replicator

~~Presumably replicates itself... very slowly.~~ Probably replicates itself, but if I'm understanding the situation correctly, then a replication attempt currently crashes the runner (`hasChars is not defined at runTurn (<anonymous>:205:33)`). Rudimentarily code-golfed.

```
_=>{d=distTo;c=s=>s.reduce((a,v)=>({...a,[v]:(a[v]|0)+1}),{});s=self();a=c(s.chars);b=c((s=s.source).split``);for(v in b)if(!(b[v]<=a[v]))return dirTo(chars().sort((a,b)=>d(a.pos)-d(b.pos))[0].pos);return build(s)}

```
> 1 votes

# Answer
# First

```
_=>dirTo(chars()[0].pos)

```

Just go towards the first char. This has an initial score of -4, much better than most.
> 0 votes

# Answer
# Hunter

This bot will go towards the closest object that is a char or a bot with less score than it.

```
_=>dirTo((chars().concat(bots().filter(b=>b.score<self().score))).sort((a,b)=>distTo(a.pos)-distTo(b.pos))[0].pos)

```
> 0 votes

---
Tags: king-of-the-hill, javascript
---


# Question
Title: Convert a string to upper case without using built in methods/functions
# Challenge

You will be given a string as an argument. You need to convert that string to upper case. But you can't use any built in method or function nor any external programs.

# Rule

No use of built in methods or functions or external programs. Only arithmetic, bitwise, logical operators, regex, replace, split, join, ASCII codes are allowed.

# Input

The string as an argument. The string can contain spaces and special characters.

# Output

The string in upper case.

This is so shortest code wins.

# Answer
# Japt, 5 bytes

```
;dCíB

```

Try it here
> 2 votes

# Answer
# Batch, ~~245~~ 116 Bytes

```
@Set v=%~1
@for %%A in (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z)do @call set v=%%v:%%A=%%A%%
@ECHO(%v%

```

Somewhat ugly and brute forced, using a for loop to enact substring modification on each instance of a character. 129 bytes dropped thanks to Neil
> 1 votes

# Answer
# Turing Machine Code, 279 bytes

```
0 q Q r 0
0 w W r 0
0 e E r 0
0 r R r 0
0 t T r 0
0 y Y r 0
0 u U r 0
0 i I r 0
0 o O r 0
0 p P r 0
0 a A r 0
0 s S r 0
0 d D r 0
0 f F r 0
0 g G r 0
0 h H r 0
0 j J r 0
0 k K r 0
0 l L r 0
0 z Z r 0
0 x X r 0
0 c C r 0
0 v V r 0
0 b B r 0
0 n N r 0
0 m M r 0
0 _ _ r 0
0 * * r 0

```

Try it online!
> 1 votes

# Answer
# Keg, 14 bytes

```
(&az⑻•[& -|&],

```

Try it online!

Finally! A challenge Keg was designed for! This utilises the fact that a) subtracting 32 from the ordinal value of any lower-case letter gives its upper-case counterpart and b) characters are treated as numbers when arithmetic is applied.

The unicode part is to ensure the letter is in the lower case range, without using built-ins.
> 1 votes

# Answer
# Erlang (escript), 56 bytes

Numeric lists are strings in Erlang. (9 bytes away from C, let's see if I can get this shorter.)

```
f([H|T])->[H-if H>97,H<122->32;1<2->0end]++f(T);f(N)->N.

```

Try it online!

## Explanation

f([H | T]) -> % Try to split the input into head & tail
[H -          % Subtract the current item by:
if
  H > 97, H < 122 -> 32;
              % If the item's ord code is in the lowercase letter range:Return 32
  1 < 2 -> 0  % Otherwise, return 0. 1<2 is 1 byte shorter than true.
end
] ++ f(T);    % Concatenate with the uppercased tail

f(N) -> N.    % If the tail is the null list (i.e. it can't be splitted):
              % Return this operand.
```
</code></pre>
> 1 votes

# Answer
# 05AB1E, ~~8~~ 5 bytes

(Once again, a'\_' uses something that I didn't know even existed in 05AB1E.)

```
AžpR‡

```

## Explanation

```
       # Implicit input
A      # Push lowercase alphabet
 žp    # Push uppercase alphabet reversed
   R   # And reverse it again
    ‡  # Transliterate
     J # Join list

```

Try it online!

# Original solution without ‡, ~~19~~ 18 bytes

```
εDAskD®ÊižpRèës}}J

```

Try it online!

## Explanation

```
                   # Implicit input
ε               }  # Loop on each character
εD              }  # Duplicate
ε A             }  # Push lowercase alphabet
ε  s            }  # Swap
ε   k           }  # Find index of character in alphabet
ε    D          }  # Duplicate for comparison
ε     ®         }  # Push -1 (see link below)
ε      Ê        }  # Check if equal
ε       i    ë }}  # If-else statement
ε       ižp  ë }}  # Push uppercase alphabet in reverse
ε       i  R ë }}  # Reverse the string (so now it's just the uppercase alphabet)
ε       i   èë }}  # Index the uppercase alphabet
ε       i    ës}}  # Swap to get character
                 J # Join all the items

```

If you're wondering why `®` returns -1, go here
> 1 votes

# Answer
# , 54 bytes

Thanks to @PkmnQ for pointing out the bug!

```
3.6993269897697017008003010098801100009960100950070094

```

Try it online!

# , 28 bytes (old answer, only supports lower case and nothing else XD)

```
3.69932700800100009950070094

```

Try it online!
> 1 votes

# Answer
# Bash \+ core utilities, 10 bytes

```
tr a-z A-Z

```

Try it online!
> 1 votes

# Answer
# C (gcc), <sup>~~47~~</sup> 45 bytes

Saved 2 bytes thanks to ceilingcat!!!

```
f(char*s){for(;*s;++s)*s^=*s>96&*s<123?32:0;}

```

Try it online!
> 1 votes

# Answer
# APL+WIN, 28 bytes

Prompts for string:

```
⎕av[i-32×(i←⎕av⍳⎕)∊(97+⍳26)]

```

Converts string to relevant indices in APL's atomic vector, identifies indices of lower case letters, decrements only those indices by 32 and converts resulting string back to characters.
> 0 votes

# Answer
# Charcoal, 9 bytes

```
⭆Ｓ§⁺αι⌕βι

```

Try it online! Link is to verbose version of code. Only 7 bytes longer than the built-in! Explanation:

```
 Ｓ          Input string
⭆           Map over characters and join
      ⌕     Find index in
       β    Lowercase alphabet of
        ι   Current character
  §         Cyclically index into
   ⁺        Concatenation of
    α       Uppercase alphabet
     ι      Current character
            Implicitly print

```

If the input character is not found in the lowercase alphabet, the returned index is `-1`, which represents the last character when passed to the cyclic index function.
> 0 votes

# Answer
# Retina, 5 bytes

```
T`l`L

```

Try it online!

`T`ransliterate lower case `l`etters into upper case `L`etters.
> 0 votes

# Answer
## 16/32/64-bit x86 assembly language, 17 bytes

```
AC    l1: lodsb
3C 61     cmp   al, 'a'
72 06     jb    l2
3C 7A     cmp   al, 'z'
77 02     ja    l2
24 DF     and   al, 0dfh ;convert to uppercase
AA    l2: stosb
84 C0     test  al, al
75 F0     jne   l1
C3        ret
```

Call with (r/e)si pointing to source string, (r/e)di to destination buffer to hold converted text.
> 0 votes

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


title: All aboard the factorial train

text:
# Question
Title: All aboard the factorial train
# The system

Assume the Earth is flat and that it extends infinitely in all directions. Now assume we have one infinitely long train railway and `n` trains in that railway. *All* trains have different speeds and *all* trains are going in the same direction. When a faster train reaches a slower train, the two trains connect (becoming a single train) and the new train keeps going at the speed with which the slower train was going.

E.g., if we have two trains, one going at speed 1 and another at speed 9, the lines below "simulate" what would happen on the railway:

```
9               1
         9       1
                 11
                  11
                   11

```

whereas if the trains start in a different order, we'd have

```
1 9
 1         9
  1                 9
   1                          9
etc...

```

With that being said, given a train/position/speed configuration there comes a time when no more connections will be made and the number of trains on the railway stays constant.

# Task

Given the number `n` of trains in the railway, your task is to compute the *total* number of trains there will be on the railway, after all the connections have been made, summing over all `n!` possible arrangements of the `n` trains.

A possible algorithm would be:

* Start counter at 0
* Go over all possible permutations of the train speeds
    + Simulate all the connections for this permutation
    + Add the total number of remaining trains to the counter
* Return the counter

**Note** that you can assume the train speeds are whatever `n` distinct numbers that you see fit, what really matters is the relationships between train speeds, not the magnitudes of the differences in speeds.

# Input

You must take `n`, a positive integer, as input.

# Output

An integer representing the total number of trains that there will be on the railway, summed over all possible permutations of the trains.

# Test cases

```
1 -> 1
2 -> 3
3 -> 11
4 -> 50
5 -> 274
6 -> 1764
7 -> 13068
8 -> 109584
9 -> 1026576
10 -> 10628640
11 -> 120543840
12 -> 1486442880
13 -> 19802759040
14 -> 283465647360
15 -> 4339163001600
16 -> 70734282393600
17 -> 1223405590579200
18 -> 22376988058521600
19 -> 431565146817638400
20 -> 8752948036761600000

```

---

This is so shortest submission in bytes, wins! If you liked this challenge, consider upvoting it! If you dislike this challenge, please give me your feedback. Happy golfing!

# Answer
# Jelly,  ~~5~~  4 bytes

```
!:RS

```

**Try it online!** Or see the test-suite.

### How?

When we introduce an \\$n^{\text{th}}\\$ train it allows:

* \\$(n-1)!\\$ states - by being placed behind none of the \\$n-1\\$ existing trains and being faster than all of them.
* all the previous end states, each in \\$n\\$ different ways - by being placed behind at least one existing train and being faster than \\$\[0,n-1\]\\$ of the \\$n-1\\$ existing trains

We know \\$a(1) = 1\\$ so...

```
n  a(n)
1  1
2  1! + 1*2
3  2! + 1!*3 + 1*2*3
4  3! + 2!*4 + 1!*3*4 + 1*2*3*4
5  4! + 3!*5 + 2!*4*5 + 1!*3*4*5 + 1*2*3*4*5
... etc

```

Which is:

```
n  a(n)
1  1
2  1 + 2
3  1*2 + 1* 3 + 2*3
4  1*2*3 + 1*2* 4 + 1* 3*4 + 2*3*4
5  1*2*3*4 + 1*2*3* 5 + 1*2* 4*5 + 1* 3*4*5 + 2*3*4*5
...
n  n!/n + n!/(n-1) + n!/(n-2) + ... + n!/1

```

Hence the code:

```
!:RS - integer, n
!    - (n) factorial      n!
  R  - range (n)          [1,...,n-2,n-1,n]
 :   - integer division   [n!/1,...,n!/(n-2),n!/(n-1),n!/n]
   S - sum                a(n)

```
> 9 votes

# Answer
# JavaScript (ES6), 34 bytes

```
f=n=>n>1?(n+--n)*f(n)-n*n*f(n-1):n

```

Try it online!

This is an implementation of the recurrence relation:

$$\cases{ a(0)=0\\ a(1)=1\\ a(n) = a(n-1) \times (2n - 1) - a(n-2) \times (n - 1)^2,\\:n\>1}$$
> 4 votes

# Answer
# APL (Dyalog), 5 bytes

```
+/!÷⍳

```

Try it online!

Calculates the sum of (`+/`) the factorial of \\$n\\$ (`!`) divided by (`÷`) the range 1 to \\$n\\$ ().
> 4 votes

# Answer
# Wolfram Language (Mathematica), 15 bytes

```
Tr[#!/Range@#]&

```

*-1 byte from @Greg Martin*

Try it online!
> 3 votes

# Answer
# 05AB1E, 5 bytes

```
!IL÷O

```

Try it online!
> 3 votes

# Answer
# Python 3, 57 bytes

```
f=lambda n:n and n*f(n-1)+math.factorial(n-1)
import math

```

Try it online!

Implements the recurrence relation given by

$$\begin{cases}a(n) = n\times a(n-1) + (n-1)! \\ a(0) = 0 \end{cases}$$

**How**: If you have \\$n\\$ trains on the railway, consider removing the faster one from the railway and take the \\$(n-1)!\\$ permutations of the remaining \\$n-1\\$ trains. For each permutation of the \\$n-1\\$ trains, there are \\$n\\$ places where you can put the \\$n\\$th train, the fastest one.

* If you put it in the front, then the connections made by the other \\$n-1\\$ trains remain exactly the same, and those never catch up with the faster train. So placing it in the front adds a new train to the total sum.
* If you put it in any other of the \\$n - 1\\$ positions, it will just connect to the train in front and then we are back at the case when we had \\$n - 1\\$ trains on the railway, so the total number of trains stays the same.
> 3 votes

# Answer
# Python 3.8,  ~~50~~  49 bytes

-1 thanks to Surculose Sputum (using walrus in 3.8 to save some `~-`s)

```
f=lambda n:n>1and(2*n-1)*f(n:=n-1)-n*n*f(n-1)or n

```

**Try it online!**

---

A **52** using a different approach:

```
f=lambda n,k=2:n*k and~-n*f(n-1,k)+f(n-1,k-1)or n==k

```

Try it online!
> 3 votes

# Answer
# Python 2, ~~57~~ ~~52~~ 50 bytes

*-2 bytes thanks to @JonathanAllan !*

```
i=x=0
f=1
exec"i+=1;x=i*x+f;f*=i;"*input()
print x

```

Try it online!

---

**If the sequence is 0-indexed, we can cut down 2 more bytes**

## Python 2, 48 bytes

```
i=x=f=1
exec"i+=1;x=i*x+f;f*=i;"*input()
print x

```

Try it online!

---

**How:** This solution uses the `exec` trick, which repeats the code `n` times, then `exec` the repeated code.

`f` is the current factorial.
`x` (the solution function) is defined by the recurrent relation:
$$x(i)=ix(i-1)+(i-1)!$$
and
$$x(0)=0$$

@RGS's answer has a really nice explanation for this formula.
> 2 votes

# Answer
# Charcoal, 12 bytes

```
≔…·¹ＮθＩΣ÷Πθθ

```

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

```
≔…·¹Ｎθ

```

Create a range from `1` to `n`.

```
    θ   Range `1`..`n`
   Π    Product i.e. `n!`
  ÷     Vectorised divide by
     θ  Range `1`..`n`
 Σ      Sum
Ｉ       Cast to string
        Implicitly print

```
> 2 votes

# Answer
# Perl 6, 22 bytes

```
{sum [*]($_)X/$_}o^*+1

```

Try it online!

Returns the sum of the factorial of \\$n\\$ divided by the range 1 to \\$n\\$.
> 1 votes

# Answer
# `j`, ~~5~~ 4 bytes

After scanning through the source, I realized an undocumented feature - the `j` flag can actually sum the output at the end!

```
7Uëÿ

```

Uncompressed:

```
*rak/

```

## Explanation

```
*r     % Reduce via multiplication
       % (Contains implicit range)
  ak   % Range from input to 1
    /  % Division (integer division when
       % none of the operands are floating-points)
Flag:j % Sum the resulting list

```
> 1 votes

# Answer
# , 9 bytes

```
1#.!%1+i.

```

Try it online!

```
1#.           the sum of (by conversion to base 1)
   !          n factorial
    %         divided by
     1+i.     the list 1..n

```

# K (oK), ~~16~~ 12 bytes

-4 bytes thanks to ngn!

```
+/*/'1+&:'~=

```

Try it online!
> 1 votes

# Answer
# Haskell, 34 bytes

```
a 0=0
a n=n*a(n-1)+product[1..n-1]

```

Try it online!

This implements the OEIS definition.
> 1 votes

# Answer
# C (gcc), 38 bytes

```
f(n){n=n>1?(n+n--)*f(n)-n*n*f(n-1):n;}

```

Port of Jonathan Allan's Python 3.8 answer.

Try it online!
> 1 votes

# Answer
# Jelly, 9 bytes

```
Œ!«\€Q€FL

```

Try it online!

this is the non-smart trivial approach

# Explanation

Observe that if we have a list of trains' speeds, moving left, then we can cumulatively reduce by minimum to get the final list of trains' speeds.

```
Œ!«\€Q€FL  Main Link
Œ!         all permutations (defaults over a range)
    €      For each permutation
   \       Cumulatively reduce by
  «        minimum
      €    For each permutation
     Q     remove duplicate values
       F   join all of the trains (flatten)
        L  and get the final length

```
> 0 votes

# Answer
# Japt `-x`, 5 bytes

```
ÆÊ/°X

```

Try it
> 0 votes

# Answer
# C (gcc), <sup>~~70~~ \\$\cdots\\$ ~~64~~</sup> 63 bytes

Saved a byte thanks to ceilingcat!!!
Saved a byte thanks to Surculose Sputum!!!

```
l;c;i;t;f(n){l=0;for(c=i=1;i<n;l=c,c=t)t=-l*i*i+c*(i+++i);n=c;}

```

Try it online!

Uses Arnauld's formula.
> 0 votes

# Answer
# Racket, 70 bytes

```
(λ(x)(let([a(range 1(+ 1 x))])(apply +(map(λ(y)(/(apply * a)y))a))))

```

Try it online!
> 0 votes

# Answer
# Factor, 61 bytes

```
: f ( n -- n ) [1,b] dup [ product ] dip [ / ] with map sum ;

```

Try it online!
> 0 votes

# Answer
# MathGolf, 5 bytes

```
╒k!╠Σ

```

Try it online.

Or

```
!k╒/Σ

```

Try it online.

**Explanation:**

```
╒      # Push a list in the range [1, (implicit) input-integer]
 k!    # Push the input-integer again, and pop and push its factorial
   ╠   # Divide the factorial by each value in the list (b/a builtin)
    Σ  # And sum that list
       # (after which the entire stack joined together is output implicitly as result)

!      # Push the factorial of the (implicit) input-integer
 k╒    # Push the input-integer again, and pop and push a list in the range [1, input]
   /   # Divide the factorial by each value in the list
    Σ  # And sum that list
       # (after which the entire stack joined together is output implicitly as result)

```
> 0 votes

---
Tags: code-golf, integer, combinatorics
---


title: Quotes around sequence of chars

text:
# Question
Title: Quotes around sequence of chars
## Challenge

Your goal is to write a function that puts quotes around a sequence of capital letters in a string.

## So some examples (everything on the left (before function) and right (after function) are STRINGS):

`Hello the name's John Cena` -\> `"H"ello the name's "J"ohn "C"ena`

`I got BIG OLD truck` -\> `"I" got "BIG" "OLD" truck`

`[OLD, joe, SMOE]` -\>`["OLD", joe, "SMOE"]`

`'BIG')` -\> `'"BIG"')`

`fOOd` -\> `f"OO"d`

`"78176&@*#dd09)*@(&#*@9a0YOYOYOYOYOYOOYOYOYOY28#@e` -\> `"78176&@*#dd09)*@(&#*@9a0"YOYOYOYOYOYOOYOYOYOY"28#@e`

## Assumptions and Clarifications

* The sequence of capital letters can have a length of one (e.g. a string containing one character: H -\> "H")
* You can assume there will be only a string inputted.

## Winning Criteria

Code golf, fewest bytes wins.

# Answer
> 4 votes
# Perl 5, 15 bytes

```
s/[A-Z]+/"$&"/g

```

Try it online!

# Answer
> 3 votes
# 05AB1E, 13 bytes

```
0.ø.γ.u}'"ý¦¨

```

Try it online!

```
0.ø              # surround input string with 0s
   .γ  }         # group characters by:
     .u          #  is uppercase?
        '"ý      # join groups with quotes
           ¦¨    # remove the first and last characters (0s)

```

# Answer
> 3 votes
# JavaScript (ES6),  ~~32~~  30 bytes

### Using a reference to the last match

*Version suggested by @Grimmy*
*Saved 2 bytes thanks to @Shaggy*

```
s=>s.replace(/[A-Z]+/g,'"$&"')

```

Try it online!

# JavaScript (ES6), 35 bytes

### With a callback function

```
s=>s.replace(/[A-Z]+/g,s=>`"${s}"`)

```

Try it online!

# Answer
> 3 votes
# Gema, 8 characters

```
<K>="$0"

```

Sample run:

```
bash-5.0$ gema '<K>="$0"' <<< 'Hello the name’s John Cena'
"H"ello the name’s "J"ohn "C"ena

```

Try it online!

# Answer
> 2 votes
# Python 3, 47 bytes

```
lambda s:re.sub('([A-Z]+)',r'"\1"',s)
import re

```

Try it online!

# Answer
> 2 votes
# Japt, 11 bytes

```
r"%A+"`"$&"

```

Try it

# Answer
> 2 votes
# sed, ~~26~~ 21 bytes

Saved 5 bytes thanks to Xcali!!!

```
s/[[:upper:]]\+/"&"/g

```

Try it online!

# Answer
> 2 votes
# Pyth, 20 bytes

Blatant port of RGS's Python answer. (I relized that I posted to the wrong challenge, whoops!)

```
:Q"([A-Z]+)""\"\\1\"

```

Try it online!

# Answer
> 1 votes
# Retina, 11 bytes

```
[A-Z]+
"$&"

```

Try it online!

I thought Retina has a shortcut for `[A-Z]` but apparently that only works in transliterations and not substitutions? Hmm...

# Answer
> 1 votes
# , 34 bytes

```
gsub("([A-Z]+)","'\\1'",scan(,''))

```

Try it online!

Simple use of Regular Expressions.

# 39 bytes

```
cat(gsub('([A-Z]+)','"\\1"',scan(,'')))

```

Try it online!

This method is the only way I can get the double quotes to work.

# Answer
> 1 votes
# V (vim), 9 bytes

```
Í¨õ«©/"±"

```

**Try it online!**

This instructs Vim to replace all occurrences on all lines (`Í`)
...using the substitution `\(\u\)\+/"\1"`. Each `\x` may be replaced by `x` with the high-bit set, thus `\1` becomes `±`, etc...

# Answer
> 1 votes
# C (gcc), <sup>~~100~~ \\$\cdots\\$ ~~74~~</sup> 72 bytes

Saved ~~21~~ 23 bytes thanks to ceilingcat!!!
Saved a byte thanks to S.S. Anne!!!

```
t;u;f(int*s){for(t=1;*s;printf(s++),t=u)(u=*s<65|*s>90)^t&&putchar(34);}

```

Try it online!

Uses `wchar_t` strings for input.

# Answer
> 1 votes
# QuadR, 10 bytes

Port of @Adám's answer.

```
[A-Z]+
"&"

```

Try it online!

# Answer
> 1 votes
# Keg, 31 bytes

```
0&?(:A$Z$•[⑻[|1⑼\",],|⑻[\",]0⑾,

```

Try it online!

But seriously, don't ask who Joe is.

# Answer
> 1 votes
# Ruby, 64 bytes

```
->s{s.chars.chunk{|c|c<c.downcase}.map{|u,c|u ??"+c*''+?":c}*''}

```

Try it online!

Longer than the other Ruby solution, but one that doesn't use regex. I also love an excuse to use `chunk`.

This groups successive characters of the string depending on whether or not they're uppercase, and then surround the ones that *are* uppercase with `"`. I had to do the `downcase` check rather than checking with `upcase`, because otherwise non-character strings (spaces, punctuation, etc.) would also be considered uppercase letters.

## Golfy Tricks:

* `*''` instead of `.join`
* `<` instead of `!=`

# Answer
> 0 votes
# AWK, 22 bytes

```
gsub("[A-Z]+","\"&\"")

```

Try it online!

# Answer
> 0 votes
# Charcoal, 20 bytes

```
Ｆ⁺Ｓ «ω✂"⁼№⪪α¹ω№αι≔ιω

```

Try it online! Link is to verbose version of code. Port of my answer to the question linked by @manatwork in the comments.

# Answer
> 0 votes
# Jelly, 11 bytes

```
e€ØAŻIœṗj”"

```

Try it online!

A monadic link taking a string and returning a string.

# Answer
> 0 votes
# perl -pE, 16 bytes

```
s/\p{Lu}+/"$&"/g

```

Unicode compliant, unlike the `s/[A-Z]+/"$&"/g` solution presented earlier.

# Answer
> 0 votes
# Ruby, 30 bytes

```
->s{s.gsub(/([A-Z]+)/,'"\1"')}

```

Try it online!

A simple regex substitution.

---
Tags: code-golf
---


title: Multi-lingual Challenge

text:
# Question
Title: Multi-lingual Challenge
After all the fun we've had with polyglot challenges in the (recent) past, how about a challenge where the output can be in two languages?

Your answer needs to accept boolean input `b` and output the text `"true"` or `"false"`. The same code needs to output, when run in another language, `"waar"` or `"onwaar"` or any other translation of `true`and `false`.

**Input**

* Input is a clearly distinguishable truthy/falsey. Admissible are the actual values T/F, a bit, int or (empty) string.
* Input needs to be the same for all parts of your submission.

**Output**

* Output may be returned by a function, written to `STDOUT`, placed in a popup-window, 3D-printed and mailed etc.
* The output needs to represent the state of `b`. So a 'truthy' needs to output 'true', 'waar' ... and 'falsey' should lead to 'false', 'onwaar', etc.
* Different languages may use different output methods.

**Languages used**

* One of your outputs MUST be `"true"` and `"false"`.
* Different versions of programming languages count as different languages for this challenge.
* Different dialects of a human language count as different languages for this challenge.
* You may extend the polyglot to more than two programming languages. Every programming language needs to output a distinct human language.

The answer with the most languages incorporated will be declared the winner. When tied, bytecount is considered.

# Answer
# Dyalog APL, ~~243~~ 237 bytes: 14 languages, extendable to 131\*

-6 bytes thanks to Soaku.

Requires `⎕IO←0` which is default on many systems. Prompts for input of `0` or `1`.

```
((⎕AV⍳'ëáàÆÅÄòðÓÈÇ')⍳⍎⎕D∩⍨4↑1⊃#⎕WG'APLVersion')⊃⎕⊃s¨⌽(s←{1↓¨⍵⊂⍨⍵=⊃⍵})';,true,adevarat,haqiqiy,otito,tunay,bener,prawda,dogru,vrai,that,wahr,vero,verdade,cierto;,false,fals,yolg''on,eke,mali,palsu,falsz,yanlis,faux,sai,falsch',18⍴',falso'

```

Depending on version (9.0 through 16.0, with minor versions) it outputs in English, Spanish, Portuguese, German, Vietnamese, French, Turkish, Italian, Polish, Sundanese, Filipino, Yoruba, Uzbek, or Romanian, although without diacritics.

`⎕AV⍳'ëáàÆÅÄòðÓÈÇ'` in the indices of the **A**tomic **V**ector (151 142 141 133 132 131 122 121 111 102 101 96)

`((`...`)⍳`...`)` find the position of

the evaluated

`⎕D∩⍨` intersection of **D**igits and

`4↑` the four\* first characters of

`1⊃` the second element of

`#⎕WG'APLVersion'` the version number

`(`...`)⊃` then use that to pick among

`⎕⊃` the input'th (0: first; 1: second) element of

the function *s* (which we will define shortly) applied to each of

the reverse of

`(s←{`...`})` *s* applied to – where *s* is defined as

`1↓¨` the first character dropped from each of

`⍵⊂⍨` the argument partitioned where

`⍵=` the characters of the argument are equal to

`⊃⍵` the argument's first character

`';,true,adevarat,`...`,falsch',` this string prepended to

`18⍴',falso'` eighteen characters taken cyclically from that string

*** Since version 12.1, the version number includes build number, so by increasing the number of characters taken from this string, it is easy to cover all 131 Latin script languages.
> 5 votes

# Answer
# 6 languages, 169 bytes

Expects `0\n` or `1\n` as input, and prints words in:

* Python 2 (Dutch `vals/waar`),
* Python 3 (French `faux/vrai`),
* Ruby (English `false/true`),
* CJam (Norwegian `usant/sant`),
* Golfscript (Danish `usand/sand`),
* Befunge-93 (Italian `falso/vero`).

---

```
"#{puts gets>?1;exit}"" "#"& 1v
""
print('vwfvaaarlauasrxi'[int(1/2*4+int(input()))::4])
""#";;;;ri"u">"sant"+o
""""
__END__
]0=~"u">"sand"""#@,,,,"vero"  _"oslaf",,,,,@

```
> 13 votes

# Answer
## All the Funges, 6 languages, 146 bytes

Now in 3D!

```
A vv"faux"0"vrai"mv#<v&#;9*j"kslaf"6j"etke">:#,_@;
; >"otreic"0"oslaf"v^<
&^>"murev"0"muslaf">
&^&<"false"0"true"<
>_>:#,_@
^_^

```

*For clarity I've separated the two planes of code so you can see how they're layered. On disk these two blocks would be separated with a form feed character at the end of the line above.*

```
   h"vals"0"waar"<

```

The rules did say different versions of a language count as separate languages, so this one is six versions of Funge/Befunge. :)

Thanks to Dennis, all of the Befunge versions can now be tested online at TIO. There aren't currently working implementations of the Unefunge and Trefunge variants, though, so for those I'd recommend Rc/Funge.

`A` is ignored in Befunge 93 and 96, but is the *About Face* command in 97 and is unsupported in 98 and thus reflects. This means that 93 and 96 follow the `v` downwards while 97 and 98 wrap around to the opposite side of the playfield.

In Befunge 96 a `;` followed by space at the start of the line marks it as a comment, so that line is skipped and the interpreter continues to the `>` on the third line. In 93, though, the interpreter follows the `>` on the second line.

The 97/98 path continues on the first line from right to left, skipping over the section inside the `;` comment markers, bridges the `&` command, eventually reaching the U-bend sequence `v<^<`. In Unefunge, these direction changes aren't supported so the interpreter reverses direction and executes the previously skipped section in the comments. In Befunge/Trefunge it continues to the left.

In Befunge 97 the `m` command is unsupported and thus skipped, so the interpreter continues along the first line. In 98 it's 3D-only so it reflects in Befunge (2D) and the interpreter follows the `v` to the right of it down to the fourth line. In Trefunge (3D) it's a *High-Low* branch which transfers up a level along the z-axis to the second plane.

So other than the Unefunge case, we have each version gathering their string pair from a separate line before being directed to one of the `&` commands to get the user input. Those code paths then all merge together via the `^` commands in the second column, directing the program flow upwards through the top of the playfield, wrapping around to the bottom again.

Finally we have the `^_^` sequence which decides which path to follow based on the user input. If *0*, we go straight to the output sequence (`>:#,_`) writing out the *false* string. If *1*, we first execute `>_` which clears the first string off the stack, and thus output the *true* string.
> 10 votes

# Answer
## 5 languages, 249 bytes

**Note: the `\r` and `\e` are literal line-feed and escape characters, but `\x5b` has to be as-is otherwise Ruby complains about the character class in the regex.**

A bit late to the party, and not a winner by any means, but I started working on a polyglot for the thanksgiving challenge and felt it might be a bit late so transformed it into this!

```
q=0//1;'''<?die("\r\e\x5bK".(fgetc(STDIN)?Ekte:Falsk));?>/.to_s.ord;def input()gets.to_i;end;q=+q+0;True="Vrai";False="Faux";'+;sub a{<><1?Vals:Waar}q-
input=prompt;print=alert;True="Vero";False="Falso"//'#'''
a=[False,True];b=input();1-+1;print(a[b])

```

### Explanation

**Python: `True` / `False`**

```
q=0//1;'''<?die("\r\e\x5bK".(fgetc(STDIN)?Ekte:Falsk));?>/.to_s.ord;def input()gets.to_i;end;q=+q+0;True="Vrai";False="Faux";'+;sub a{<><1?Vals:Waar}q-
input=prompt;print=alert;True="Vero";False="Falso"//'#'''
a=[False,True];b=input();1-+1;print(a[b])

```

Here we set `q` to `0//1` which is `0`, then we have a `'''` string that contains most of the other code, store an array containing `False` and `True` and indicies `0` and `1` respectively, assign the input to `b` (which should be `0` or `1` to signify `Falsy` and `Truthy`) then `print` the `b`th index of `a`, showing `False` or `True`.

---

**Ruby: `Vrai` / `Faux`**

```
q=0//1;'''<?die("\r\e\x5bK".(fgetc(STDIN)?Ekte:Falsk));?>/.to_s.ord;def input()gets.to_i;end;q=+q+0;True="Vrai";False="Faux";'+;sub a{<><1?Vals:Waar}q-
input=prompt;print=alert;True="Vero";False="Falso"//'#'''
a=[False,True];b=input();1-+1;print(a[b])

```

As with the Python script, we set the variable `q`, but in Ruby this is set to `0 / /1;'''<?die("\r\e\x5bK".(fgetc(STDIN)?Ekte:Falsk));?>/.to_s.ord`, as Ruby breaks this down as `0/` as "zero divided-by" and the following `/` as "beginning of regex literal". Using this literal I'm able to conceal the PHP code and begin Python's `'''`. We have to add `.to_s.ord` because the right operand to `/` has to be a `Fixnum`. After this we define a function `input()` and the variable `True` and `False` to contain their French counterparts and finally start a string `'` which continues onto the next line. Finally we create an array `a` which contains `"Vrai"` and `"Faux"` and select them using the `input()`ed number `0` or `1`.

---

**Perl: `Waar` / `Vals`**

```
'0//1;\'\'\'<?die("\r\e\x5bK".(fgetc(STDIN)?Ekte:Falsk));?>/.to_s.ord;def input()gets.to_i;end;q}+q{0;True="Vrai";False="Faux";\'';sub a{<><1?Vals:Waar}'
input=prompt;print=alert;True="Vero";False="Falso"//\'#\'\'\'
a=[False,True];b=input();1'+1;print(a[b])

```

In Perl, the `q=..=`, `q+...+` and `q-...-` blocks are quoted literals using unusual delimiters, in the code above I've replaced these with `'...'`. Most of the code is contained in a literal string, but we do define `sub a` (which contains a `<><`!) that checks if `STDIN` is less than `1`, returning either `Waar` or `Vals`. The `print(a[b])` actually `print`s the result of calling the `sub` `a` with and argument of `[b]` which is an ArrayRef that contains the bare-word `b`.

---

**JavaScript: `Vero` / `Falso`**

```
q=0//1;'''<?die("\r\e\x5bK".(fgetc(STDIN)?Ekte:Falsk));?>/.to_s.ord;def input()gets.to_i;end;q=+q+0;True="Vrai";False="Faux";'+;sub a{<><1?Vals:Waar}q-
input=prompt;print=alert;True="Vero";False="Falso"//'#'''
a=[False,True];b=input();1-+1;print(a[b])

```

The first line is mostly commented out by the division `0//1` (`//` is line comment in JavaScript) so we just set `q` to `0`. The next line deals with mapping the JS functions to their Python names and setting variables `True` and `False` to be the Italian strings, finally we execute the same as the Ruby code, setting a to an array of the Italian words and selecting using an `input` of `0` or `1`.

---

**PHP: `Ekte` / `Falsk`**

```
die("\r\e\x5bK".(fgetc(STDIN)?Ekte:Falsk));

```

Since PHP only executes code between `<?...?>` everything else is output as-is, so our code here simply prints a line-feed (to put us back to the beginning of the current line) and the ANSI escape sequence to clear to the end of the current line, followed by either `Ekte` or `Falsk` depending on whether the input char (`0` or `1`) is truthy or falsy.
> 5 votes

# Answer
# Pyth, Python - 28 bytes

```
#>"onwaar"yQ.q
print input()

```
> 3 votes

# Answer
# C#, Java, 104 Bytes

Golfed:

```
String M(Boolean b){String s=b+"";if(s=="True")return "Wahr";if(s=="False")return "Falsch";return b+"";}

```

Ungolfed:

```
  class MultiLingualChallenge
  {
    public String M(Boolean b)
    {
      String s = b + "";
      if (s == "True")
        return "Wahr";
      if (s == "False")
        return "Falsch";
      return b + "";
    }
  }

```

Test:

**C#**

```
Console.WriteLine(new MultiLingualChallenge().M(true));
//Wahr
Console.WriteLine(new MultiLingualChallenge().M(false));
//Falsch

```

**Java**

```
System.out.println(new MultiLingualChallenge().M(true));
//true
System.out.println(new MultiLingualChallenge().M(false));
//false

```

Explanation:

When calling `ToString()` or `toString()` on a Boolean in C# and Java respectively, C# prints the string with a capital first letter, `True` and `False`, but Java prints all in lower case `true` and `false`.

```
Console.WriteLine(true+"");
//True

System.out.println(true+"");
//true

```
> 3 votes

# Answer
# 2 languages, 60 bytes

```
print('onwaar'[2*int(input()):]);1#¶ị“¡ẈẆ“⁸1»

```

Languages are:

* Jelly `true` `false`
* Python3 `waar` `onwaar`

Note: There are UTF-8 bytes, not Jelly bytes.
> 2 votes

# Answer
# JavaScript / BF

In both these languages, no input is considered as false and any input is considered true.

When you see the structure of the program rotated 90 degrees to the left, the BF symbols look like towers in a city :)

Try it online (BF true testcase)!

Try it online (BF false testcase)!

```
console.log(prompt()?"true":"false")
/*
           >,[>
+          <<]>>[->-<]
+          >[<->[-]]<>[-]<[>>
+++        [->
++++       <]>[->
++++++++++ <]>---.>]>
++++++++++ [->
++++++++++ <]
+++        [->
+++++      <]>.<
++++       [->----<]>--.<
+++        [->
++++       <]>
+          .<
+++        [->---<]>-.
*/
```

## Explanation

### JavaScript

If the `prompt` is true (ie not empty because `prompt` returns a string), outputs `true`, or else outputs `false`.

### BF

Outputs `sand` (Danish for true) if there is an input, or else outputs `usand` (false) if the input is empty.

**TL;DR** If input is not empty (ie true), don't output anything. If input is empty (ie false), output `u`. Then, regardless whether the input is true or false, output `sand`.

I have taken inspiration from https://esolangs.org/wiki/Brainfuck\_algorithms with which I constructed the logic of my program.

Take input. If input is not empty, increment memory, let's call this cell "Cell A". End if-statement

```
>
,[
>+
<<
]>

```

Compares the value of "Cell A" with `0`. If they are equal, let "Cell B" be `1`, or else let it be `0`.

```
>
[->-<]+>[<->[-]]<

```

If "Cell B" is 1, then output `u`. Close if-statement

```
>[-]<
x[>>
+++[->++++<]>[->++++++++++<]>---.
>]

```

Output `sand`

```
>
++++++++++[->++++++++++<]+++[->+++++<]>.
<++++[->----<]>--.
<+++[->++++<]>+.
<+++[->---<]>-.

```
> 1 votes

# Answer
# Lua/JavaScript, 68 bytes

```
x=1//1print(...and"true"or"false")
--x;alert(prompt()?"vrai":"faux")

```

Don't know why I golfed it; I just felt like it.
> 1 votes

# Answer
# Haskell, JavaScript, Python, 115 Bytes

```
q=1//1#1;f True="waar";f False="false";a//b=0;a#b=0{-
1//1;f=lambda x:"wahr"if x else"falsch";"""
f=x=>x+[]//"""#-}

```
> 1 votes

---
Tags: code-challenge, natural-language, polyglot
---


title: Shortest Code that creates a Deadlock

text:
# Question
Title: Shortest Code that creates a Deadlock
Write the shortest code to create a deadlock. Code execution must halt, so this doesn't work:

```
public class DeadlockFail extends Thread{ //Java code
    public static void main(String[]a){
        Thread t = new DeadlockFail();
        t.start();
        t.join();
    }
    //this part is an infinite loop; continues running the loop.
    public void run(){while(true){}}
}

```

It doesn't need to be certain that the code goes into deadlock, just almost surely (if you run for infinite time, it will deadlock).

# Answer
## Dyalog APL (10)

```
⎕TSYNC⎕TID

```

`⎕TSYNC` makes the thread wait until the given thread ends, `⎕TID` gives the current thread.

Dyalog APL can recognize deadlocks though, so it immediately responds with

```
DEADLOCK

```

The fun thing is, you don't even need to spawn any extra threads, making the UI thread wait for itself is plenty.

If this is cheating and new threads are actually required, you can do it in 27 characters:

```
{∇⎕TSYNC&{⎕TSYNC⎕TID+1}&0}0

```

`F & x` runs `F` in a new thread on value `x`, and returns the thread ID. So:

* `{⎕TSYNC⎕TID+1}&0` creates a thread that will synchronize with the thread whose ID is one higher than its own,
* `⎕TSYNC&` creates a new thread that will synchronize with the previous thread, and which gets an ID one higher than the thread that was just created (assuming nothing else is creating threads).
* causes an infinite loop (so we keep creating threads until there's a deadlock).

This will deadlock as soon as the second thread gets created before the first one starts running, which is pretty soon:

```
9:DEADLOCK

```
> 11 votes

# Answer
## Go, 42

```
package main
func main(){<-make(chan int)}

```

Apologies, downvoter, for not providing how it works. This creates an anonymous channel of ints and reads from it. This pauses the main thread until a value gets sent down the channel, which obviously never happens since no other threads are active, and thus, deadlock.
> 8 votes

# Answer
# Ruby, 39 characters

```
T=Thread;t=T.current;T.new{t.join}.join

```

The idea to use a cross-join shamelessly stolen from Johannes Kuhn's Java answer.

We can shave off four characters (getting to **35**) if we tune the code to a specific environment. JRuby's console IRB is single-threaded:

```
T=Thread;T.new{T.list[0].join}.join

```

---

---

This is my previous solution:

getting a thread stuck on a mutex is easy:

```
m=Mutex.new;2.times{Thread.new{m.lock}}

```

but this isn't a proper deadlock, because the second thread is technically not waiting for the first thread. "hold and wait" is a neccessary condition for a deadlock according to Wikipedia. The first thread doesn't wait, and the second thread doesn't hold anything.

# Ruby, ~~97~~ 95 characters

```
m,n=Mutex.new,Mutex.new
2.times{o,p=(m,n=n,m)
Thread.new{loop{o.synchronize{p.synchronize{}}}}}

```

this is a classic deadlock. Two threads compete for two resources, retrying if they succeed. Normally they get stuck within a second on my machine.

But, if having infinitely many threads (none of which consumes CPU infinitely and some of which deadlock) is OK,

# Ruby, ~~87~~ 85 characters

```
m,n=Mutex.new,Mutex.new
loop{o,p=(m,n=n,m)
Thread.new{o.synchronize{p.synchronize{}}}}

```

According to my test, it fails after the thread count reaches about 4700. Hopefully it doesn't fail until each thread had a chance to run (thus either deadlocking or finishing and freeing space for a new one). According to my test, the thread count doesn't drop after the failure occurs, meaning that a deadlock did occur during the test. Also, IRB died after the test.
> 4 votes

# Answer
# Python, 46

```
import threading as t
t.Semaphore(0).acquire()

```

(self-deadlock)
> 4 votes

# Answer
# Bash + GNU coreutils, 11 bytes

```
mkfifo x;<x

```

Creates a stray FIFO `x` in the current directory (so you'll need to not have a file by that name). FIFOs can be deleted the same way as regular files, so it shouldn't be hard to clear up.

A FIFO has a write side and a read side; attempting to open one blocks until another process opens the other, and this seems to have been intentionally designed as a synchronization primitive. Given that there's only one thread here, as soon as we try to open it with `<x`, we get stuck. (You can unstick the deadlock via writing to the FIFO in question from another process.)

This is a different kind of deadlock from the one when there are two resources, and two threads each have one and needs the other; rather, in this case, there are zero resources and the process needs one. Based on the other answers, I think this counts, but I can understand how a deadlock purist might want to disallow the answer.

Come to think of it, I can actually think of three deadlock-like situations:

1. The "traditional" deadlock: two threads are each waiting for a lock to be released, that's held by the other thread.
2. A single thread is waiting for a lock to be released, but it holds the lock itself (and thus is blocking itself from being able to release it).
3. A single thread is waiting for a synchronization primitive to be released, but the synchronization primitive starts in a naturally locked state and has to be unlocked externally, and nothing's been programmed to do that.

This is a deadlock of type 3, which is in a way fundamentally different from the other two: you could, in theory, write a program to unlock the synchronization primitive in question, then run it. That said, the same applies to deadlocks of type 1 and 2, given that many languages allow you to release a lock you don't own (you're not *supposed* to and would have no reason to do so if you had a reason to use the locks in the first place, but it works…). Also, it's worth considering a program like `mkfifo x;<x;echo test>x`; that program's sort-of the opposite of a type 2 deadlock (it's trying to open both ends of the FIFO, but it can't open one end until after it opens the other end), but it was made from this one via adding extra code that never runs after this one! I guess the problem is that whether a lock is deadlocked or not depends on the *intention* behind the use of the lock, so it's hard to define objectively (especially in a case like this where the only purpose of the lock is to produce a deadlock intentionally).
> 4 votes

# Answer
## Tcl, 76

```
package r Thread;thread::send [thread::create] "thread::send [thread::id] a"

```

Deadlock.

This creates a new Thread, and tells the other thread to send my thread a message (script to execute).

But sending a message to an other Thread usually blocks until the script has been executed. And while it is blocking, no messages are processed, so both Threads wait for the other to process their message.
> 2 votes

# Answer
## Java, 191

```
class B extends Thread{public static void main(String[]a)throws Exception{new B().join();}Thread d;B(){d=Thread.currentThread();start();}public void run(){try{d.join();}catch(Exception e){}}}

```

Ungolfed:

```
class B extends Thread {
    Thread d;
    public static void main(String[] args) throws Exception {
        new B().join();
    }
    B() { // constructor
        d = Thread.currentThread();
        start();
    }
    public void run() {
        try {
            d.join();
        } catch (Exception e) {
        }
    }
}

```

Starts a new Thread and `join` on it (wait until this thread has finished), while the new Thread does the same with the original Thread.
> 2 votes

# Answer
# C#, 100

```
class C{static C(){var t=new System.Threading.Thread(Main);t.Start();t.Join();}static void Main(){}}

```

See: The no-lock deadlock
> 2 votes

# Answer
# Bash with glibc, 6 Bytes

Sorry to revive an old thread, but couldn't resist.

As root:

```
pldd 1

```

From man pldd:

> BUGS
> Since glibc 2.19, pldd is broken: it just hangs when executed. It is unclear if it will ever be fixed.
> 2 votes

# Answer
alternative java with monitor-abuse (248 charas)

```
class A{public static void main(String args[]) throws Exception{final String a="",b="";new Thread(new Runnable(){public void run(){try {synchronized(b){b.wait();}} catch (Exception e) {}a.notify();}}).start();synchronized(a){a.wait();}b.notify();}}

```
> 1 votes

# Answer
# Scala, 104 bytes

```
class A{s=>lazy val x={val t=new Thread{override def run{s.synchronized{}}};t.start;t.join;1}};new A().x

```

The lazy val initialization block suspends until a condition is fulfilled. This condition can only be fulfilled by reading the value of lazy val x - another thread that is supposed to complete this condition cannot do so. Thus, a circular dependency is formed, and the lazy val cannot be initialized.
> 1 votes

# Answer
# PowerShell, ~~36~~ ~~28~~ 23 bytes

```
gps|%{$_.waitforexit()}

```

Self-deadlock. We get all processes with `Get-Process` and then wait patiently for each of them to exit ... which will happen approximately never, since the process will be waiting on itself.

Edit - Saved 5 bytes thanks to Roman Gräf
> 1 votes

# Answer
# Kotlin, 35/37/55 bytes

General theme: `Thread.currentThread().join()`.

Excluding JVM bugs / very specialized code against this submission this shoud never return as the current execution thread is now disabled waiting for itself to die.

---

### Evil property: 35 bytes (non-competing): 35 bytes

`val a=Thread.currentThread().join()`

Putting this anywhere a property declaration is valid will deadlock whoever is initializing it. In the case of a top-level property, that will be the classloader initializing the mapped JVM class for that file (by default `[file name]Kt.class`).

Non-competing because "put this as a top level property anywhere" is restrictive.

---

### Function: 37 bytes

`fun a()=Thread.currentThread().join()`

---

### main(): 55 bytes

`fun main(a:Array<String>)=Thread.currentThread().join()`
> 1 votes

# Answer
# The Waterfall Model (Ratiofall), 13 bytes

```
[[2,1],[1,1]]

```

Try it online!

Here's a fun off-the-wall answer. This is the simplest possible infinite loop in The Waterfall Model (variables in The Waterfall Model repeatedly decrement whenever nothing else is happening; this program defines a variable that increments itself whenever it decrements, so there's no way anything can ever happen).

The question asks for a deadlock, not an infinite loop. However, we can exploit the behaviour of specific implementations. At optimisation level 2 or higher (the default is 3), the interpreter Ratiofall will detect the infinite loop, and optimise it… into a deadlock! So at least if we consider languages to be defined by their implementation (which is usually the case on this site), this program does indeed define a deadlock, rather than an infinite loop.

You can see evidence of the deadlock from the time report on the Try it Online! link above:

```
Real time: 60.004 s
User time: 0.006 s
Sys. time: 0.003 s
CPU share: 0.01 %
Exit code: 124

```

The program ran for 60 seconds (until TIO automatically terminated it), but for most of that time, there was no CPU usage, no time spent by the program running, and no time spent by the kernel on behalf of the program.

To get even stronger evidence, you can run Ratiofall under a system-call-level debugger such as `strace`; doing this on Linux will show the interpreter blocking on a `futex` system call that attempts to take a lock which will never be released.
> 1 votes

# Answer
# C (Linux only), 31 Bytes -- Try it online!

```
main(a){syscall(240,&a,0,a,0);}

```

System call 240 (0xf0) is futex(2), or fast userspace mutex. The documentation states that the first argument is a pointer to the futex, the second argument is the operation (0 means FUTEX\_WAIT, that is, wait until another thread unlocks the futex). The third argument is the value you expect the futex to have while still locked, and the fourth is the pointer to the timeout (NULL for no timeout).

Obviously, since there's no other thread to unlock the futex, it will wait forever in self-inflicted deadlock. It can be verified (via `top` or other task manager) that the process uses no CPU time, as we should expect from a deadlocked thread.
> 0 votes

# Answer
# BotEngine, 3x3=9 (9 bytes)

```
v
lCv
> <

```

Step 5 ends with two bots waiting indefinitely for each other to move... one bot can't move because it's waiting for the other to move out of the bottom right square, and the other bot can't move because it's waiting for the first bot to move out of the bottom center square.
> 0 votes

# Answer
# Julia 0.6, 13 bytes

Language newer than question. Wait on a task (like a go-routine, will currently be on the same thread, in future versions of Julia it may be on another thread) which is not scheduled to run.

```
wait(@task +)

```

Try it online!
> 0 votes

# Answer
# Perl 6, 24 bytes

```
Semaphore.new(0).acquire

```

Try it online!

Create a semaphore with zero permits and then try to acquire it.
> 0 votes

---
Tags: code-golf, concurrency
---


# Question
Title: Return a word with a prescribed sum of letters
Identify each letter of the English alphabet with the number denoting its position in the alphabet, that is,

`a = 1, b = 2, c = 3, ..., z = 26`

(no distinction between lower and upper case letters is made). Every other character is identified with `0`.

The "sum" of a word is the sum of its characters, for example: the sum of `e-mail` is `40 = 5 + 0 + 13 + 1 + 9 + 12`, since `e = 5, - = 0, m = 13, a = 1, i = 9, l = 12`.

**The Challenge**

Write a program or a function that takes as input an integer `n` in the range 10-100 and returns a word of the English language whose sum is equal to `n`

This is codegolf, standard loopholes are forbidden.

**ADDENDUM:**

# Answer
> 5 votes
# Python 3.8 (pre-release), ~~262~~ 235 bytes

```
lambda x:f'JKLmGoPlheAhVegytMtosOdtthfvtWypvttgYsRWspytps    e  eegli ra eehnkPooeoroyyauiuruotoituooup    b   aggd  p ai    mnrwiwpnwsnyotrosturwutr{"":8}d{"":14}gnlz   nht ntkpstmsltty'[(k:=x-10)//46*23+k%23::46].strip()+k//23%2*'er'

```

Try it online!

Uses words from the list that appear with and without a trailing `er`, cutting the number of required words almost in half.

# Answer
> 4 votes
# JavaScript (ES6),  ~~217~~  205 bytes

An idea similar to the one used by ovs.

Most words are used twice: once with the `-ty` suffix (which is worth \\$45\\$ points) and once without it.

```
n=>"JK"[n-10]||["Hwy",,"Yor",,"Yot"][n-56]||"KaMMaOPQCanSTAtMiAmiCatDuBawBetGilBolPieBitBooCooEmpToFooBunCotDotKitBoxBusButCutJotJaunGusGutYesUmpJutSixMusUnsNut".match(/.[a-z]*/g)[(n-12)%45]+(n>55?'ty':'')

```

Try it online!

---

# JavaScript (Node.js),  ~~325 ... 240~~  235 bytes

Words of \\$3\\$ to \\$5\\$ letters ending in either `"d"` or `"y"`, with the penultimate letter deduced from the other ones.

```
n=>(w="EAGCABCABACBCCHFABAAAAdBADFaFGAAAKBCASCDBFEYLGNHHArOPSPPTOYRSDoCoDoCuFoEyYaLoYoNoSpSiPoOoRoToAttCurIzAtyButCurDizSuDruExpYesMurFurYumMusMizBuz".match(/.[a-z]*/g)[n-10])+(B=Buffer)([B(w+(c=n>27?'y':'d')).map(c=>n+=96-c)&&n+64])+c

```

Try it online!

# Answer
> 4 votes
# 05AB1E, ~~187~~ ~~51~~ 48 bytes

```
žĆ•o‹§d∍(Ì•3в¾7:65Å1«.¥žy+èãJε„'ÿ.V}ʒAsSk>OQ}Réθ

```

Try it online. (Pretty slow unfortunately, so no test suite, but here is a list of all the words used.)

**Explanation:**

```
  •o‹§d∍(Ì•           # Push compressed integer 13897672729830113
    3в                # Convert it to base-3 as list: [2,1,1,1,1,1,1,1,1,1,1,2,0,1,1,2,1,1,1,2,1,2,1,1,1,1,1,1,1,1,1,1,1,2]
      ¾7:             # Replace the 0 with a 7
         65Å1         # Push a list of 65 1s
             «        # And append it to the list
              .¥      # Undelta the list (with leading 0): [0,2,3,4,5,6,7,8,9,10,11,12,14,21,22,...]
                žy+   # Add 128 to each: [128,130,131,...]
žĆ                 è  # Index each into the 05AB1E codepage builtin
ã                     # Get the cartesian product with itself, to create all possible pairs
 J                    # Join each pair together
  ε     }             # Map over each pair:
   „'ÿ               '#  Push string "'ÿ", where the `ÿ` is automatically filled with the current pair we're mapping over
      .V              #  And eval it as 05AB1E code, pushing the dictionary word
ʒ       }             # Filter the list of words by:
 A                    #  Push the alphabet
  s                   #  Swap to take the current word we're filtering over
   S                  #  Convert it to a list of characters
    k                 #  Get the index of each letter inside the alphabet
     >                #  Increase it by 1 to make the 0-based indices 1-based
      O               #  Sum them all together
       Q              #  And check if it's equal to the (implicit) input-integer
R                     # Then reverse the list of remaining words (work-around for input n=11,
                      # which otherwise would result in "fda", which is not in OP's list)
 é                    # Then (stable) sort all words based on length, from shortest to longest
  θ                   # And only leave the last one
                      # (after which it is output implicitly as result)

```

Unfortunately, not all words that can be found in the 05AB1E word list can be found in the provided list as well.

See this 05AB1E tip of mine (sections *How to use the dictionary?*, *How to compress large integers?*, and *How to compress integer lists?*), to understand how the dictionary words and compressed integer list works.

---

**Original 187 bytes answer:**

```
“„é…ªƒ…°»ØÎ‰éãŠêˆÜŠ°í©ÓŽÄÍÝ‚†–ìŠÑÞã™Ä‡ÉˆÁ³²áäÁÑÆ©…¥Ê†…íÆ±Ñœ›Ç²èœÊ‚ì€€Šµ€„±½†íª¯ÅÝ‚îäÔÈÃÞºì¤ƒ‚ž¨€º¢êˆ¨ïëïÆÐ¼ˆÌ²Ï……ƒÔ…ÙÒ„±ÞŒÂä†ÔÚ´´½é‚¤»œË´¥º™Žâ¤Ñ¸‚É„¾ÈÕˆî†Û‚äŠÁ‹‚Œæ‹Ì†ÏƒÓ‡È…Ï‰Éƒà‚ë„¶™£“#sè

```

Try it online or verify all test cases.

I've chosen random words which are both in the English dictionary provided, as well as in 05AB1E word list.

**Explanation:**

```
“...“     # Dictionary string containing all words, space-separated
     #    # Split it on spaces
      s   # Swap to get the (implicit) input
       è  # And used it to index into the list (0-based and with wrap-around,
          # so 91-100 wrap around to the first few words)
          # (after which the result is output implicitly)

```

Here is just the dictionary string part of the program.

See this 05AB1E tip of mine (section *How to use the dictionary?*), to understand how the dictionary string works.

# Answer
> 1 votes
# Perl 5, 361 bytes

```
say''.(memGunzip(decode_base64('H4sIAINkcl4CAx2PC3LDIBBDL/Qu5Q+JneJAgbVZTl/RGWA0WkloQ2BdDs6Niy+JPRIi50llqZyRRTcUQsWJX1Znc943wXnpDFLBLlIjdqLza9RGckaiF4pTneYyVvpD76w2CGKOp/FNDx+7eYs77sk5P24KdbLmaVSytNmcYp3Uhb1Tpa/S7pPY0nAF32x2T9BVTv6P6ek+pilyuWrlohYvG4M8jcdE1YsG1oZa5kftpuaaE7dmCpBvs6Lk/Rz66LFh7CrjLG7qGsOkc2pa9GVFOFq3mVHV/Po3aefhfyb5uBZsAQAA'))=~/\w+/g)[-10+pop]

```

Try it online!

Ungolfed program.pl:

```
#!/usr/bin/perl
use v5.10;
use MIME::Base64 'decode_base64';
use Compress::Zlib 'memGunzip';

# base64-encoded gzip'ed string of 91 words:
my $data=<<'';
H4sIAINkcl4CAx2PC3LDIBBDL/Qu5Q+JneJAgbVZTl/RGWA0WkloQ2BdDs6Niy+JPRIi50
llqZyRRTcUQsWJX1Znc943wXnpDFLBLlIjdqLza9RGckaiF4pTneYyVvpD76w2CGKOp/FN
Dx+7eYs77sk5P24KdbLmaVSytNmcYp3Uhb1Tpa/S7pPY0nAF32x2T9BVTv6P6ek+pilyuW
rlohYvG4M8jcdE1YsG1oZa5kftpuaaE7dmCpBvs6Lk/Rz66LFh7CrjLG7qGsOkc2pa9GVF
OFq3mVHV/Po3aefhfyb5uBZsAQAA

say ''.(memGunzip(decode_base64($data))=~/\w+/g)[-10+pop]

```

Run:

```
for n in {10..100};do echo -n "n=$n "; perl program.pl $n; done
.
.
.
n=95 potsy
n=96 furzy
n=97 luxus
n=98 musty
n=99 mizzy
n=100 buzzy

```

Improvement: I could have search for words in `words.txt` that gave shorter gzip'ed `$data`. Probably shortest AND most similar word from one `n` to the next.

# Answer
> 0 votes
# C (gcc), 574 bytes

```
char*s[]={"ee","afd","ic","m","n","o","dl","el","ii","s","as","il","3rd","er","es","y","ln","by","cy","gv","ey","fy","fz","or","um","ot","lx","yl","ym","yn","yo","zo","xr","yr","ys","ty","bys","xw","xx","buz","ety","hwt","now","yew","guz","hvy","hwy","kyu","yor","yum","yot","you","puy","yow","yox","yoy","suz","swy","doxy","cozy","xxv","cuvy","xxx","eyry","yawy","xyz","yoky","youp","prys","fuzz","yoyo","huzz","yows","yowt","typw","burys","muzz","yutu","xyst","curvy","dizzy","wuzu","druxy","ayuyu","yesty","potsy","furzy","yummy","yours","yourt","buzzy"};f(n){n=s[n-10];}

```

Wordlist generated using my program run as `program < words.txt`.

Try it online!

---
Tags: code-golf, natural-language
---


title: Remove duplicated & switched case

text:
# Question
Title: Remove duplicated & switched case
## Goal

The goal of this challenge is: given a string as input, remove duplicate pairs of letters, if the second item in the pair is of opposite capitalization. (i.e. uppercase becomes lowercase and vice-versa).

Pairs should be replaced from left to right. For example, `aAa` should become `aa` and not `aA`.

## Inputs & outputs:

```
Input:         Output:
bBaAdD         bad
NniIcCeE       Nice
Tt eE Ss tT    T e S t
sS Ee tT       s E t
1!1!1sStT!     1!1!1st!
nN00bB         n00b
(eE.gG.)       (e.g.)
Hh3lL|@!       H3l|@!
Aaa            Aa
aaaaa          aaaaa
aaAaa          aaaa

```

The input consists of printable ASCII symbols.

*You shouldn't remove duplicated digits or other non-letter characters.*

## Acknowledgement

This challenge is the opposite of @nicael 's "Duplicate & switch case". Can you reverse it?

Thank you for all contributors from the sandbox!

## Catalogue

The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
## Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
## Ruby, <s>104</s> <s>101</s> 96 bytes

```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:

```
## Perl, 43 + 2 (-p flag) = 45 bytes

```

You can also make the language name a link which will then show up in the snippet:

```
## [><>](http://esolangs.org/wiki/Fish), 121 bytes

```

```
<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 85509; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 36670; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "//api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "//api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(42), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>
```

# Answer
# Jelly, 8 bytes

```
ṛŒsḟḟȧµ\

```

Try it online! or verify all test cases.

### How it works

```
ṛŒsḟḟȧµ\  Main link. Argument: s (string)

      µ   Convert all links to the left into a chain (unknown arity) and begin a
          new chain.
       \  Do a cumulative reduce by the chain to the left.
          Left argument:   r (previous result or first character)
          Right argument:  c (next character)
ṛ           Set the return value to c.
 Œs         Swap c's case.
    ḟ       Remove c from r (if present).
            This yields an empty string if c and r are identical (repeated letter
            with the same case or non-letter) and r otherwise.
            Note that r will be empty if the previous character has been removed.
   ḟ        Remove the resulting characters (if any) from c with swapped case.
            This yields c with swapped case if the result to the right does not
            contain c; otherwise, it yields the empty string.
     ȧ      Flat logical AND with c.
            Replace swapped case c with c; do not modify an empty string.

```
> 13 votes

# Answer
## Retina, 18 bytes

```
(.)(?!\1)(?i)\1
$1

```

Try it online!

### Explanation

This a single (and fairly simple) substitution which matches the relevant pairs and replaces them with only the first character. The pairs are matched by activating case-insensitivity halfway through the pattern:

```
(.)     # Match a character and capture it into group 1.
(?!\1)  # Use a negative lookahead to ensure that the next character *isn't* the same
        # as the character we just captured. This doesn't advance the position of the
        # regex engine's "cursor".
(?i)    # Now activate case-insensitivity for the remainder of the pattern.
\1      # Match the second character with a backreference to the first. With the i
        # modifier activated, this will match if the two characters only differ
        # by case.

```

The substitution simply writes back the character we already captured in group `1` anyway.
> 12 votes

# Answer
# C#, ~~87~~ 75 bytes

```
s=>System.Text.RegularExpressions.Regex.Replace(s,@"(.)(?!\1)(?i)\1","$1");

```

With the mighty regex from Martin Ender. C# lambda where the input and the output are `string`.

12 bytes saved by Martin Ender and TùxCräftîñg.

---

# C#, ~~141~~ 134 bytes

```
s=>{var r="";for(int i=0,l=s.Length;i<l;i++){var c=s[i];r+=c;if(char.IsLetter(c)&i+1<l&&(c|32)==(s[i+1]|32)&c!=s[i+1])i++;}return r;};

```

C# lambda where the input and the output are `string`. The algorithm is naive. This is the one I use as reference.

Code:

```
s=>{
    var r = "";
    for(int i = 0; i < s.Length; i++)
    {
        r+=s[i];
        if (char.IsLetter(s[i]) & i+1 < s.Length)
            if (char.ToLower(s[i])==char.ToLower(s[i+1])
              & char.IsLower(s[i])!=char.IsLower(s[i+1]))
                i += 1;
    }
    return r;
};

```

7 bytes thanks to Martin Ender!

---

Try them online!
> 5 votes

# Answer
# Brachylog, 44 bytes

```
.v|.l1|hA,?bhB(@uA;A@uB),?bb&~b.hA|?b&~b.h~h?

```

Brachylog has no regular expressions.

### Explanation

```
    .v          Input = Output = ""
|               OR
    .l1         Input = Output = string of one character
|               OR
    hA,         A is the first char or the Input
    ?bhB        B is the second char of the Input
    (
        @uA         B uppercased is A
        ;           OR
        A@uB        A uppercased is B
    ),
    ?bb&        Call recursively on Input minus the first two elements
    ~b.hA       Output is the result of that call with A appended before it
|               OR
    b&          Call recursively on Input minus the first element
    ~b.h~h?     Output is the result of that call with the first element of Input appended
                  before it

```
> 5 votes

# Answer
## Perl, ~~40~~ 24+1=25 bytes

Use the same regex as Martin.
Use the `-p` flag

```
s/(.)(?!\1)(?i)\1/\1/g

```

Test it on ideone
> 4 votes

# Answer
# Python 3, ~~64~~ ~~59~~ 58 bytes

```
r=input()
for c in r:r=c[c.swapcase()==r!=c:];print(end=r)

```

Test it on Ideone.
> 4 votes

# Answer
# C, 66 bytes

```
l;main(c){for(;~(c=getchar());)l=l^c^32|!isalpha(c)?putchar(c):0;}

```
> 4 votes

# Answer
# Pyth, ~~24~~ 20 bytes

4 bytes thanks to @Jakube.

This still uses regex, but just for tokenizing.

```
shM:zj\|+s_BVGrG1\.1

```

Test suite.

```
shM:zj\|+s_BVGrG1\.1   input as z
         s_BVGrG1      generate ['aA', 'Aa', 'bB', 'Bb', ..., 'zZ', 'Zz']
        +        \.    add "." to the back of the array
     j\|               insert "|" between every element of the array,
                       forming a new long string, which will be our
                       tokenizer: "aA|Aa|bB|Bb|cC|Cc|...|yY|Yy|zZ|Zz|."
                       the "." at the end is to capture the remaining characters
  :z               1   return all matches of z against that regex
                       this is effectively a tokenizer
 hM                    take the first character of each token
s                      join all the transformed tokens together, and then
                       implicitly print to STDOUT.

```
* 24-byte version here.
> 3 votes

# Answer
# MATL, 21 bytes

```
"Kk@k=K@XK=>?4XKx}K&h

```

Try it online!. Or verify all test cases.

### Explanation

This processes each character in a loop. Each iteration compares the current character with the previous character. The latter is stored in clipboard K, which is initiallized to `4` by default.

The current character is compared with the previous one twice: first case-insensitively and then case sensitively. The current character should be deleted if and only if the first comparison was true and the second was false. Note that, since clipboard K initially contains 4, the first character will always be kept.

If the current character is deleted clipboard K should be reset (so the next character will be kept); otherwise it should be updated with the current character.

```
"            % Take input string implicitly. For each char from this string:
  K          %   Push previous char, initiallized to number 4
  k          %   Convert to lower case. For numbers it rounds down
  @          %   Push current char
  k          %   Convert to lower case.
  =          %   True if current and previous chars are (case-insensitively) equal
  K          %   Push previous char
  @          %   Push current char
  XK         %   Update clipboard K with current char. This doesn't affect the stack
  =          %   True if current and previous chars are (case-sensitively) equal
  >?         %   If first comparison was true and second was false
    4XKx     %     Reset clipboard K to 4
  }          %   Else
    K        %     Push previous char
    &h       %     Concatenate horizontally to gradually build the output string

```
> 3 votes

# Answer
# C, ~~129~~ ~~127~~ ~~125~~ ~~107~~ ~~106~~ ~~105~~ ~~93~~ ~~92~~ ~~90~~ ~~88~~ ~~85~~ ~~78~~ 73 bytes

```
c;d;f(char*s){for(;c=*s;s+=isalpha(putchar(c))*d*!((d^=c)&95)&&d)d=*++s;}

```

A C port of my C# answer. My C may be a bit bad. I don't use the language a lot anymore. Any help is welcome!

* 1 byte saved thanks to Lowjacker's trick: `a!=b` = `a^b`
* 1 byte saved thanks to Walpen's trick: `a&&b` = `a*b`
* 12 bytes saved by Lynn's trick and inspired here by TùxCräftîñg
* 1 byte saved thanks to Joey Adams's trick and inspired here by orlp: Moving variable to global
* 2 bytes saved by SEJPM by resolving my `(c|32)==(d|32)` bitwise problem
* 5 bytes saved by Pietu1998
* 5 bytes saved by ceilingcat

Code:

```
c;d;f(char*s) {
    for(;putchar(c=*s);)
        s+=isalpha(c)*(d=*++s)&&(!((c^d)&95)&&c^d);
}

```

Try it online!
> 3 votes

# Answer
## JavaScript (ES6), ~~71~~ 68 bytes

```
s=>s.replace(/./g,c=>l=c!=l&&c>'0'&&parseInt(c+l,36)%37<1?'':c,l='')

```

Explanation:

```
s=>s.replace(/./g,c=>   Loop over each character in the string
 l=                     Save result for next loop
  c!=l&&                Check whether characters differ
  c>'@'&&               Check minimum character code
  parseInt(c+l,36)%37<1 Check if characters have same value
  ?'':c,                If so then delete this character
 l='')                  Initial empty previous character

```

Given `c>'@'`, the only way for `parseInt(c+l,36)` to be a multiple of 37 is for both `c` and `l` to have the same value (they can't have zero value because we excluded space and zero, and if they have no value then the expression will evaluate to `NaN<1` which is false) is for them to be the same letter. However, we know that they're not the same letter case-sensitively, so they must be the same case-insensitively.

Note that this algorithm only works if I check every character; if I try to simplify it by matching on letters it will then fail on things like `"a+A"`.

Edit: Saved 3 bytes thanks to @edc65.
> 3 votes

# Answer
# JavaScript (ES6), ~~61 bytes~~, 57 Bytes

`s=>s.replace(/./g,c=>l=c!=l&/(.)\1/i.test(l+c)?'':c,l='')`

Thanks to Neil for saving 5 bytes.
> 2 votes

# Answer
# Java 7, 66 bytes

```
String c(String i){return i.replaceAll("(.)(?!\\1)(?i)\\1","$1");}

```

Used Martin Ender's regex from his Retina answer.

**Ungolfed & test code:**

Try it here.

```
class Main{
  static String c(String i){
    return i.replaceAll("(.)(?!\\1)(?i)\\1", "$1");
  }

  public static void main(String[] a){
    System.out.println(c("bBaAdD"));
    System.out.println(c("NniIcCeE"));
    System.out.println(c("Tt eE Ss tT"));
    System.out.println(c("sS Ee tT"));
    System.out.println(c("1!1!1sStT!"));
    System.out.println(c("nN00bB"));
    System.out.println(c("(eE.gG.)"));
    System.out.println(c("Hh3lL|@!"));
    System.out.println(c("Aaa"));
    System.out.println(c("aaaaa"));
    System.out.println(c("aaAaa"));
  }
}

```

**Output:**

```
bad
Nice
T e S t
s E t
1!1!1st!
n00b
(e.g.)
H3l|@!
Aa
aaaaa
aaaa

```
> 2 votes

# Answer
# JavaScript (ES6) 70

```
(s,p,q)=>s.replace(/./g,c=>p!=c&q===(d=parseInt(c,36))?q='':(q=d,p=c))

```

```
f=(s,p,q)=>s.replace(/./g,c=>p!=c&q===(d=parseInt(c,36))?q='':(q=d,p=c))

;
[['bBaAdD','bad']
,['NniIcCeE','Nice']
,['Tt eE Ss tT','T e S t']
,['sS Ee tT','s E t']
,['1!1!1sStT!','1!1!1st!']
,['nN00bB','n00b']
,['(eE.gG.)','(e.g.)']
,['Hh3lL|@!','H3l|@!']
,['Aaa','Aa']
,['aaaaa','aaaaa']
,['aaAaa','aaaa']]
.forEach(
  x=>
  {
    var i=x[0],k=x[1],r=f(i)
    console.log(k==r?'OK':'KO',i,r)
  }
)
```
> 1 votes

# Answer
## Convex, 18 bytes

```
V±V.+'.+'|*\ô{0=}%

```

Try it online!

Similar approach as @Leaky Nun's Pyth answer. It constructs the array `["aA" "bB" ... "zZ" "Aa" "Bb" ... "Zz" '.]`, joins by the `'|` character, and tests the input based on that regex. Then it takes the first character of each match.
> 1 votes

# Answer
Haskell, 70 Bytes

```
import Data.Char
f (a:b:c)|g a/=g b=a:f c|0>1=a:b:f c
f a=a
g=isUpper

```
> 0 votes

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


title: Tips for Golfing in Symja

text:
# Question
Title: Tips for Golfing in Symja
Symja is a "computer algebra language & Java symbolic math library for Android NCalc calculator". It's a fun little language, so I'm wondering if y'all have any tips for golfing in Symja.

~~As per usual, "remove comments", etc, isn't really an answer.~~ It turns out that there is no comment system in Symja, so "remove comments" isn't an answer. :P

# Answer
# Don't Use `Print`...Use the Formatted Output

Here's an example fizzbuzz:

```
For(i=1,i<101,i++,s="";If(Mod(i,5)==0,s=s<>"Fizz");If(Mod(i,3)==0,s=s<>"Buzz");If(Mod(i,5)*Mod(i,3)!=0,s=s<>ToString(i));Print(s))

```

Now, this is alright, but it can be improved:

```
For(i=1,i<101,i++,If(Mod(i,5)==0,s=s<>"Fizz");If(Mod(i,3)==0,s=s<>"Buzz");If(Mod(i,5)*Mod(i,3)!=0,s=s<>ToString(i));s=s<>"\n");s

```

Sure, it's only two bytes shorter, but hey, *it's two bytes shorter*.

Just put all the output into a string and tack a `;<variable_name>` onto the end and you'll have a shorter program (usually).
> 2 votes

---
Tags: tips
---


title: Tips for golfing in Erlang

text:
# Question
Title: Tips for golfing in Erlang
Does anybody have tips for golfing in Erlang? I'm looking for specific things that can be applied to Erlang, not any language. I know we already have tips for Elixir, but that is different.

As usual, please post separate tips in separate answers.

# Answer
## Use the ending conditions

Suppose you have a function reversing a list:

```
r([H|T])->[T]++r(H);r([])->[].

```

Since this is the only condition left, this can be golfed into:

```
r([H|T])->r(T)++[H];r(_)->[].

```

Or, since this is an identity function:

```
r([H|T])->r(T)++[H];r(I)->I.

```

You can also abuse the wild-cards in if statements. E.g.

```
if A<B->A;true->B end.

```

This can be golfed into:

```
if A<B->A;_->B end.

```
> 1 votes

---
Tags: code-golf, tips
---


title: Tips for golfing in Pure Data

text:
# Question
Title: Tips for golfing in Pure Data
Pure data is a graphical programming language designed for audio processing. This makes it unsuitable for most general programming but especially unsuitable for .

It would then be nice to have a question so that people can get a first foot up in this language.

What tips are there for golfing in Pure Data? Answers should apply specifically to Pure Data.

# Answer
## Use a text editor

The editor that comes with Pure Data is really useful for making programs that work or helping you to understand existing programs. However if you want to golf, the files it creates are full of extra stuff that can be removed with an text editor (e.g. vim).

This post will serve as a list of a bunch of small byte saving tricks accessible only through or more easily though a traditional editor.

* **Use defaults on `canvas`:** Your file needs a canvas line. `#N canvas;` is enough to get things to run without error. The missing arguments default to zero.
* **Newlines are optional:** The graphical editor puts newlines between statements. Presumably to make these files somewhat readable. However these are not strictly required and can be removed with an editor.
* **Rearrange your objects for better object indices:** Since connections identify objects by their order in the source, placing objects with a lot of connections earlier in the file can shorten your source. Make sure that you update all the references once you reorder.
* **Put everything in the top left:** Since object location is purely a graphical aid, you can place them wherever. Single digit locations are the shortest so changing the location to `0 0` or something similar will save you. This turns your code into an unreadable blob so it is probably best to do this once everything already works.
> 2 votes

# Answer
# Avoid using `trigger`s to sequence messages

One of the common uses of `trigger` objects is to make the order of execution clear when a single object is sending messages to multiple places. In those cases, since code readability is not a concern for us, you can depend on Pure Data's default behavior which is to send the messages across connections in the order that the connections were created (or if you are using a text editor, the connection that appears first in the file).
> 1 votes

---
Tags: code-golf, tips
---