title: Integers sorted by their digital roots

text:
# Question
Title: Integers sorted by their digital roots
The digital root (also repeated digital sum) of a positive integer is the (single digit) value obtained by an iterative process of summing digits, on each iteration using the result from the previous iteration to compute a digit sum. The process continues until a single-digit number is reached.

For example, the digital root of **65536** is **7**, because **6 + 5 + 5 + 3 + 6 = 25** and **2 + 5 = 7**.

---

Sorting all digital roots doesn't make much sense, since it would just start with infinitely many **1**s.

Instead, we'll create lists of all the single digits integers along with their digital roots, then all double digit numbers along with their digital roots, then the triple, quadruple and so on.

Now, for each of those lists, we'll sort it so that all the integers with digital roots of **1** appear first, then all integers with digital roots of **2** and so on. The sorting will be stable, so that the list of integers with a certain digital roots should be in ascending order after the sorting.

Finally we'll concatenate these lists into one single sequence. This sequence will start with all single digit numbers, then all double digit numbers (sorted by their digital root), then all triple digit numbers and so on.

---

### Challenge:

Take a **positive** integer **n** as input, and output the **n**'th number in the sequence described above. You may choose if the list is **0**-indexed of **1**-indexed.

The sequence goes like this:

```
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 19, 28, 37, 46, 55, 64, 73, 82, 91, 11, 20, 29 ...
72, 81, 90, 99, 100, 109, 118, ...
981, 990, 999, 1000, 1009, 1018, 1027, ...

```

### Test cases:

The test cases are 1-indexed.

```
   n   f(n)
   9      9
  10     10
  11     19
  40     13
  41     22
  42     31
  43     40
  44     49
  45     58
 600    105
 601    114
 602    123
 603    132
 604    141
 605    150
4050   1453
4051   1462
4052   1471
4053   1480
4054   1489
4055   1498

```

Easier to copy:

```
n =    9, 10, 11, 40, 41, 42, 43, 44, 45, 600, 601, 602, 603, 604, 605, 4050, 4051, 4052, 4053, 4054, 4055,
f(n) = 9, 10, 19, 13, 22, 31, 40, 49, 58, 105, 114, 123, 132, 141, 150, 1453, 1462, 1471, 1480, 1489, 1498

```

### Clarifications:

* You may not output all **n** first elements. You shall only output the **n**'th.
* The code must theoretically work for all integers up to **10^9**, but it's OK if it times out on TIO (or other interpreters with time restrictions) for inputs larger than **999**.
* Explanations are encouraged.

It's , so the shortest code in each language wins! Don't be discouraged by other solutions in the language you want to golf in, even if they are shorter than what you can manage!

# Answer
> 16 votes
# Python 2, ~~78~~ ~~60~~ ~~52~~ ~~46~~ 45 bytes

-6 bytes thanks to G B.
-1 byte thanks to Jakob.

```
n=input()
b=10**~-len(`n`)
print~-b+n/b+n%b*9

```

Try it online!

Finally reached a closed form, 1-indexed.

---

# Python 2, 78 bytes

0-indexed.

```
d=10;k=1
exec'\nk+=9\nif k>d+7:k=d;d*=10\nif k>=d:k-=d/10*9-1'*input()
print k

```

Try it online!

# Answer
> 4 votes
# Python 3, 80 bytes

```
f=lambda i,k=1:k>i and sorted(range(k//10,k),key=lambda n:n%-9)[i-k]or f(i,k*10)

```

Try it online!

1-indexed. This is the best I could manage in Python 3 (well, except for the 78-byter, which is a port of my Python 2 solution below; I think this one is much cooler, though). Python 2 full programs are advantaged for this particular challenge, because `input()` needs a conversion to `int` in Python 3 (+5 bytes), `exec` is a function, rather than a statement (+2 bytes) and `/` performs integer division by default if its arguments are integers in Py 2 (+1 byte), so this is *definitely shorter* than porting ovs' answer.

## How it works

**Setup**

```
f=lambda i,k=1:k>i and ... or f(i,k*10)

```

This defines a recursive function **f** that takes one integer argument **i** and another one, **k**, which defaults to **1**. While **k ≤ i**, the function **f** returns **f(i,10k)**, multiplying **k** by **10** each time until it becomes greater than **i**.

**Target range and correct indexing**

```
...range(k//10,k)...[i-k]

```

After this set of operation, we're left with **i**, the initial input and the variable **k** which represents the smallest power of **10** greater than **i**. This way, we are able to generate the (integer) range **\[floor(k/10), k)**, which basically includes all integers that are:

* greater than or equal to the highest power of **10** less than or equal to **i**
* less than **k**, the smallest power of **10** greater than **i**

Since we disregard the integers smaller than **x = floor(k/10)**, we must shift the indexing so that we account for the missing numbers. The obvious way is to subtract their count, **x**, from **i**, so that we index into the list (after sorting, which is described below), therefore having **i-x**. However, since the list contains **9k/10**, items, and indexing in a list at index **-y** for some positive **y** yields the **yth** element from the end in Python, this is simply equivalent to indexing with **i-k**, hence saving 4 bytes.

**Sorting each *chunk* by the digital root**

```
sorted(...,key=lambda n:n%-9)

```

The formula for the digital root function is **1+((n-1) mod 9)** (see the *Congruence formula* section of this Wikipedia article). As **1** would this way be added to each of them, it is superfluous when sorting, so we're left with **(n-1) mod 9**. The way Python's `%` operator works when given negative numbers on the RHS is very convenient, because we can use **n pymod -9** instead to save yet anther byte.

---

# Python 2, 72 bytes

Inspired by Chas Brown's submission.

```
lambda i:sorted(range(1,10**len(`i`)),key=lambda n:(len(`n`),n%-9))[i-1]

```

Try it online!

# Answer
> 4 votes
# Python 2, ~~73~~ ~~71~~ 70 bytes

```
lambda n:sorted(range(10**len(`n`)),key=lambda i:(len(`~i`),i%9))[n]+1

```

Try it online!

2 bytes thx to Mr. XCoder; and 1 byte thx to H.PWiz.

This is 0-indexed.

# Answer
> 4 votes
# Jelly,  ~~15 14 10~~  9 bytes

```
D,Ḣ$‘Ḍḅ9’

```

**Try it online!**

### How?

Uses a golfed version of the closed-form solution created by ovs in their Python answer...

The formula exposed by ovs is: **9\*(n%b) + (n/b) + b - 1** where **b=10floor(log(n,10))**

Now if **c** is the count of decimal digits of **n** then **b-1** is **c-1** nines in decimal.
This is the same as nine times the value of **c-1** ones in decimal (e.g. `111*9=999`).

Furthermore **n/b** is the leading digit of **n** and **n%b** is the rest of the digits as a decimal number.

A formula like **b\*x+y** may be implemented as a conversion of `[x,y]` from base **b**
(i.e. **b^1\*x + b^0\*y = b\*x+y**)

As such we can take a number, **n** (for example `7045`), split it into the leading and trailing digits, placing the leading digit at the end (`[[0,4,5],7]`), add one to all of the digits of the first item to cater for the addition of **b-1** (`[[1,5,6],7]`) convert these from decimal lists to integers (`[156,7]`), and convert that from base nine (`1411`).

In the implementation below we add one to all of the digits of both items when catering for **b-1** (`[[0,4,5],8]`), convert from decimal lists to integers (`[156,8]`), convert from base nine (`1412`) and then subtract the one this process added (`1411`).

```
D,Ḣ$‘Ḍḅ9’ - Link: positive integer, n    e.g. 4091
D         - to base ten                       [4, 0, 9, 1]
   $      - last two links as a monad:
  Ḣ       -   head (modifies the list too)    4
 ,        -   pair (the modified list) with   [[0, 9, 1], 4]
    ‘     - increment (vectorises)            [[1, 10, 2], 5]
     Ḍ    - from base ten (vectorises)        [202, 5] (since 1*10^2+10*10^1+2*10^0 = 100+100+2 = 202)
      ḅ9  - convert from base 9               1823 (since 202*9^1 + 5*9^0 = 202*9 + 6*9 = 1818 + 5 = 1823)
        ’ - decrement                         1822

```

---

Previous, 14 byter:

```
æċ⁵DL,’%9ƊƲÞị@

```

**Try it online!**

This one builds the list up to the next power of **10** above the input by sorting these natural numbers by `[digitalRoot, digitCount]` then finds the value at the inputted index.

# Answer
> 3 votes
# Haskell, ~~94~~ 88 bytes

```
([n|x<-[0..],i<-[1..9],n<-[10^x..10^(x+1)-1],until(<10)(sum.map(read.pure).show)n==i]!!)

```

Try it online! 0-indexed.

**Explanation:**

The list comprehension generates the sequence as infinite list in which we index with `!!`:

* `x` is one less than the current number of digits and is drawn from the infinite list `[0,1,2,3, ...]`
* `i` iterates over the range from `1` to `9` and is used for sorting by the digital roots
* `n` iterates over all numbers with `x+1` digits
* `until(<10)(sum.map(read.pure).show)` computes the digital root (see here for an explanation)
* `n` is added to the list if its digital root equals `i`.

# Answer
> 2 votes
# Pyth,  ~~36 31 25 24 23~~  22 bytes

1-indexed.

```
@o%tN9rFK^LThBlt`Q-QhK

```

Test suite!

### How it works (outdated)

```
@smo%tN9dcU^TKhs.lQT^LTSK – Full program. Q = input.
             Khs.lQT      – Take floor(log10(Q))+1 and store it in K.
          U^T             – Generate [0 ... T^K).
         c                – Cut at locations...
                    ^LTSK – Of the powers of 10 less than K.
  m     d                 – Map over those.
   o  N                   – Sort them by...
    %t 9                  – Themselves decremented, modulo 9.
@s                        – Flatten the result and retrieve the Q'th entry.

```

# Answer
> 2 votes
# Retina, 65 bytes

```
.
9
.+
*
L$`
$`
O$`_(_{9})*(_*)
$2
_+
$.&
N$`
$.&
"$+L`^|\d+"^~G`

```

Try it online! 1-indexed. Explanation:

```
.
9
.+
*
L$`
$`

```

Build up a list of lines of `_`s from 0 until the next power of 10 (exclusive).

```
O$`_(_{9})*(_*)
$2

```

Sort them all in order of digital root.

```
_+
$.&

```

Convert from unary to decimal.

```
N$`
$.&

```

Sort them in order of length.

```
"$+L`^|\d+"^~G`

```

Extract the `n`th element.

# Answer
> 2 votes
# 05AB1E, ~~19~~ 11 bytes

Port of my Python answer.

-6 bytes(!) thanks to Kevin Cruijssen.

```
g<°©‰`9*®O<

```

Try it online!

```
Code           Explanation            Stack
               implicit input         [n]
g              length                 [len(n)]
 <             decrement              [len(n)-1]
  °            10 ** a                [10**(len(n) - 1)]
   ©           store value            [10**(len(n) - 1)]
    ‰          divmod                 [[n // 10**(len(n) - 1), n % 10**(len(n) - 1)]]
     `         push items to stack    [n // 10**(len(n) - 1), n % 10**(len(n) - 1)]
      9*       multiply by 9          [n // 10**(len(n) - 1), n % 10**(len(n) - 1) * 9]
        ®      retrieve value         [n // 10**(len(n) - 1), n % 10**(len(n) - 1) * 9, 10**(len(n) - 1)]
         O     sum the stack          [n // 10**(len(n) - 1) + n % 10**(len(n) - 1) * 9 + 10**(len(n) - 1)]
          <    decrement              [n // 10**(len(n) - 1) + n % 10**(len(n) - 1) * 9 + 10**(len(n) - 1) - 1]
               implicit output

```

# Answer
> 1 votes
# Pyth, 23 bytes

```
@o%tN9rF_mJ^TsdtBl`Q-QJ

```

Try it here.

-3 thanks to Mr. Xcoder

1-indexed.

# Answer
> 1 votes
# Perl 6,  ~~68~~  58 bytes

```
{({|(10**$++..^10**++$).sort({({.comb.sum}…*==*).tail})}…*)[$_]}

```

Test it 0-based

```
{sort({.chars,({.comb.sum}…*==*).tail},^10**.chars)[$_]}

```

Test it 1-based

## Expanded:

```
{  # bare block lambda with implicit parameter $_

  sort(
    {
      .chars,         # sort by the length first

      (  # generate sequence to find digital sum

        { .comb.sum } # one round of digital sum
        … * == *      # stop when the digital sum matches itself (1..9)

      ).tail          # get the last value
    },

    ^                 # Range up to (and excluding)
      10 ** .chars    # the next power of 10

  )[ $_ ] # index into the sequence
}

```

# Answer
> 1 votes
# Ruby, ~~43~~ 38 bytes

```
->x{9*(x%b=10**~-x.to_s.size)+x/b+b-1}

```

Try it online!

Originally a port of the excellent Python answer by ovs, then simplified some more.

# Answer
> 1 votes
# Java 8, 68 bytes

```
n->{int b=(int)Math.pow(10,(n+"").length()-1);return~-b+n/b+n%b*9;}

```

Boring port of *@ovs*' Python 2 answer, so make sure to upvote him!
-1 byte thanks to *@Jakob*

Try it online.

# Answer
> 1 votes
# K4, 38 bytes

**Solution:**

```
-1+9/:10/:'(0;c-1)_1_(1+c:#x)#x:1+10\:

```

**Examples:**

```
q)k)-1+9/:10/:'(0;c-1)_1_(1+c:#x)#x:1+10\:40
13
q)k)-1+9/:10/:'(0;c-1)_1_(1+c:#x)#x:1+10\:601
114
q)k)-1+9/:10/:'(0;c-1)_1_(1+c:#x)#x:1+10\:4051
1462

```

**Explanation:**

Port of Jonathan Allan's solution as I run out of memory building the digital roots from 1 to 1e9.

```
-1+9/:10/:'(0;c-1)_1_(1+c:#x)#x:1+10\: / the solution
                                  10\: / convert to base 10
                                1+     / add 1
                              x:       / save as x
                             #         / take from x
                     (      )          / do together
                          #x           / count x
                        c:             / save as c
                      1+               / add 1
                   1_                  / drop the first
                  _                    / cut at these indices
           ( ;   )                     / 2-item list
              c-1                      / length - 1
            0                          / .. zero
      10/:'                            / convert each from base 10
   9/:                                 / convert from base 9
-1+                                    / subtract 1

```

**Bonus:**

Translation of ovs' solution is simpler but longer:

```
-1+b+/1 9*(_%;.q.mod).\:x,b:10 xexp#1_$x:

```

# Answer
> 0 votes
# Jelly, 19 bytes

```
æḟ©ræċɗ⁵Ṗ%Þ-9⁸‘_®¤ị

```

Try it online!

-1 thanks to Mr. Xcoder.

1-indexed.

# Answer
> 0 votes
# J, 24 bytes

```
(]/:([:+/[:".&>":)^:_"0)

```

This *tacit* expression is wrapped in parens to signify that it should be treated on its own rather than as part of any following expression (like the arguments).

The phrase '\]/:' orders (ascending '/:') the original array '\]' by the sum '+/' of the digits The expression

```
". &> ":

```

converts a number to a character vector with '":', then applies its inverse '".' - character to number - applied to each '&\>' item. So, 65536 -\> '65536' -\> 6 5 5 3 6.

The power conjunction '^:' near the end of the expression applies the code we just explained (on the left) a specified number of times. In this case, the specified number of times is infinity '\_' which means to keep applying until the result stops changing.

The final '"0' means to apply the whole expression on the left to each scalar (0-dimensional) item on the right, which would be the array of numbers to which we want to apply this.

# Answer
> 0 votes
# Elixir, 239 bytes

```
q=:math
e=Enum
r=fn x,f->cond do
x<10->x
1->f.(e.sum(Integer.digits x),f)end end
fn p->e.at(e.at(Stream.unfold({0,[0]},fn {a,c}->{c,{a+1,c++e.sort(trunc(q.pow 10,a)..trunc(q.pow 10,a+1)-1,&r.(&1,r)<=r.(&2,r))}}end),1+trunc q.log10 p),p)end

```

Try it online!

Explanation incoming (slowly)! I don't think it can get much shorter than this, but I'm always open to suggestions

# Answer
> 0 votes
# Perl 5 `-pF`, 27 bytes

```
$_=9x$#F+$_%10**$#F*9+$F[0]

```

Try it online!

Uses @ovs's formula and @JonathanAllen's explanations to come up with a nice compact piece of code.

---
Tags: code-golf, math, number, sequence
---


# Question
Title: Camel Up Cup: An AI board game tournament
## Camel Up Cup 2k18

In this challenge, we will be playing the semi-popular board game Camel Up.

Camel Up! is a board game that has players betting on camels to win rounds, win the game or lose the game, set traps to influence movement or move a camel. Each of these decisions rewards you with the chance of getting some money, which is what determines the winner. Players should use probability, game-state considerations and opponent tenancy to make their decisions. Here is a short video showing players how to play.

## How to play

Here is a rough idea of how to play. Watching one of the videos may be more helpful because they have visuals :)

On your turn you have 4 options.

1. Move a camel. This picks a camel from those who haven't moved and moves it between 1-3 spaces. You get 1 coin. Rounds end when all five camels have moved, they can then all move
2. Place a trap. This goes on the board until the end of round. You choose +1/-1 trap. If a camel or camel stack lands on it they move +1/-1 and you get a coin. You cannot place a trap on square 0. You can place a trap where camels are, although it will only affect camels that land on it after.
3. Round winner bet. You take a bet on a round winner. They win you get 5/3/2/1 depending on if you were the 1st/2nd/3rd to bet on that camel.
4. Game winner/loser. You take a bet on who will be in first or last at the end of the game. you get 8/5/3/1/1 (I think) based on if you were 1st/2nd/3rd/etc to bet on that camel

Notes:

* There are 5 camels. They start on a position randomly from 0-2.
* When a camel is moved (see above for what triggers this) they move 1-3 squares. If they would be placed on a square with another camel they are put "on top" of the other, creating a camel stack. If a camel is to move it moves all camels above it on the camel stack. The camel at the top of the stack is considered in the lead
* If you land on a +1 trap (see above for what triggers this) you move one square further forward. Standard stacking rules apply.
* However if you hit a -1 trap you move one square backwards. You go *under* the stack of camels that are on that square, if any.
* The game ends when a camel hits square 16. This immediately invokes round end and game end triggers
* Game winner/loser bets can be done only once per camel. I.e. you cannot bet on a camel to win *and* lose the game

## Challenge

In this challenge, you will write a Python 3 program to play a four player, winner takes all glory game of Camel Up

Your program will receive the gamestate, which contains:

* **camel\_track**: with the locations of the camels
* **trap\_track**: with the location of the traps (entry of the form \[trap\_type (-1,1), player\])
* **player\_has\_placed\_trap**: an array telling you if players have placed a trap this round
* **round\_bets**: an array of the bets placed this round. Of the form \[camel,player\]
* **game\_winner\_bets / game\_loser\_bets**: arrays of the bets players made for camels to win or lose the game. You will only be able to see the value of players who made the bets, *not* who they bet on. You can know who you bet on. #of the form \[camel,player\]
* **player\_game\_bets**: another representation of the game\_winner\_bets / game\_loser\_bets. Again, only look at the bets that your bot made.
* **player\_money\_values**: an array showing the amount of money each player has.
* **camel\_yet\_to\_move**: An array showing if a camel has moved this round.

On top of the gamestate you also get:

* **player**: an integer telling you what player number you are (0-3).

---

Syntax for what players should return is:

* \[0\] : Move Camel
* \[1,trap\_type,trap\_location\] : Place Trap
* \[2,projected\_round\_winner\] : Make Round Winner Bet
* \[3,projected\_game\_winner\] : Make Game Winner Bet
* \[4,projected\_game\_loser\] : Make Game Loser Bet

This should be wrapped in a move(player,gamestate) method

For instance, here's a player that will make a round winner bet if they are in last place. If they aren't then they will place a trap on a random square.

```
class Player1(PlayerInterface):
     def move(player,g):
         if min(g.player_money_values) == g.player_money_values[player]:
            return [2,random.randint(0,len(g.camels)-1)]
        return [1,math.floor(2*random.random())*2-1,random.randint(1,10)]

```

The game was chosen for several reasons: it has a relatively small pool of options to select from (roughly 20 choices per turn, easily narrowed down to usually about 3-4), games are short and there is an element of luck (makes it so even the "bad" bots can win).

## Gameplay

The tournament runner can be found here: camel-up-cup. Run `camelup.py` to run a tournament or the function PlayGame to run games. I'll keep that repository updated with new submissions. Example programs can be found in `players.py`.

A tournament consists of 100 games per 10 players (rounded up, so 14 players means 200 games). Each game will be four random players selected from the pool of players to fill the four positions. Players will not be able to be in the game twice.

## Scoring

The winner of each game is the player with the most money at the end of the game. In the case of a tie at the end of a game all players with the maximum money amount are awarded a point. The player with the most points at the end of the tournament wins. I will post scores as I run the games.

The players submitted will be added to the pool. I added three really dumb bots and one that I made to start.

## Caveats

Do not modify the inputs. Do not attempt to affect the execution of any other program, except via cooperating or defecting. Do not make a sacrificial submission that attempts to recognize another submission and benefit that opponent at its own expense. Standard loopholes are banned.

Limit the time taken by your bot to be ~10s per turn.

Submissions may not duplicate earlier submissions.

Please don't view game\_winner or game\_loser bets from other players. Its pretty easy to do but still cheating.

If you have any questions, feel free to ask.

## Winning

The competition will stay open indefinitely, as new submissions are posted. However, I will declare a winner (accept an answer) based on the results one month after this question was posted (July 20th).

## Results

```
Player0: 12
Player1: 0
Player2: 1
Sir_Humpfree_Bogart: 87

```

# Answer
## `Sir_Humpfree_Bogart.py`

This is a bot I made for the Camel Up Cup Tournament.

First, they look at all the possible configurations that the camels could end up at the end of the round. Then they determine the expected value of betting on a camel winning the round using

```
EV_roundwin = (chance_1st)*(payout) + (chance_2nd)*(payout) - (chance_3rd_or_worse)*(cost)

```

Then they move camels randomly until a camel wins. After doing this a few thousand times you can estimate the chance each camel will win and lose. Again, we get the expected value of these using

```
EV_gamewin = (chance_1st)*(payout) - (chance_2nd_or_worse)*(cost)

```

The only other options are moving a camel (which always yields one coin, so its expected value is one) and placing a trap. Both teams felt placing a trap was a weak enough option to ignore it entirely. With this information the bots chose the option with the highest expected value.

Since the tournament viewed a second place finish the same as a last place finish it makes sense if you are behind to take chances to get into first place. SBH used distance\_from\_first\_place and nearness\_to\_end to determine how risky the bot should be, where if you are far from first and close to the end then riskiness would be high and if you are in first or far from the end of the game the riskiness would be low. With a low riskiness the bot would decide on an action with a high expected value option and a high riskiness yielding the option with a high upshot. The exact equation was

```
Functional_EV = EV + (upshot-EV) * riskiness

```

where upshot is the highest payout you can get from a decision and riskiness ranges from 0 to 1.
> 1 votes

# Answer
## `players.py`

These are incredibly dumb bots to get the tournament going. They have nearly no logic but act as frameworks for people to use

```
import random
import math
from playerinterface import PlayerInterface

class Player0(PlayerInterface):
    def move(player,g):
        #This dumb player always moves a camel
        return [0]

class Player1(PlayerInterface):
    def move(player,g):
        #This player is less dumb. If they have the least amount of money they'll make a round winner bet
        #If they aren't in last then they'll place a trap on a random square. Still p dumb though
        if min(g.player_money_values) == g.player_money_values[player]:
            return [2,random.randint(0,len(g.camels)-1)]
        return [1,math.floor(2*random.random())*2-1,random.randint(1,10)]

class Player2(PlayerInterface):
    def move(player,g):
        #This dumb player always makes a round winner bet
        return [2,random.randint(0,len(g.camels)-1)]

```
> 0 votes

---
Tags: king-of-the-hill, python, board-game
---


title: Z̡̬a̧̯̔l̆̓g̛̘̟o̡ generator

text:
# Question
Title: Z̡̬a̧̯̔l̆̓g̛̘̟o̡ generator
Write a program or function that transforms an input string into Zalgo text.

For example, for an input string `Zalgo`, a possible output might look like:

> Z̗̄̀ȧ̛̛̭̣̖̇̀̚l̡̯̮̠̗̩̩̥̭̋̒̄̉̏̂̍̄̌ģ̨̭̭̪̯̫̒̇̌̂o̢̟̬̪̬̙̝̫̍̈̓̅̉̇

## Zalgoification specs

* Each letter (upper or lower case) must be zalgoified, and nothing else (spaces, punctuation).
* The combining characters that can be placed on letters here are all those between U+0300 ̀ and U+032F ̯
* Each letter must have a total number of combining characters on it (above and under combined) which is randomly chosen according to a normal distribution of mean 10 and standard deviation 5 (If a negative number is chosen, 0 combining characters must be added).
* Each combining character placed on a letter is chosen uniformly at random between the 48 possible combining characters (see 2nd item).

## Inputs, Outputs

* Input is a single line string that contains only characters between ASCII 32 (space) and ASCII 126 (tilde). No line breaks. You may assume there is at least one letter in the string. The input can be taken as command line argument, function parameter, or STDIN.
* Output is the Zalgoified string. It can be written to a file, or printed to STDOUT, or returned from a function. A trailing line feed is fine. **The output doesn't have to display properly in your interpreter/whatever, as long as when you copy it to a Stack Exchange answer it displays properly like here**.

## Test cases

* The Zalgo example above.
* Input: `Programming Puzzles & Code Golf`

Possible output:

> P̢̭̟̟̮̍̅̏̍̀̊̕̚̚r̢̫̝̟̩̎̔̅̈̑o̡̠̣̪̠̍̈̐̏̌̆g̡̬̯̟̠̩̎̐́̅̚ȑ̢̨̩̠̙̭̤̩̟̔̕ą̟̟̯̠̪̜́̉̒̎̂̍̃́̚̚̚m̪̈̅̈m̨̛̛̪̤̟̔̍̓i̢̛̬̠̠̇̈̂̓̒̀̋̔̚̚n̛̝̩̜̓̐̑̅̅g̨̩̪̊ P̨̧̢̟̙̮̋̆ų̨̙̞̙̫̤̫̭̊̓̒̃̒̚z̜̤̮̪̫̄̌̃̈̉̑̋́̕z̡̥̯̠̬̜̥̑̌̓̌̋́̅ľ̫̙̟̪̖̉ė̢̨̘̦̘̖s̛̜̙̘̚ & C̨̠̟̯̟̙̠̉̄̄́̄̑̈̔̆̀ö̭̟̗̯̥̏̐̄̏̌d̞̬̀̆́̀é̟̙̩̗̙̣̋̎̌̌̋ Ğ̨̡̧̡̣̪̝̝̘̩̮̉̋̀̉̉̕̕ọ̠̠̘̟̑̇́̀̃̎̓̋̚ḽ̡̢̟̪̥̍̍̅̀́̎̆̕f̧̢̪̠̠̀̉̒̍̍̊́

* Input: `Golf is a club and ball sport in which players use various clubs to hit balls into a series of holes on a course in as few strokes as possible.`

Possible output:

> Ǧ̡̧̄̐̊ò̡̞̟̖̌́̄́̆̈̒l̡̬̣̜̫̞̘̪̇̈̏̊̆̃̑̉̓̒f̙̐̍̇́̐̍̉ į̦̘̝̣̊̒̎̚s à̡̛̠̜̙̣̙̞̣̗̯̝̘̩̅̊̓̄̒̃ ć̬̗̫̯̫̎́̚l̒̎̋ű̯̜̑̎b̯̣̮̭̤̃̊́ a̡̨̟̘̭̣̍̈̀̃̎́̐̋̆̂ń̨̖̭̝̬̘̦̣̓̇̚̕d̨̤̣̙̜̪̖̪̍̓̔̍̔̃̒̍̆̏̚̚̕̚ ḃ̬̪̇̕a̡̟̖̬̬̖̬̋́̎̎̔̄̏̒̑̚l̨̖̜̬̠̭̭̇l̡̡̛̛̬̤̆̔̑̍ s̠̙̣̠̖̜̜̅p̤̖̃́̅̕̕ǫ̢̥̬̠̞̭̭̘̟̞̋̊̌r̡̛̞̬̈̇̑̎̄̚t̟̩̏̀ ï̡̧̢̨̜̜̝̝̜̜̫̔̇̂̔̐n̞̖̫̪̟̤̦̫̂̓̍̑̆̒̚ w̨̧̟̠̯̜̙̘̏̎̈̆̂̅̔hi̧̝̖̗̖̒̆̆̈̚ć̪̜̫̖̠̣̞̋̈́̀̌̋h̢̢̨̥̮ p̜̣̋̔̆l̨̧̛̘̫̝̙̠̯̂̑̌̈̒̐ā̩̗̟̐ẏ̢̛̫̠̦̤̫̞̦̯̥̜̀̀̈̅̉̈̄ẹ̡̑̔̄̉̀̎̒̑r̛̫̭̤̋̄̓̀̅̓ș̜̯̆̋̒̍̔ ų̛̘̭̜̝̈̃̂̅̌̍̆̚s̡̡̡̨̫̥̪̋̈̀̀̆ê̢̡̡̥̖̮̞̫̪̥̘̥̯̎́ v̡̢̢̟̠̞̬̥̩̣̫̫̦̞̂̐̓̇ặ̢̧̙̝̥̪̗̆̎̓ŗ̦̙̩̑̒̕í̫̣̊̚ō̡̧̤̘̟̩̠̫̗̃̍̉̊̕ụ̡̪̠̈̈́̊̅s̢̢̘̤̝̪̀̎̅ c̡̢̛̖̫̗̑̒̆́̎̚l̥̥̖̘̉̎̓̔̀̔ų̘̘̣̟̃̆̓̉̏̅̓̂́̇b̡̝̗̙̗̮̖̩̗̦̏̌̏š̛̮̣̮̜̒̓̌ ṭ̣̫̗̮̙̈̔̅̂̎̃̌̈ò̮̘̍̅̃̃̅̚̕ ḩ̜̞̮̠̇i̮t̝̗̦̖̮̞̗̩̞̤̎̍̒̐ bȁ̢̮̩̝̣̉ļ̛̮̘̏ĺ̨̖̮̑s̢̬̪̗̬̖̟̅̀ i̢̗̖̊̃ń̨̧̛̫̮̞̎t̡̗̞̩̙̑̐̏̔̏ơ̧̯̮̦̖̇̆̔ ạ̧̉̍̚ s̤̬̫̠̉e̎̃r̟̪̥̗̜̥̍̆̍̇̕̕i̧̧̭̝̫̪̯̖̞̪̅̇̎̈̐̅̍ȇ̟̬́̄̃̐̊̕s̢̢̛̝̤̙̭̘̩̩̍̑̂̈̀̀̍̄̔̒̒ o̡̢̘̩̣̅̐̆̌̂̉̇̆̋̕f̡̯̜̝̘̮̠̖̐̂̒̃̚̕ h̪̘̫̪́ǫ̭̦̔̋̆̚̕l̢̡̧̨̙̯̤̔̅̓̆̑̍́ȅ̪̬̝̙̅̋̍s̪̖̭̫̪̟̖̐̀̕ ǫ̦̠̫̍̊̉̄̚n̐̎̂̀ ą̡̛̛̤̦̪̣̭̈̐̂̎ c̪̩̠̗̟̜̘̐̂̈̐̑̏̈ọ̡̡̙̫̞̜̐̇̄̓̏u̥̖̙̝̔̂̎̅̚̚r̙̜̬̭̠̮̙̙̪̫̝̙̬̥̥̯̐́̈́̊̈̍̍ș̀́e̞̜̒̌̚ ĩ̧̦̝̪̆n̛̞̞̆̆̀ a̟̅̐̈̍̉̚̚̕ş̫̭̍̐̚ f̘̝̠̪̦̜́̌̍̇̀̕e̩̫̣̊̎̇̚w̪ ŝ̨̨̠̠̝̦̣̜̦̗̮̞̞̥̥̅̄̄̕t̢̡̢̙̞̟̩̭̤̅̎̌̒̃̇̕r̞̤̙̄̊̃̇̅̈̏̈̌ǫ̝̬̀̋̏̐̌̈k̡̢̧̪̭̝̙̆̈̒̀ȩ̛̙̣̠̗̞̮̅̅s̙̣̒̉̎́̂̅ à̧̛̖̘̞̫̘̎̃̀̑̎̕̕s̢̟̟̭̩̈̏̇ p̣̟̭̗̪̜̫̦̝̣̎̋̎̀̐̏o̧̢̪̮̤̦̎́̐̒̀̚̕s̛̯̦̗̬̬̊̊̄̓̐̉̏́̚s̢̠̣̬̥̬̔̅̕̕i̡̠̣̣̫̞̣̮̥̟̅̎̇̄̋̌̌̇b̡̧̡̖̖̃̄̋̈̋l̢̢̙̪̣̉̉̐̑̆ẹ̢̒̎.

## Scoring

This is , so the shortest answer in bytes ẁ̨̛̭̙̥̖̏̏̐̐̉̃̅̚i̜̟̭̤̞̘̗̐̐̔̈̍̋̏̚n̘̯̥̩̗̯̠̘̮̋̈̃̀̊̉̎̈̕s̛̬̦̙̮̩̜̄̑̐́̎̆̚.

# Answer
# CJam, ~~57~~ ~~56~~ ~~49~~ 47 bytes

*Thanks to Sp3000 for saving 7 bytes.*

```
q{_eu_el={Pmrmc1.mrml-50*mq*A+mo{48mr'̀+}*}|}/

```

Test it here.

# Explanation

This uses Box–Muller for the normal distribution: the basic algorithm generates two uniform variables in the range `[0,1)`, `U` and `V` and then computes two normally distributed values from them. We only need one and the simpler one is `X = √(-2 ln U) cos(2πV)`. This generates a distribution with mean `0` and standard deviation `1`, so we need to multiply it by `5` to correct the standard deviation and add `10` to correct the mean. We can also simplify the cosine, because omitting the `2` gives the same distribution. So we compute `X = √(-50 ln U) cos(πV) + 10` before rounding to get the number of combining marks.

Here is the code:

```
q{          e# For each character in the input...
  _eu_el=   e#   Make an upper case and a lower case copy and check if they are equal.
  {         e#   If they aren't... (i.e. if this is a letter)
    Pmr     e#     Generate a uniformly random value in [0,π).
    mc      e#     Take the cosine.
    1.mr    e#     Generate a uniformly random value in [0,1).
    ml      e#     Take the natural logarithm.
    -50*    e#     Multiply by -50.
    mq*     e#     Take the square root and multiply by the cosine.
    A+      e#     Add 10.
    mo      e#     Round to nearest integer.
    {       e#     That many times...
      48mr  e#       Generate a uniformly random integer in [0,47].
      '̀+    e#       Add it to the first combining mark.
    }*
  }|
}/

```

This means we just dump all the characters and combining marks on the stack in the correct order, where they are printed automatically at the end of the program.
> 37 votes

# Answer
## Python3, ~~162~~ 156 bytes

```
from random import*
q=lambda z:''.join([v,v+''.join(choice(list(map(chr,range(768,815))))for i in range(int(normalvariate(10,5))))][v.isalpha()]for v in z)

```

Possible usage:

```
print(q(u"Programming Puzzles and Code Golf"))

```

I import random, generate a string of all combining characters, return a random subset of combining characters according to mean 10, stddev 5 normal distribution and append to each alpha letter in then string, then join the results.

Test input:

```
Programming Puzzles and Code Golf

```

Test Output:

> P̡̣̝̬̞̃̏̋r̫̤̒̇̋̂̉̔̂̕ó̘̫̔g̭̤̝̖̅̏̍̆̇̍ȑ̮̭̃̎̒̄̅̊̚ḁ̉̅̎̑m̧̠̤̎̒̅̂̓̒m̨̮̏̐̓̐̇ī̘̌́̄̆̋̏̉̇ń̝̀̑̔̅̏́̑̕g̢̞̬̥̜̩̖̎̍́ P̨̞̮̭̂̄̄ử̝̔̍̋̀̕zž̧̥́l̩̫̣̉̊̍̋̐̊̌ĕ̡̛̤̖̤̄̅̈̚s̨̨̞̝ ą̙̦̖̄̓̊̌̉̌n̢̙̜̪̤̣̪̔d̘̙̠̝̫̭̜̑̔̕ C̢̛̝̦̬̝̈̄̏̏ȏ̡̇̓̐̎̆̉̌̄d̗̝̞̤̟̭̓̐̈̕ė̡̛̜̥̥̠̟̦̌ G̖̟̘̅̄̈́̚o̧̗̬̗̥̞̙̐̌̊l̢̞̖̟̑̇f̢̛̩̀̒̃̌̈
> 14 votes

# Answer
# MATLAB, 89 bytes

Credits go out to DankMemes, but as I am not able to comment yet I'm forced to place my improvements w.r.t. his MATLAB submission in a separate answer.

```
function o=z(a),o=[];for c=a,o=[o,c,randi(49,[1,isletter(c)*fix(normrnd(5,10))])+767];end

```

Slightly more golfed by replacing the newlines with commas and semicolons (which also suppresses the intermediate outcomes from the loop).

* *9 bytes* can be won by replacing **isstrprop(c,'alpha')** with **isletter(c)**.
* We don't need the dots in front of * and +, as we multiply with a scalar. That's another *2 bytes*.
* **fix** instead of **floor** for *2 bytes*. It does give a slight bias towards 0 though, so alternatively **ceil** can be used to gain *1 byte*.
* I changed the random character pick to work with random integers between 1 and 49 to reduce the amount of operations and save some additional bytes.

Using it with

```
z('Simple check for proper functionality results in this beautiful text!')

```

Results in

> Ś̜̬̭̃̑̓́̃i̩̰̗̙̫̜̇̀̑mplë̥̟̣̩̙̗̐̌̇ cḧ̢̛̰̝̣̝̋̋̑eç̛̞̖̖̰̰̝̭̞̜̝̥̋̎̇̄̂̆̆̔̎̊k̢̟̠̞̈̌̂ for̢̡̫̥̩ ṗ̝̥̗̬̯̯̝̍̑̈̊rop̡̡̨̢̝̫̤̠̫̠̏̎̄́̒ė̦̋̕ŕ̦̣̇̊ f̧̜̦̏̏̉̇unc̨̢̗̟̙̩̝̠̄̈̋̑̏̎̄̇̌̒́̇̚ti̝ỏ̧̯̰̥̣̜̎̓̀̊̔̒̉̔̑̑̔̋̚n̡̘̠̮̤̖̥̤̂̔̇̇al̩̫̇̇̔it̫̮̔̎̕y̡̰̰̦̔̇̏̎̋ r̛̙̯̉ĕ̬̟̉̓̌s̛̝̝̭ul̨̧̧̛̙̤̥̜̟̞̔̓̓̊̀̂t̡̠́̓̀̉̎̒̈̚ş̗̠̋̍̏̌̎̕ ǐ̛̗̭̪̤̃̏̍̎̈̓̐̚n̞̮̞̬̝̭̎̔̍ th̢̧̛̬̬̖̠̗̮̰̠̖̖̠̞̦̞̎̄̓̎̇̆̚̕is̟̬̍̂̎ bea̭̗̝ṳ̝̞̠̦̣̤̦̅̂̒̄̒̔̉̏tỉ̪̩̅̓̂f̢̝̰̬̤̰̊̊̉̎̕̕u̡̝̇l tex̰̤̥̍̕t̡̝̥̣̟̩̟̉̂̆̋̈̈̈̍̔!
> 13 votes

# Answer
# Javascript (ES6), ~~199~~ 196 bytes

Uses a Box-Muller transform for the normal distribution (which ends up taking a lot of space, unfortunately. JS is not the best language when it comes to normal distributions)

```
i=>i.split``.map(e=>e.match(/[a-z]/i)?e+Array((i=~~((M=Math).sqrt(-50*M.log((R=M.random)()||.1))*M.cos(M.PI*R()||.1)+10))<0?0:i).fill().map(f=>String.fromCharCode(~~(R()*48+768))).join``:e).join``

```

Fiddle

Edit: I made a mistake and had to add one byte. This should now zalgoify capital letters as well as lowercase ones.

Edit 2: Simplified the transform as in Martin Buttner's answer.
> 11 votes

# Answer
# Perl, ~~81~~ 79(?) bytes

Gee, you guys are all using variables! Who needs variables? :)

Here’s the simple code, which is just 79 bytes, most of it taken up by silly identifiers(but not variables :):

```
use Math::Random;s/\pL\K/(x x random_normal 1,10,5)=~s,.,chr 768+rand 48,reg/eg

```

Which, written more normally without compression, might be:

```
use Math::Random;
s{
    \pL         # find a Letter
    \K          # and Keep it, so the insertion point is right afterwards
}{
    # make a string of x's and replace each with a random combining character
    ("x" x random_normal(1,10,5)) =~ s{
            .  # take any character, including our x
        }{
            chr( int(768 + rand(48)) );
    }xreg;
}xeg;

```

## How It Works

1. Load the Math::Random module, importing the *random\_normal* function.
2. For each letter of the input:

1. Get 1 random real number from a normal distribution whose mean is 10 and whose standard deviation is 5.
    2. Create a string containing as many *x*’s as the integer truncation of that random normal real number.
    3. For each of those *x*’s:
        1. Generate an evenly distributed random real number in the range \[768, 768+48).
        2. Derive the character whose code point is the integer truncation of that random number.
        3. Replace the current *x* with that character.
    4. Place the resulting string of combining characters after that letter.

## How to Count?

But I’m not quite sure how to count it because I’m not clear on the output requirements and the function requirements and how these impact counting.

## File Execution

The solution above transforms its input and leaves the result where it is using the normal input space as with *sed*. If you want it printed, you would need to add a `-p` switch.

So for example, if you put that in a file named *zalgo* then you could test it this way:

```
echo These are not the zebras you are looking for. |
perl -p zalgo

```

which produces

> # T̛̝̠̟̙̭̗̮̘̠̪̖̤̍́̇ĥ̫̞̥̙̞̈̈e̢̨̛̟̥̥̫̐̒̄s̛̮̊̒̆́ę̨̛̪̗̝̙̥̘̯̈̃̏̑̄̆̍ à̢̨̖̫̟̮̂̍̒̍̓ř̛̜̌̎̅ȩ̛̗̣̗̬̒̉̄̇̉ n̥̟̪̪̙̞̠̝̪̄̓̅̈̎ȏ̧̭̭̫̤̥̒̉ţ̛̛̜̅̔̏̍̆̓̊̔̍̍̕ t̝̬̜̫̦̜̭̄̀̂̈̎ȟ̛̗̭̌̏̐̍̀̚ē̯̬̙̖̘̒̕ z̡̨̛̯̠̥̪̣̤̟̐̍̀̉ë̬̫̪̟̟̔̚b̗̝̣̎́̚r̞̟̋ã̢̛̪̪̗̝̞̝̃̄̄s̡̢̧̛̙̖̙̘̊̐́̀̎̚ ÿ̢̪̥̤̮̫̏̇̌̆o̡̜̝̓ŭ̜̖̦̥̦̞̑̏ á̡̤̫̞̟̥̘̒̔̋̑̐r̛̛̮̥̘̫̅ȩ̦̗̞̯̮̄́̂̈ ľ̠̉̈̀̒̚ò̖̘̖̉̋̀̊̔̏̇̕o̡̦̦̜̫̫̬̅̇́̌̏̚k̡̪̔̄̉̍̄̋̂̊ȉ̢̨̙̭̥̫̟̉̑́̏̌̚̚n̜̣̎̄̄̐̈̋g̖̞̭̘̜̞̑̂̃̅̅ f̡̧̡̛̤̓̀̏̚o̓ṙ.

I’ll revise the byte count once I learn how you’d like this to be counted.

---

## Zalgotic Beowulf

If might be better to test this on something with more interesting letters so show that it doesn’t get stuck on some 1960s notion of what letters are. For example, it should be well-behaved on stuff like *æþelingas*. So given this text with the three first lines of *Beowulf*:

> Hwæt, we gar-dena in geardagum,
> þeodcyninga þrym gefrunon,
> hu ða æþelingas ellen fremedon!

Here’s how to make a zalgotic Beowulf:

```
perl -p zalgo beowulf

```

Which emits:

> H̝̙̓̒w̢̩̞̫̠̖̍̅̉̚̕̚æ̛̖̭̭̝̊̄̒t̢̬̩̒̑̑̇̔, w̨̢̢̘̥̎̆̑̉̐̇̃́̃̌ę̛̛̩̥̩̣̗̮̜̗̋̂̋̒̒̑̆̆̑̒̀ g̗̦̟̯̑ā̖̦̮̀̐̏̓r̢̫̄̈̊̉-d̨̗̪̜̃́̂̅̕ḙ̡̨̠̣̠̣̎̉̄̊̐̒̂̏̓̔n̟̤̫̓̄̉̓̔ą̗̪̃̈̔ i̡̤̤̣̠̮̍̚n̨̟̝̥̊̈̌̀̏̂̌̍ g̡̛̜̘̮̈̋̈̂̒̓̕e̢̞̤̐̒a̢̨̪̟̟̘̦̗̬̓̐̉̎́̏̓r̡̫̙̐̑̉ḋ̛̖̮̫̜̫̒ą̢̣̮̦̪̙̮̙̠̏̂̎̄̉́̅̚g̛̭̣̩̜̙̓̑̎̊̑̏̏u̡̢̞m̡̫̝̞̗̟̞̈̉̆̋̒,
> þ̢̧̛̩̟̬̘̣̟̦̣̃̊̋̌̎ḙ̭̖̋̊́̎ọd̪̙̉c̝̭̩̦̠̓̅̅̍̐ỷ̖̞̥̦̐̍̏̄́n̬̥̥̣̗̂̀̄̕ĩ̡̡̗̞̩̗̋̒̆̏ṅ̢̢̫̬̝̑̉̌̈̌̐ĝ̥̭̬̤̇̂̅̎̂̅́̊̇ā̫̦̥̗̙̙́̀̕ þ̢̙̥̝̬̖̣̦̬̗̗̎̌̓̄̐̑r̡̢̨̯̬̮̝̮̜̩̃̉̅̐̀̑̓̐̉̈y̖̜̫̠̜̐̕m̧̟̜̣̘ g̢̧̪̗̫̘̖̃̍̓̑e̡̯̓f̛̬̥̔̌̒ř̨̜̙̠̥̒́̋ú̗̘̊̆̆̄̕̕n̢̛̜̫̍̐̐̋̉o̤̘̬̜̥̖̜̫̎̋̔̏̍̀̋̉n̨̧̮̆̑̅̇,
> h̨̬̪̝̭̀́̐̕̚̚ú̜̖̭̭̯̘̗̠̊̊̆̌̀̀̕̕̕̚ ð̦̦̤̠̬̖̏̉̑̓̆̍̒̋̚̕ẳ̧̫̦̚ æ̯̙̘̣̯̋̆̑̑̀̅þ̢̝̣̯́̆̇̈̐̊̅̈ệ̗̙̣̙̪l̢̧̝̗̦̖̟̔̄̐̄̊̚i̡̬̝̘̜̍̉̏̑̍̊̐̋̔̉ņ̥̩̣̋̐̊̇̔̎̉̋̓ģ̝̬̯̪̥̞̪̃̅à̧̨̤̫̖̊̅̓̄̑̏̊̋̚̚s̨̡̥̭̞̙̎̓ ê̜̆̊̆́l̘̪̟̙̙̝̎̀́̂ľ̢̛̬̥̗̋̀̐̅̎̔̔̄̉ẽ̡̨̤̬̭̦̞̤̯̬̍̀̋̚ň̢̨̖̘̣̖̝̞̙̍̀̆̄̂̕ f̩̘̦̦̜̦̞̑̏̄̋r̘̓ẹ̤̠̟̀̅̔m̢̪̮̙̗̆̉̒̚̕̚e̎d̬̘̓̒̈̆̓̒̄̑̚ò̡̝̥̮̯̝̜̯̜̘̞̑̐̌̇̓̐n̪̣̗̤̈̎́̆̊!

---

## All CLI, No Files

If you wanted to go all command line, you could inline it this way:

```
echo "This particularly rapid unintelligible patter isn’t generally heard and if it is, it doesn’t matter." |
perl -CS -MMath::Random -ple's/\pL\K/(x x random_normal 1,10,5)=~s,.,chr 768+rand 48,reg/eg'

```

and generate this from it:

> # T̢̜̪̜̬̥̝̂̉̆̈̏̏̒̂̋̊̕h̢̛̙̝̦̥̫̉̌̑̐̚į̧̧̪̀̉̌̐š̙̗̘̑̉̒̋̈̍̐̊ p̡̛̛̗̞̜̙̔́̊̊̊̆a̬̦̫̠̦̜̐̂̈́̅r̢̩̩̝̣̖̔̊̇̈t̢̘̫̪̜̄̍̏̌̄̚i̞̟̜̊̍̒́̄̂c̟̑̑̃̌̋ư̧̫̫̝̠̟̦̎̋̍̓l̛̥̞̖̟̩̈̋̈̍̍a̢̜̦̘̫̓̉̇̂̇̒̓̆ȓ̪̤ļ̬̫̟̣̬̬̆̃y̌ ŕ̩̞̟̖̝̬̟̪́̒̐̔ȧ̡̟̖̙̤̜́́̎̍̀̒̌̋p̪̤̦̜̒̉̈̌̌̆̇̉̚ỉ̧̡̟̪̔̔̀̈̅̆ḑ̖̣̐̆̍́̃ ṳ̩̗̫̦̦̗̤̅̃̒̊̆nį̧̢̫̪̦̩̞̞̎̉̅̇̆̔́̋̐̍ņ̡̧̛̩̘̪̪̪̎̈̕̕t̥̤̬̩̦̓̄̍̑̇̄e̡ĺ̢̠̓̂̇̅̐̚ľ̗̭̝̪̀̅̕í̤̬̥̙̭̠̊̅́̒ģ̩̬̣̃̐̆̇̓i̛̗̦̭̙̝̐̔̇̄̉̄̇bl̖̭̘̣̙̤̇̎̔̅̒̔̚e̘̤̖̞̎̎̅̍̕ p̧̢̡̟̠̜̬̩̃̀̆̃̆̍a̧̡̭̙̥̤̟̟̔̄̎̔̓̕t̖̦̎̊̏̉̕ţ̤̥̦̝̜̭̤̈̆̊̓̈̊̎̚ȇ̡̛̖̈̊̓̎̕r̟̫̍̒̅̈̈ i̧̘̪̠̟̗̙̭̍̇̄̊ş̛̩̖̦̬̞̣̤̘̫̓̊̆̈̌̓̐̎̕n̡̧̜̥̤̪̩̋̇’t̓̈̑̀̈̔̈̐̔̊̒ g̛̤̋̇̋ę̢̛̛̠̤̥̟̞̣̫̞̬̝̙̐́̂̂̍̕n̩̟̙̞̖̭̫̂̂̌̃̔̉̑ȩ̗̥̥̠̂̈̉̅r̪̫̩̂̀̄aḽ̢̜̖̝̌̇̓́̒̑ļ̢̧̫̦̥̬̤̑̎̒̒̓̑̚̚̕ỳ̛̥̖̭̍̐̃̑̍ h̖̬̠̠̝̜̝̪̗̒̊̊̋̄ȩ̛̞̭̪̜̤̟̘̣̅̆̃́̂̔a̛̝̕r̝̦̅̅̍̍̎̂̊ḑ̩̞̬̘̪̝̝̍̏̂̓̔̄̑̕ ą̡̧̬̞̝̟̍̓̉́̈̀ň̛̟̩̙̈d̡̜̥̣̦̫́̅̌̚ ĩ̖̜̔f̧̅̌ į̡̢̪̬̫̟̜̄̑̑̓̊̚̕̚t̪̘̦̩̐̄́̐ ỉ̥s̪̝̤̀̈̚, ǐ̪̭t̛̬̭̝̋̄̋̇̏̉̆̚̕̕ d̝̗̭̓̒̂o̡̝̙̒̅̒̏̉̚e̢̦̦̝̘̘̣̔̓ş̛̤̤̊̇̃̋̎ṅ̨̧̬̤̜̚’ţ̪̗̭̘̟̝̔̋̑̀̇̃̈ m̢̛̦̭̖̥̪̫̙̤̈̅̏̃̂̆̋̈̌̕ả̛̜̝̝̗̣̦̅̚t̫̤̜̘̒̅̅̚t̪̬̗̘̑́̔̓̏̅̉̆ȇ̡̦̘̣̘̭̖̞̥̄̔̑̆̂̃̀̀̍̇̉̚̕r̛̭̙̘̬̉̄̆̉̇̅́̕̕.

---

### The Fine Print

To really make this work well, you may need to have something in your environment or on the command line or in the file to say this is Unicode throughout. That might be `-CS` or `-CSD`, or `PERL_UNICODE=S` or `PERL_UNICODE=SD` depending on which way you’re going at it. However, because the problem says we don’t actually have to print anything, and that the input is mere ASCII, these are not needed for the small specific case given in the problem description.
> 11 votes

# Answer
# Groovy, 201 196 182 174 170 154 146 130 129 124 bytes

My first golf, not really aiming to win here but figured I'd give it a shot anyway.

Run it as `groovy zalgo.groovy 'input'`

```
o='';r=new Random();args[0].chars.any{o+=it;if(it.letter)(r.nextGaussian()*5+10).times{o+=(char)(768+r.nextInt(48))}}print o

```

Ungolfed (with syntax highlighting):

```
// By making this a Groovy script, the weight of
// a full Java-like class definition can be avoided
////
// Originally, this part of the answer used the 'def'
// keyword to infer the type of the variable, but it
// turns out you can define a variable in Groovy
// without any type at all.
buffer = '';
rand = new Random();
// There used to be a for loop here using def, but now it's a
// .any closure. .any saves a byte over .each.
////
// Groovy automatically defines an args variable for
// scripts, which we use here.
args[0].chars.any {
    // As in Java, += works on a String. Previous versions of the
    // answer used a StringBuffer, but a String works just as well.
    buffer += it;
    // Another Groovy extension; we can use the primitive char like
    // a Character object, and use .letter instead of .isLetter()
    if (it.letter)
        // Since Gaussian is already a normal distribution with mean 0
        // stddev 1, we can fix that with a quick multiply and add.
        ((rand.nextGaussian() * 5) + 10).times {
            // I use the literal number '768' here, as it's the same size
            // as a Java char literal, and Groovy doesn't have char literals.
            buffer += (char)(768+rand.nextInt(48));
        }
}
// Finally, we can take a quick shortcut here by using the
// parentheses-less syntax for print in Groovy. Using print
// instead of println saves a whole two bytes!
print buffer

```

Example output:

> P̊r̡̜̋̎̎̆ȍ̧̨̖̣̖̠̪̬̘̂̚g̩̯̗̈̃̆r̡̮̭̬̙̟̟̭̗̅̐̀̑̕ą̢̛̜̗̗̩̂̓̂̎̕m̝̬̊̂̒̐̕m̤̠̪̣̍̓̍̂̍̚į̫̣̞̝̬̪̘̟̎̅̒n̛̬̦̗g̝̦̏̇̏̀̆̓ P̨̨̡̉́̓̒̕ų̠̤̪̬̘̪̪̤̪̏̀̎z̛̜̀̒̐̕ž̛̙̮̩̔̌̉̉̎̍́̑l̨̡̤̗̮̜̣̬̩̜̜̭̦̈̒̊̃̊̌̉ȩ̘̬̖̞̗̦̘̪̬̇̅̅̈s̒̄́̌̎ & Ĉ̢̣̜̗̟̤̌̒ơ̡̜̪̖̫̂̉̍̆̐̊̇̔̍̕̚d̛̛̦̫̫̯̥̯̭̍̋̔̆̂̕ê̫̪̆̍̒̄ G̙̪̅ȏ̢̥̖̘̦̟̜̪̈̔̌̑l̯̘̞̅f̬̗
> 7 votes

# Answer
## Moonscript - 118 117 112 110 105 96 bytes

This needs to be saved as Latin 1, but generates utf-8. It uses the central limit theorem to approximate the normal distribution. `math.random!` returns a number with a uniform distribution 0 to 1, which has a mean of 0.5 and a standard deviation of 1/sqrt(12). If we add 300 samples, we get a number with a mean of 150 and a standard deviation of 5, with an approximately normal distribution. We subtract 140, and the distribution now has the correct mean.

In utf-8, the character codes U+300 to U+32F are encoded as 11001100:10000000 to 11001100:10101111. So it is the byte 204 followed by a random byte 128 to 175.

```
r=math.random
=>@gsub '%a',(b=-140)=>
 b=b+r!for _=1,300
 @=@..@.char(204,127+r 48)for _=1,b
 @

```

This is a code block which returns an anonymous function taking one argument, the string, and returning the zalgo-fied version. Assuming this is saved in zalgo.moon, a full program that uses this would be:

```
print require'zalgo' io.read!

```

Edit:

* Turns out it's cheaper to use char code 204 instead of an embedded Latin 1 character.
* Can access string.char using a.char
* Switch to command line args, rather than stdin.
* use method for implicit parameter @.
* Switch to a function that returns a value
> 6 votes

# Answer
# MATLAB, 106 bytes

I thought I'd submit another answer from a language which actually has a built in normal distribution function. I don't think I've ever tried MATLAB before so this may not be the most golfed it can be.

```
function o=z(a)
o=[]
for c=a
o=[o c floor(rand(1,floor(normrnd(5,10)*isstrprop(c,'alpha'))).*48.+768)]
end

```
> 6 votes

# Answer
## AutoIt - (sad) 219 bytes

```
dim $r=random,$f
for $u in stringsplit($i,"",3)
do
dim $a=2*$r()-1,$b=$a^2+(2*$r()-1)^2
until $b<1
$f&=$u
for $m=1 to $a*sqrt(-2*(log($b)/$b))*5+10
$f&=stringregexp($u,"\p{L}")?chrw($r(768,815)):""
next
next
clipput($f)

```

What's really bloating up the code is the distribution calculation. I cheated a bit by writing the output directly to the clipboard, because `clipput` is the shortest output function in AutoIt. The RegEx `\p{L}` matches all letters.

---

You have to supply the input using a global variable `$i`:

```
$i = "A study in scarlet."

```

yields

> Ą̣̘̤̪̜̮̎̊ s̭̫t̡̢̢̡̢̩̝̙̍̏̂̇̎̍̂̈ǖ̮̮̭̬̋̕ḑ̦̗̟̄̀̒̌̂̕y̨̧̙̪̩̎̀̓̋ į̣̦̥̮̔̈̃̅̐̌n̗̜̑ s̘̦̞̘̗̠̣̤̏̊̐c̨̡̛̭̝̬̭̜̟̥̝̮̍̄̊̎̔á̡̬̤̠̦̠̗̟̆̍̄̈̕r̛̤̥̬̠̋̍̒̚ļ̨̞̫̤̆̊̋̑ë̟̪̝̞̑̌̎̆̓̇̇̀̚̕t̢̖̟̞̟̘̮̅̎̂̐.
> 5 votes

# Answer
# Javascript, ~~190~~ ~~169~~ 136 bytes

```
function q(z){var o="",r=Math.random;for(var v in z){o+=z[v];for(var k=0;k<r()*100;k+=r()*10){o+=String.fromCharCode(768+~~k)}}return o}

```

usage :

```
var d=q("There is snow on the ground \
And the valleys are cold \
And a midnight profound \
Blackly squats o'er the wold; \
But a light on the hilltops half-seen hints of feastings un-hallowed and old. \
")

```

output :

...

> T̡̗̙̀̅̎h̀è̇̋r̖̀̄̉̍̔̕è̀̅̉̏ ̀ì̘̟̥̫̱̀̇̐s̖̟̦̀̀̀̉̊̍ ̗̀̇̉̎̕s̗̀̃̈̊̑ǹ́̈̍̏̐ò̅̈̎ẁ̃̅̋ ̀̉ò̜̟̦̬́̄̌̓ǹ̘̀̉̌̍̒ ̛̝̀̈̒t̀̀̀h̘̀̈̐è̇̊̋̍̐ ̙̝̥̪̮̱̀̂̋̔g̗̀̉̒r̖̀̉̑ò̅̋̎̏̓̓ù̙̈̋̑ǹ̄d̖̀̉̏̑̔ ̀̆̊̍̕ ̀́̆̍ ̛̀̂̂̆̍̏̕ ̀̉̎ ̀̈̌̍̒À̖̜̠̅̍̏ǹ̀d̀́ ̀t̢̙̀̆̎̐̓h̜̤̤̀̈̉̊̊̏̓è̢̘̣̈̋̎̓ ̀̂̄̅̇̍̎v̗̙̀́̄̋̍̓̓̔̚à̛́̅̋̎̓̚l̀̂̊l̀̀̆̎̕è̗̈̑̕ỳ̃̊̍s̀̀̅̉̑ ̀̀̂̈à̈̊̌̎̑̒r̢̢̘̤̀̂̃̃̋̑̓è̖̗̇̉̏ ̀̈̈̍̎̑c̀̃̈̏ò̄l̀̆̍d̀̅̈̉ ̀̉̒̓ ̷̡̨̙̥̬̮̰̀̄̍̒̿̓͌̕ ̛̀̉̌̒ ̀̃ ̀́̈̊̐̑À̈̊̏̏̑ǹ̂̌̎d̖̀̉̑̕ ̙̀̃̆̋̔à ̖̀̀̄̆̌̍̕m̛̖̀̃̄̇̇̍ì̀̄̅̆̋̕d̀̈̊̏̕ǹ̀́̇̉ì́̊̎̕g̘̘̀̇̍̑h̗̟̟̀̅̎t̜̞̣̀̀̃̋̍̏̒ ̛̖̀̇̍p̖̟̥̀̈̍̓̚r̛̠̀̅̍̍̕ò̢̖̜̃̄̎̎̓̓f̘̙̜̀̂̇̊̒ò̙̅̉̐̕̚ù̡̖̙́̂̈̉̋̔̔ǹ́̇d̀̂̇̇̉ ̘̘̀̄̇̑ ̨̖̖̗̣̀̄̆̊̏̑̑̚ ̀̉̒ ̀̀̅̈̋̑ ̢̗̙̀̀́̅̍̎B̀̆̋l̤̫̀̀̇̍̔̚̚à̂̃̋c̀̄̄k̜̥̪̀̄̇̋̎̓̓l̀̂̉̊̐ỳ̃ ̖̘̀̉̍̎̐s̀̆̇̊̑q̀́̂̄̄̇̍ùà̈̎̑t̀̂̅̈s̀̀̀́̃̅̅̍ ̛̀́̂̇̉̌̓̔ò̅̅̇̇'̀́̄̇è̄r̡̛̀̀̈̈̒ ̀́̉t̀̀̂̊h̀̂̆è̢̂̋̔̚ ̀̀́̄ẁ̞̦̫̰̀̇̌̍̕ò̂̃̄l̝̀̇̎̏̒̒̕̚d̘̜̜̞̥̀̃̉̐;̡̙̤̪̬̀̇̋̑ ̘̙̠̀̆̎̚ ̀̅̉̓ ̖̀̃̌ ̖̙̀́̄̅̉̒ ̀B̀̈̐̔ừ̘̆̎̏̑t̘̟̀̃̉̊̍̏ ̀̉̋à́̈̋̐ ̀̉̊̒̒̔l̀̀̇̊̍̓̚ì̃g̀̈̐h̨̖̟̮̀̂̆̋̔t̀̇̌̍ ̀̇ǫ̗̠̠̀̆̈̉̑ǹ̇̌̍ ̙̣̀̀́̉̏̒t̀̀h̗̜̀̃̊̊̌̎è̙́̈̋̍̔ ̀̂h̗̀̂̇̈̏ì̙̝̣̉̑̓̓l̗̜̀̃̃̇̑l̞̀̈̏̑̕t̙̟̀̅̍̎̕̚ò̂̄p̀̂̋̍s̀̄̇̐ ̖̀̄̋̍h̗̀̅̋̐̓à̶̢̧̝̮̈̏̕l̀̂̊f̀̀̇̇-̀̄̄̉̓s̀̂̇̍è̘̈̏è̖̟̤̥̩̰̇̏ǹ̇̋̏ ̀̇̋̐̕h̀̉̏ì́̃̈̈ǹ̅̏̓t̀̇̈s̀̄̌ ̀̃̇̊̒ò̖̖̃̋̋̏f̛̀́̅̉̑ ̀́̃̈f̀̅è́̅̉à̃̅̌̓s̛̗̣̤̀́̃̄̌̎̑t̀̆̉ì̞̤̭̃̈̑̚ǹ̗̟̦̂̂̅̆̊̊̊̏g̗̀̅̊̓̓s̀̂ ̀̄̉̑̓̔ù̅̋ǹ́̊̎̒-̀́̄̈h̀́́̊̓̔à̀̈̊l̛̀̄̌̎̔l̢̛̖̣̀̉̋̕ò̆̊ẁ̉̐̚è̆̌̍d̜̥̦̭̀̀̂̈̑̔̕ ̀̇̍̓à̈̊ǹ̗́̆̋̑̔̕ḍ̴̛̪̬̀̅̊̌̑ ̨̙̜̤̭̀̀́̈̎̏ò̈l̀̈̎̏̐d̢̝̬̀̂̃̋̌̔.̨̝̝̤̪̀̅̇̊̓ ̀̈̌̐̓̕ ̛̗̤̮̮̰̀̃̉̊̏̐̒ ̀̄̇̏ ̀̉̐ ̀́̅̇̎
> 4 votes

# Answer
## Perl, 73 bytes

```
s!\w\K!$x=-140;$x+=rand for 1..300;(x x $x) =~ s/x/chr 768+rand 48/ger!ge

```

Input is taken as newline-separated strings.

If you want to ignore the warnings printed to STDERR, use the `-C7` command-line flag.

This uses the same approximation for a normal distribution as the Moonscript solution.
> 3 votes

# Answer
# Haskell, 223 bytes

```
import System.Random
import Data.Char
a!b=round$10+sqrt(-50*log a)*cos(2*pi*b::Double)
r=randomIO
m=mapM
z s=concat.zipWith(\c r->c:[x|x<-r,isAlpha c])s<$>(m(\_->(!)<$>r<*>r)s>>=m(\x->m(\_->randomRIO('\768','\815'))[1..x]))

```

`(!)` does a Box-Muller transform on a pair of numbers, z maps each letter into random normally distributed number `x`, which is then mapped into the range `[1..x]`, in which all numbers are replaced by a uniformly random punctuation. The original characters are then appended to these lists.

Sample output:

T̢̨̮̝̘̖̗̣̟̝̞̘́̔̇̅̌̐̐̋̕ŗ̦̘̬̄y̩̦̯̞̍̂̑ ï̛̘̣̟̭̮̩̄̍̑̂̅̚t ȯ̖̤̞̎̓̔̏̕̕̚ń̢̦̖̟̠̜̯̒̀̏̑̕ļ̨̛̫̟̝̎̇̃̍̑̊̇ĩ̛̯̙̦̦̐̚n̮̪̮̞̞̈̄̔̀̚ȩ̨̜̟̬̟̫̩̦̌̂̆̋̏̄̏́!
> 2 votes

# Answer
# Perl 6, ~~68~~ ~~63~~ 59 bytes

```
{S:g/./{chrs roll max(0,-140+sum rand xx 300),768..815}$//}

```

Try it online!

> t̤̣̜̉̌̂̇̍h̢̙̦̩̉ȇ̡̡̢̛̞̠̔̑̃̊̑̓ ̗̩̜̎̒̑i̛̭̤̘̒c̛̤̮̔́̑̃̔̅̐̑̚hǫ̘̣̩̣̙̙̆̎̂̉̋̊̕r̨̦̯̋̀̊̀ ̥̙̉̓̃̇̑p̢̨̛̯̗̥̞̞̘̬̪̗̠̖̅̅̉̃́̀̐̉e̖̋r̒̐m̧̖̪̉̐ẻä̪̞ţ̯̠̦̖̍̍̋̅̊̀̕ḙ̡̡̙̐̓̌̉̌ŝ̢̧̝̃̉̀ ̡̮̘̤̙̤̘̋̃̂̋̊̐̀̏̋̐̐̒ą̛̞̥̦̘̌̊̋̂̂̒̆l̢̛̛̮̘̜̦̝̫̮̪̟̭̖̜̅̑̂̍̑̉ḷ̨̞̜̤̠̣̪̥̋̀̇̊̊̍̈ ̢̢̤̜̬̫̊̇̑̐̇̑̒̕Ḿ̢̭̫̘̟̟̤̮́̃̎Y̧̬̖̜̆̀̍̍̐̒̉̒ ̡̗̔̎̆̆̀́̎F̬̯̯̏Â̡̛̝̭̎̂̉̑C̡̦̄̑̓Ę̛̭̞̤̂̓̔̃̎̓̏ ̛̪̬̯̘́̐̚MÝ̛̝̫̥̖̓̏̑̀ ̘̤̄́̍F̬̯̠̩̞̊̃̓̔̕Ă̙̥̞̤̕C̪̓̆E̡̟̝̭̦̮̎̒̅́ ̭̈̋ḣ̢̛̫̗̩̩̣̭̋̎̐̃̄̈̉̓ ̦̘̖̃̉̔̂̆̃̍̅̕g̡̧̢̜̬̪̞̟̒̇̊́̃̋̚ǭ̫̣̩̙̆̏̏̌̑̀̕d̟̮̠̬̙̗̥̪̭̜̐̑̊̔̕̕ ̨̙̠̟̠̯̆̑̅̒̔ṋ̛̘̜̞̦̈̋̋̍̋̈ơ̡̧̗̟̟̩̙̔̏̀̈̀̇̇̆̎̕ ̨̛̦̎̀̕N̛̄̋Ò̢̡̙̦̓̑̒̂̆́ ̧̗̮̠̗̮̯̆̉̑̅N̛̤̤̒O̧̤̯̯̦̥̒̍̏̃̇̊̕Ő̜̩̙̂̀̎̕Ọ̝̗̆̉Ơ̢̦̫̭̪̐̚̚ ̨̢̞̊̉̑̍̎̆̒N̡̞̭̙̏̏̓̄̚ ̠̖̫̦̗̓̉́s̤̄̋t̨̞̫̣̭̏̔̀ở̜̘̝̉ṗ̧̬̗̥̫̤̗̣̄̋̒̎́̒ ̯́̃̕ṭ̮̖̟̥̗̤́̊̋̇̎ḩ̞̜̗̪̊̂̏e̢̞̬̟̟̠̗̎̌̐̏̔̒ ̥̠̞̉̌́̈́̈̏̍ä̡̨̩̩̯̦̐̂n̢̟̫̖̯̞̗̙̙̊̋̐̍̚\*̢̘́̒̉̎̚g̛̗̬̐̂́̇̉̆̀̚l̨̢̦̪̬̤̤̂̀̇̉̂̍̒̚ȩ̧̢̖̘̠̓̐́̈̌s̘̯̘̒̉̆̒̄̈̇̕ ̡̧̛̬̠̣̮̅ă̗̮̖̜̥̟̮̋̅̉̍̅̕r̢̢̢̤̩̙̩̋̑̓̍̆̍̕̚e̡̛̙̗̅̄̄̒́̚ ̡̖̫̞̖̖̟̣̭̅̐̄̑̊̃̉̎ǹ̗̟̤̄ö̪̏̎t̡̛̫̥̗̫̠̜̪̏̒ ̡̡̢̜̮̭̇̒̋̑̏̃̓̕r̡̗̬̯̪̝̮̂̊̒̏̔̉̀̚e̢̧̗̯̞̭̘̝̐̓̈̔̊̋̉å̖̣̔̋l̡̛̛̬̮̟̝̪̯̆̊ ̡̪̩̐̒Z̡̦̗̝̞̜̠̊̇̓̆AḶ̒̇̇̅̓̈̃̂Ğ̮̯̭̮̘̞̙̣̐̐̉̇Ő̡̠̞̄ ̢̟̖̪̋́́̔̚̚Į̪̗̭̖̊Ș̢̬̤̜̥̟̌̅ ̨̢̜̥̪̠̦̦̦̘̟̯̯̋̒̓̍̈̇̕T̢̉̆̌̊̎̈̕Ȍ̧̢̫̬̄̉̀̇̍̍̌̚̕Ņ̥̩̝̟̀̈̀̇̆̏̕y̛̟̫̠̭̫̗̫̮̬̥̥̭̗̓̏̑̋̍̇̐̔̋̐̅ ̝̥̘̫̪̖̫̅̂̌́̎̀̚̚̕Ṭ̌H̦̫̖̟̥̣̔̚̕Ę̢̬̮̩̣̙̇̅ ̨̧̝̭̩̟̈̂̈̃̓̓̚P̩̞̭̠̝̗̂̓̒̋̄Ợ̙̬̜̮̄̑̊̏̒N̘̤̆̏̇Y̨̫̪̜̖̯̒̎̋̌̍̈̄̊ ̧̣̠̣̜̌̄̇̋̄̊̉̏H̛̠̮̣̝̩̖̋̑̍E ̡̢̙̘̥̬̗̯̄̌̔̂̀̆̇̔̑C̪̣̮̋̇̎O̧̨̩̖̠̓̓̉̚̚̕M̛̛̙̘̟̪̙̘̩̝̖̉́̀̂̏̇Ẻ̡̛̛̘̯̜̆̀̓̓̒S

Uses the, ahem, 'binomial approximation' to the normal...

Text from that bobince answer.
> 2 votes

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


# Question
Title: Find the Number With the Highest Sum of Neighbors
# The Challenge

Given a grid of numbers (10 \<= N \<= 99) Return number with the highest sum of the four numbers adjacent to it; that is the numbers above, below, right, and left of the number, but not itself.

1. The number itself does not count, only its four neighbors.
2. A number on the edge *should* be treated as though the missing number is a 0.
3. I will design the test to avoid ties.
4. Numbers will not repeat.
5. This is .

# Example

Given

```
56 98 32 96
12 64 45 31
94 18 83 71

```

Return

```
18

```

# A Real Test

Given

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

```

Return

```
13

```

Given

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

```

Return

```
15

```

# Answer
> 9 votes
# MATL, ~~20~~ ~~15~~ ~~13~~ 12 bytes

```
t1Y6Z+tuX>=)

```

Saved 5 bytes thanks to Emigna, 2 thanks to Giuseppe, and another thanks to Luis Mendo.
Try it online!

### Explanation

```
t1Y6Z+tuX>=)
t                  Duplicate the (implicit) input.
 1Y6               Push the array [0 1 0; 1 0 1; 0 1 0].
    Z+             Convolve with the input.
       uX>         Get the maximum unique element...
      t   =        ... and compare elementwise.
           )       Index into the input.

```

# Answer
> 6 votes
# APL (Dyalog Unicode), ~~31~~ ~~27~~ ~~26~~ ~~24~~ 23 bytesSBCS

-2 thanks to Cows quack. -1 thanks to ngn.

Anonymous tacit prefix function. Takes a matrix as argument. Assumes `⎕IO` (**I**ndex **O**rigin) to be `0`, which is default on many systems.

```
{⊃⍒,(+/--/)⊢∘,⌺3 3⊢⍵}⊃,

```

Try it online!

`,` ravel (flatten) the input

`{``}⊃` pick an element from that according to the result of the following function:

`⊢⍵` yield the argument (separates `3 3` from )

…`⌺3 3` apply the following function to each 3-by-3 neighbourhood:

`⊢∘,` ignore the edge-information in favour of the ravelled (flattened) neighbourhood

`(``)` apply the following tacit function to those

`-/` the alternating sum (lit. right-associative minus reduction)

`+/-` subtract that from the sum (this gives the sum of every other element)

`,` ravel (flatten) that (the neighbourhood sums)

produce the indices which would sort that

pick the first (i.e. the index of the highest sum)

# Answer
> 5 votes
# Jelly, 22 bytes

```
;€0ZṙØ+SṖ
,ZÇ€Z+$/ŒMœị

```

Try it online!

~~Not having convolution built-ins like MATL and Dyalog~~ *Forgetting your language has convolution built-ins* (thank you @dylnan) hurts, but we can do sort of okay without them, partially thanks to `ŒM` and `œị`. First, a helper function to compute neighbors in just one direction, which incidentally transposes the input:

```
;€0Z         Append a zero to each row, then transpose.
    ṙØ+S     Rotate by +1 and −1 (Ø+ = [1,-1]) and sum these.
        Ṗ    Pop the last row.

```

Visually, the computation is:

```
1 2 3   ;€0   1 2 3 0   Z   1 4 7   ṙØ+     2 5 8   0 0 0     S   2  5  8   Ṗ   2  5  8
4 5 6  ————→  4 5 6 0  ——→  2 5 8  ————→  [ 3 6 9 , 1 4 7 ]  ——→  4 10 16  ——→  4 10 16
7 8 9         7 8 9 0       3 6 9           0 0 0   2 5 8         2  5  8       2  5  8
                            0 0 0           1 4 7   3 6 9         4 10 16

```

Interpretation: cell (x, y) of this result is the sum of cell (y, x)'s horizontal neighbors. (For example, here we see that **f(A)\[2,3\] = 16 = 7 + 9 = A\[3,1\] + A\[3,3\]**.)

Then, the main function:

```
,ZÇ€            Pair the input with its transpose and apply helper to both.
    Z+$/        Fold by Z+, i.e., turn [X,Y] into transpose(X)+Y.
                Now we've summed the horizontal and vertical neighbors for each cell.
        ŒM      Find the 2D index of the maximal value.
          œị    2D-index (into the original input).

```

# Answer
> 5 votes
# Jelly, 18 bytes

```
5BæcµḊṖ)
ZÇZ+ÇŒMœị

```

Try it online!

The helper function finds the neighbors of each element in each row. The main function does this to the rows and the columns then finds the element that has the maximum neighborhood sum.

```
5BæcµḊṖ)
5B           bin(5): 1,0,1
  æc         Convolve with [[1,2,9],[other rows]] (for example): [[1,2,10,2,9],...]
    µ        New chain.
       )     Apply this to each element:
     Ḋ       Remove the first element.
      Ṗ      Remove the last element.
             Gives [[2,10,2],...]

ZÇZ+ÇŒMœị
Z            Zip the matrix
 Ç           Apply helper function
  Z          Zip again. Yields the sum of the vertical neighbors of each element.
   +         Add:
    Ç        The sum of each element's horizontal neighbors.
     ŒM      Find the multidimensional index of the maximal element.
       œị    Index back into the original matrix.

```

# Answer
> 3 votes
# Wolfram Language (Mathematica), 58 bytes

```
Im@Last[Union@@ListConvolve[{a={0,1,0},{1,I,1},a},#,2,0]]&

```

Convolve the matrix with \\$ \left( \begin{smallmatrix} 0 & 1 & 0 \\ 1 & i & 1 \\ 0 & 1 & 0 \end{smallmatrix} \right) \\$, take the element with the largest real part, and take its imaginary part.

Try it online!

# Answer
> 2 votes
# Python 2, 127 bytes

```
def f(a):n=len(a[0]);b=sum(a,[])+[0]*n;print b[max(range(len(b)-n),key=lambda i:b[i-1]*(i%n>0)+b[i+1]*(i%n<n-1)+b[i-n]+b[i+n])]

```

Try it online!

# Answer
> 2 votes
# Stencil, 1 + 10 = 11 bytes

Command-line option: `1` compute 1 generation

```
y⊃⍨⊃⍒,
+/N

```

Try it online!

`y` from the flattened original input
`⊃⍨` pick
the first
in descending order
`,` of the flattened

`+/` sums of
`N` the von neumanN neighbourhoods without selves

# Answer
> 2 votes
# JavaScript (ES6), 94 bytes

```
a=>a.map(p=m=(r,y)=>p=r.map((v,x)=>(s=~r[x-1]+~p[x]+~(a[y+1]||0)[x]+~r[x+1])>m?v:(m=s,o=v)))|o

```

Try it online!

### How?

Instead of looking for the maximum of the sum of the 4 neighbors, we look for the minimum **m** of the sum **s** of their one-complements. This allows us to process undefined values just like zeros, because:

```
~undefined === -1
~0 === -1

```

The inner **map()** is written in such a way that it does not alter the content of the row **r**. Therefore, we can save its result in **p** in order to test top neighbors in the next iteration.

We use:

* `~r[x-1]` for the left cell
* `~r[x+1]` for the right cell
* `~p[x]` for the top cell
* `~(a[y+1]||0)[x]` for the bottom cell

# Answer
> 1 votes
# K (ngn/k), ~~43~~ 40 bytes

```
{(,/x)@*>,/(+g@+x)+(g:{(+':x)-|-':|x})x}

```

Try it online!

# Answer
> 1 votes
## Javascript ES6, 170 bytes

```
c=g=>{s=0;n=0;f=m=>m||[];for(i=0;i<g.length;i++)for(j=0;j<g[i].length;j++){s=~~f(g[i-1])[j]+~~f(g[i+1])[j]+~~f(g[i])[j-1]+~~f(g[i])[j+1];b=s>n?g[i][j]+!(n=s):b;}return b}

```

# Answer
> 1 votes
# Java 8, 187 bytes

```
m->{int r=0,l=m.length,i=l,L,j,S=0,s;for(;i-->0;)for(L=j=m[i].length;j-->0;)if((s=(i<1?0:m[i-1][j])+(i<l-1?m[i+1][j]:0)+(j<1?0:m[i][j-1])+(j<L-1?m[i][j+1]:0))>S){S=s;r=m[i][j];}return r;}

```

Try it online.

**Explanation:**

```
m->{                           // Method with integer-matrix parameter and integer return
  int r=0,                     //  Result-integer, starting at 0
      l=m.length,              //  Amount of rows
      i=l,                     //  Rows index integer
      L,                       //  Amount of columns
      j,                       //  Column index integer
      S=0,                     //  Largest sum of four cells
      s;                       //  Current sum of four cells
  for(;i-->0;)                 //  Loop over the rows
    for(L=j=m[i].length;j-->0;)//   Inner loop over the columns
      if((s=                   //    Set the current sum to: the sum of:
           (i<1?0:m[i-1][j])   //     Value of the cell to the left, or 0 if out of bounds
          +(i<l-1?m[i+1][j]:0) //     Value of the cell to the right, or 0 if out of bounds
          +(j<1?0:m[i][j-1])   //     Value of the cell down, or 0 if out of bounds
          +(j<L-1?m[i][j+1]:0))//     Value of the cell up, or 0 if out of bounds
         >S){                  //    If this current sum is larger than the largest sum:
        S=s;                   //     Replace the largest sum with this current sum
        r=m[i][j];}            //     And set the result to the current cell
  return r;}                   //  Return the result

```

---
Tags: code-golf, number, matrix
---


title: Animate Jacob's ASCII Ladder

text:
# Question
Title: Animate Jacob's ASCII Ladder
You may have seen Jacob's Ladder in children's science museums. If you're not familiar with what they look like, there are several images and video examples on the Wikimedia Commons. The challenge today is to create an animated ASCII version of the electrical gadget. In the end, it should look something like this:

---

**Ladder Construction**

Here is the basic shape of a ladder with a height (***H***) of 6:

```
6   \            /
5    \          /
4     \        /
3      \      /
2       \    /
1        \  /
0         ¯¯

```

The numbers on the left simply indicate row number for this example and should not be included in the output. We'll refer to a given row by it's number (***R***). Row 0 is the bottom `¯¯`. Each row 1 through ***H*** is comprised of four parts:

* A space  (U+0020) repeated (***H*** \- ***R***) times
* A back slash `\` (U+005C)
* A space  (U+0020) repeated (2 * ***R***) times
* A forward slash `/` (U+002F)

Row 0 is identical except both the slashes are replaced with a macron `¯` (U+00AF). Trailing whitespace at the end of each line or below the ladder is OK. Leading whitespace is not.

---

**Arc Construction**

Once the ladder is constructed, you can create arcs between the left and right side. One arc is entirely within a row and replaces the spaces between the leading `\` and trailing `/`. Therefore, row 2 will have 4 characters in its arc, row 3 will have 6, and so forth. Each arc is composed using the following rules:

* The only allowable characters are `_/¯\` (U+005F, U+002F, U+00AF, U+005C)
* In order to ensure a smooth appearance, any `¯` or `/` must be followed by a `¯` or `\`
* In order to ensure a smooth appearance, any `_` or `\` must be followed by a `_` or `/`
* The two rules above apply to the edges of the ladder as well
* The three rules above effectively mean that the first character in the arc must be `_` or `/` and the last character must be `_` or `\` (`\¯\_//` is invalid on both ends but `\_/¯\/` is OK)
* There must be a non-zero chance for each allowable character to occur at a given point
* Each arc is independent from every other arc

---

**Animation**

The life of a single arc is created by starting it at row 1 and "moving" it up one row at a time until it reaches the top. I.E., first generate an arc at row 1, then set it back to spaces and generate an arc at row 2, and so forth. Given a number of arcs to show (***N***), show the complete life of that many arcs one at a time using the following guidelines:

* Only one arc should be "alive" at any one time. The next arc cannot start until the current one reaches the top and then extinguishes.
* Each row of the arc's life should be shown for exactly one frame
* There should one frame of just the basic ladder (with no arcs) before a new arc starts (optional before the first arc)
* The animation should show the full life of ***N*** arcs. If ***N***=0, it should animate random arcs forever until stopped.
* If ***N***\>0, you may still loop the animation forever but it must be a loop of the same arcs over and over. (The example GIF at the top of this post has ***H***=6 and ***N***=3 but it loops forever.)
* The animation should occur in-place. That is, each frame should completely overwrite the next frame and be in the same location.
* The length of each frame can be whatever you want but make it watchable by a human (I.E., use your common sense: 0.01s/frame and 30s/frame are both unacceptable.)

---

**Input / Output**

* Input and Output can be in any standard format
* You can export a GIF, write text to the screen, output a single file for each frame, or any other reasonable means
* Standard loopholes are forbidden
* The height of the ladder ***H*** will be a positive integer
* The number of arcs to show ***N*** will be a non-negative integer
* Both ***H*** and ***N*** are taken as inputs in any order you choose (Please include the order in your answer)

---

**Winning Condition**

This is so the shortest code wins.

Sandbox

# Answer
## JavaScript (ES6), 245 bytes

```
f=(o,h,n,i=0)=>(o.innerText=[...Array(h+1)].map((_,j)=>` `.repeat(j)+(j<h?`\\${[...Array(w--*2)].map((_,k)=>h+~j-i?` `:k>w*2|Math.random()<.5?s[s=t,1]:s[s=`¯\\`,0],s=t=`/_`).join``}/`:`¯¯`),w=h).join`
`,(++i<h||--n)&&setTimeout(f,250,o,h,n,i%h))
```

```
Height: <input type=number min=1 value=6 id=h><br>Arcs: <input type=number min=0 value=3 id=n><br><input type=button value=Go! onclick=f(o,+h.value,+n.value)><pre id=o></pre>
```

Byte count assumes ISO-8859-1 encoding.
> 4 votes

# Answer
# Python 2, ~~287~~ ~~271~~ ~~270~~ ~~276~~ 275 bytes

```
import time,random
r,n=input()
c=n*-~r or-r
while c:
 c-=1;L=[list(' '*i+'\\'+'  '*(r-i)+'/')for i in range(r)];x=c%-~r;time.sleep(1);y=x+1;exec"L[x][y]=random.choice('\xaf/\_'[L[x][y-1]in'\_'::2][y==2*r-x:]);y+=1;"*2*(r-x)
 for l in['']*99+L+[' '*r+'\xaf'*2]:print''.join(l)

```

Try it online!

Does not clear the screen on tio, but works in a console.

Gif of it running:
> 5 votes

# Answer
# C (gcc), 406 bytes

```
#define p(X) printf(X),usleep(999)
#define x(X) do{s[X]=0;p(s);s[X]=' ';}while(0)
char c[2][2]={95,47,92,'¯'};R;i;j;k;a(){char s[2]={92,0};for(j=0;j<2*R-1;++j,p(s))*s=c[*s<50][rand()%2];*s=c[*s<50][0];p(s);}f(H,N){char s[99];for(i=0;i<99;++i)s[i]=' ';p("\e[s");for(i=0;;++i){i%=(N?N:i+1);srand(i^H^N);for(k=1;k<H;++k){for(R=H;--R;){x(H-R+1);p("\\");if(R==k)a();else x(2*R);p("/\n");}x(H);p(" ¯¯\n\e[u");}}}

```

Try it online!

Description:

```
#define p(X) printf(X),usleep(999)              // Define p to printf(p) + delay
#define x(X) do{s[X]=0;p(s);s[X]=' ';}while(0)  // Define x(X) to print X spaces
                                                // This uses a string s full of
                                                // spaces and adds the null
                                                // terminator where approrpiate
char c[2][2]={95,47,92,'¯'};                    // 2d array of 'next arc' options
R;i;j;k;                                        // Variables
a(){                                            // a() -> print arc for row R
    char s[2]={92,0};                           // s is a string of next char
                                                // initialize to backslash
    for(j=0;j<2*R-1;++j                         // loop over each character
            ,p(s))                              // printing s each time
        *s=c[*s<50][rand()%2];                  // set s to the next arc char
    *s=c[*s<50][0];                             // set s to the 'first' arc char
                                                // note that in definition of c
                                                // first means appropriate as
                                                // final character before /
    p(s);}                                      // print the last character
f(H,N){                                         // f(H,N) -> print jacob ladder
    char s[99];for(i=0;i<99;++i)s[i]=' ';       // this is the space string for x
    p("\e[s");                                  // ANSI terminal save position
    for(i=0;;++i){i%=(N?N:i+1);                 // loop i->N (or i->INT_MAX if N=0)
        srand(i^H^N);                           // seed random with i XOR H XOR N
        for(k=1;k<H;++k){                       // for each row (bottom to top)
            for(R=H;--R;){                      // for each row (top to bottom)
                x(H-R+1);p("\\");               // print left "    \"
                if(R==k)                        // if on the arc row
                    a();                        // print the arc
                else x(2*R);                    // otherwise print spaces
                p("/\n");}                      // finish off the row
            x(H);p(" ¯¯\n\e[u");}}}             // print bottom line and move back

```
> 4 votes

# Answer
# PowerShell, ~~347~~ 319 bytes

```
filter c{Param($h,$n)if($n-eq0){$n=-1}for($x=0;$x++-ne$n;){($h..1)|%{$l=(($h..1)|%{"$(" "*($h-$_))\$(" "*$_*2)/"})+"$(" "*$h)¯¯"
$r="Get-Random"
$i=0
$z=-join((0..(($h-$_)*2))|%{$i=switch($i%3){0{&$r 0,1}default{&$r 2,3}}"_/¯\"[$i]})+"_\\_"[$i]
$l[$_-1]=($l[$_-1]).Substring(0,$_)+"$z/"
cls
$l
Sleep -m 250}}}

```

Try it online! Couldn't get `$args` to play nice, so the link calls the function without clearing the console.

## Ungolfed

```
filter c{
    Param($h,$n)
    if($n -eq 0){$n=-1} # inelegant swap to allow for an infinite loop.
                        # Curse you zero-indexing!
    for($x=0;$x++-ne$n;)
    {
        ($h..1) | % {
            $l=(($h..1)|%{ # (( double paren is needed to induce each line
                           # as a new array element
                "$(" "*($h-$_))\$(" "*$_*2)/" # offset by total height.
                                              # N spaces + rung + N*2 spaces + rung
            })+"$(" "*$h)¯¯" # last line is the floor of the ladder

            $r="Get-Random" # shorter to declare once and execute with & operator

            $i=0 # initialize $i so we choose only _ or / for the first char

            $z=-join( # build an electric ZAP!
                (0..(($h-$_)*2))|%{
                    $i = switch($i%3) { # choose next char based on previous selection
                        0{&$r 0,1}
                        default{&$r 2,3}
                    }
                    "_/¯\"[$i]
                }
            )+"_\\_"[$i] # final char is \ or _ to rejoin the ladder
            $l[$_-1]=($l[$_-1]).Substring(0,$_)+"$z/" # select one rung of the ladder
                                                      # append an electric ZAP!
            cls # clear the console
            $l  # display the ladder
            Sleep -m 250
        }
    }
}

```
> 2 votes

# Answer
# Ruby, 293 bytes

```
m={}
"   __/\\_/¯¯\\/¯\\".chars.each_slice(3){|e|u,*v=e;m[u]=v}
a=->l,c{l<1?"/":(d=m[c].sample;c+a[l-1,d])}
n=gets.to_i
h=gets.to_i
o=0
while o<n||n<1
h.times{|i|puts (0...h).map{|j|" "*j+"\\"+a[2*(h-j),i==h-j-1?["_","/"].sample: " "]}*"\n";puts" "*h+"¯¯";sleep(0.3);puts"\n"*99}
o+=1
end

```

Try it online!

I'm on windows so it just prints many "\n" to clear the console. Takes 2 arguments `n` and `h` as two lines on stdin.
> 2 votes

---
Tags: code-golf, ascii-art, animation
---


title: Minimum perimeter of an area

text:
# Question
Title: Minimum perimeter of an area
Just a simple code golf function for fun, intentionally left open with few rules to see what creativity comes up.

**Input:** An integer representing the area of a rectangle.

**Output:** Two integers representing the side lengths of the rectangle that have the least perimeter for the area. (In any order.)

**Test cases:**

```
25 => 5, 5
53 => 53, 1
4294967295 => 65537, 65535

```

# Answer
> 6 votes
## GolfScript (21 chars)

```
:^,{)^\%!},.,2/=)^1$/

```

This takes the input as a number on the stack and leaves the result as two numbers on the stack.

For fair comparison with Howard's solution, taking input on stdin and giving output on stdout separated by newline is **23 chars**:

```
~:^,{)^\%!},.,2/=)n^2$/

```

It works because this problem is trivial: it's just looking for the pair of factors closest to `sqrt(area)`.

Online demo for a square; online demo for a non-square.

# Answer
> 13 votes
# Mathematica ~~34~~ 26

Besides the explicit search there is a nice convergent series:

```
n = 27

{i=√n//.i_:>n/⌈n/⌊i⌋⌉,n/i}

```

> {3, 9}

Three previous approaches with 34 characters:

```
{#,n/#}&@FixedPoint[n/⌈n/⌊#⌋⌉&,√n]

For[i=√n,i>(i=n/⌈n/⌊i⌋⌉),];{i,n/i}

f@i_:=f[f@i=n/⌈n/⌊i⌋⌉]
{i=f@√n,n/i}

ClearAll[f]

```

Visualization:

```
p = FixedPointList[n/⌈n/⌊#⌋⌉ &, Sqrt[n]];

Plot[n/x, {x, 0, 11}, GridLines -> {Range@n, Range@n},
 AspectRatio -> Automatic, PlotRange -> {{0, 10.2}, {0, 7.2}},
 Epilog -> {Red, Thickness[0.005],
   Arrow[Transpose[{{n/p, ⌈p⌉}, {n/p, ⌊p⌋}, {⌈n/⌊p⌋⌉, ⌊p⌋}}, {2, 3, 1}]],
  PointSize[0.02], Black, Point[{n/p[[-1]], p[[-1]]}]}]

```

# Answer
> 3 votes
# Python 2 (~~63~~ 62)

```
n=input()
print[(i,n/i)for i in range(1,n)if i*i>=n/i*i==n][0]

```

This produces all pairs of integers (i, n/i) that could be the sides of the rectangle, starting from the first one greater or equal to the square root of n. It prints the first one.

# Answer
> 2 votes
**Golfscript (~~46~~ ~~43~~ 40)**

```
~1{..*2$>!}{1$1$%!{.@@}*)}while;1$/p p];

```

No way to beat the math oriented languages at this challenge I suspect :)

Somewhat "long winded", it would be shorter to work with arrays, sadly they get a bit large with the last test case.

Basically what it does is similar to the Python solution, it loops from 1..sqrt(n), testing for an even multiplier, then just displaying the last value found.

# Answer
> 2 votes
### GolfScript, 30 characters

```
~:t,{[.t\/].~*t=1$~>!&\@if}*n*

```

Does a test on all numbers as many other solutions.

# Answer
> 1 votes
**C# (178)**

```
int[] R(int n){var a=Enumerable.Range(1,n);var b=a.SelectMany(x=>a.SelectMany(y=>a.Select(_=>new{x,y}))).Where(f=>f.x*f.y== n).OrderBy(f=>f.x+f.y).First();return new[]{b.x,b.y};}

```

Pretty

```
int[] R(int n)
{
    var a = Enumerable.Range(1, n);
    var b = a.SelectMany(x => a.SelectMany(y => a.Select(_ => new { x, y }))).Where(f => f.x * f.y == n).OrderBy(f => f.x + f.y).First();
    return new[] { b.x, b.y };
}

```

# Answer
> 1 votes
## Java 8, ~~73~~ 72 bytes

Saved one byte due to @ThomasKwa!

```
n->{for(int i=(int)Math.sqrt(n);;i--)if(n%i<1)return new int[]{n/i,i};};

```

Lambda function, test with:

```
public class Rectangle {
    interface Test {
        int[] run(int v);
    }
    public static void main (String[] args){
        Test test = n->{for(int i=(int)Math.sqrt(n);;i--)if(n%i<1)return new int[]{n/i,i};};

        int[] testCases = {1, 4, 8, 15, 47, 5040, 40320, 25, 53};
        for (int i : testCases) {
            int[] result = test.run(i);
            System.out.println(i + ": " + result[0] + ", " + result[1]);
        }
    }
}

```

Finds the greatest divisor less than or equal to the square root of the area. Returns an `int[]`.

# Answer
> 1 votes
# C, 54 bytes

```
f(x,y){for(y=sqrt(x);x%y;y--);printf("%d, %d",y,x/y);}

```

Just some general silliness.

Test if you like:

```
int main() {
    printf("Enter a number\n");
    int a;
    scanf("%d", &a);
    f(a);
    printf("\n");
    return 0;
}

```

# Answer
> 0 votes
## C# 4.0: 79 characters

```
long[] P(long a){long r=0,s=0;while(++s<a/s)if(a%s==0)r=s;return new[]{r,a/r};}

```

If it weren't for the last test case, I could save 3 characters naming `long` to `int`.

In pretty format:

```
long[] Perimeter(long area)
{
    long result = 0;
    long side = 0;
    while (++side < area / side)
    {
        if (area % side == 0)
            result = side;
    }
    return new long[] { result, area / result };
}

```

# Answer
> 0 votes
## C, 71 bytes

Nothing fancy, find the pair of integers `(a, b)` closest to `sqrt(n)` such that `a*b==n`:

```
f;x;L(n,a,b)int*a,*b;{for(f=0,x=sqrt(n);x;--x)n%x||f++?:(*a=x,*b=n/x);}

```

If the function is allowed to work only on first invocation, then we can shrink it to 67 bytes:

```
f;x;L(n,a,b)int*a,*b;{for(x=sqrt(n);x;--x)n%x||f++?:(*a=x,*b=n/x);}

```

Test main:

```
#include <stdio.h>

int main() {
  int testdata[] = {1, 4, 8, 15, 47, 5040, 40320};
  int x,y;
  for (int i = 0; i < 7; ++i) {
     L(testdata[i], &x, &y);
     printf("%5d >  %dx%d\n", testdata[i], x, y);
  }
}

```

The code was originally written for another golf, which is a duplicate of this.

# Answer
> 0 votes
# Jelly, 8 bytes

```
÷Ɱ½ĖḞƑƇṪ

```

Try it online!

Use a bunch of new quicks. (`ƇⱮƑ`)

---

# Jelly, 9 bytes

```
ọⱮ½TṪð,÷@

```

Try it online!

A port of my other answer.

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


# Question
Title: Zigzag this string by collapsing duplicates
Given a string, your task is to collapse it into a zigzag-like structure as described below.

## Folding into a Zigzag

We'll take the string `"Mississippi"` as an example:

1. First, output the longest prefix consisting of unique characters only:

```
Mis

```
2. When you reach the first duplicate character **C**, ignore it, and output the longest prefix consisting of unique characters of the remaining string (`issippi`) vertically, below the first occurrence of **C**:

```
Mis
  i
  s

```
3. Repeat the process, alternating between horizontal and vertical continuation. But now be careful (at step 1) to continue outputting horizontally from latest occurrence of the duplicate character, which is not necessarily the last one, as in this case:

```
Mis
  i
  sip
-----
Mis
  i
  sip
    i

```

## Rules

* The string will only contain printable ASCII characters, but won't contain any kind of whitespace.
* You can compete in any programming language and can take input and provide output through any standard method and in any reasonable format1, while taking note that these loopholes are forbidden by default. This is , so the shortest submission (in bytes) for *every language* wins.
* 1 Input: String / List of characters / whatever else your language uses to represent strings. Output: Multiline string, list of strings representing lines or list of lists of characters/length-1 strings, but please include a pretty-print version of your code in your answer, if possible.
* Regarding additional spaces, the output may contain:
    + Leading / trailing newlines
    + Trailing spaces on each line / at the end
    + A *consistent* number of leading spaces on each line
* You must begin to output horizontally, you may **not** start vertically.

## Test cases

Inputs:

```
"Perfect"
"Mississippi"
"Oddities"
"Trivialities"
"Cthulhu"
"PPCG"
"pOpOpOpOpOpOp"
"ABCCCE"
"ABCCCECCEEEEC"
"abcdcebffg"
"abca"
"AAAAAAAA"

```

Corresponding outputs:

```
Perf
 c
 t

```

```
Mis
  i
  sip
    i

```

```
Od
 ies
 t

```

```
Triv
  a
  l
  ies
  t

```

```
Cthul
  u

```

```
P
C
G

```

```
pO
OpO
pOp
 p

```

```
ABC
  C
  E

```

```
ABC
  CCE
  E EC

```

```
abcd
  e
  b
  fg

```

```
abc

```

```
A
AA
 A

```

# Answer
> 2 votes
# Wolfram Language (Mathematica), 143 bytes

```
{#}//.{q___,a_,r___,a_,Longest@s___}:>{q}~f@{a,r}~{{s}}//.{q_~f@a_~s_}/;s~FreeQ~f:>(PadLeft@{q~Join~#,##2}&)@@PadRight@Join[{a},s]/. 0->" "&

```

Try it online!

Contains `0xF8FF`, which corresponds to the `\[Transpose]` operator.

Phew, it was tough making the result into a string. Getting each branch isn't so tough: `#//.{q___,a_,r___,a_,Longest@s___}:>{q,a,{r},{s}}&`

# Answer
> 2 votes
# Python 2, 131 bytes

```
X=Y=y=0
s=input()
o=()
l={}
for i in s:o+=[' ']*len(s),;exec('l[i]=X,Y','y^=1;X,Y=l[i];l={}')[i in l];o[Y][X]=i;X+=y<1;Y+=y
print o

```

Try it online!

-1 thanks to Lynn.

Prints as a tuple of lists of length-1 strings. Pretty-printed output.

# Answer
> 1 votes
# Python 2, ~~184~~ ~~176~~ ~~175~~ 168 bytes

-5 bytes thanks to Mr. Xcoder

```
def f(x):i,k=[p for p in enumerate(map(x.find,x+"z"))if cmp(*p)][0];return[x[:i]+' '*len(x)]+[' '*k+''.join(d)+i*' 'for d in zip(*f(x[i+1:]))]if x[len(set(x)):]else[x,]

```

Try it online!

# Answer
> 0 votes
# CJam, 81 bytes

```
{_,_S*a*a\+{__L#){V!:V;L#)LM:L;=~:U;:T}{[TU]a+L+:L}?;U@_U=T4$tt\;TV!+:T;UV+:U;}*}

```

Try it online!

---
Tags: code-golf, string, ascii-art
---


title: Travel Back in Quine

text:
# Question
Title: Travel Back in Quine
The challenge here is simple, and not at all about byte-count. Your job is to output the first 50 characters of the previous quine's source code, concatenated with the first 50 characters of yours starting with the 50 characters I've placed below:

```
abcdefghijklmnopqrstuvwxyzACDEFGHIJKLMNOPQRSTUVWXY

```

So, lets take an example here, if you were to answer in 05AB1E, a solution to simply output the first 50 bytes would be:

```
ži50£

```

Which would mean you'd need to output:

```
abcdefghijklmnopqrstuvwxyzACDEFGHIJKLMNOPQRSTUVWXYži50£

```

If your program is shorter, simply use the first `x < 50` characters. If your program is longer only concatenate the first 50 characters, ending on the 50th character. The next person will then have to output the first 50 characters of your quine concatenated with their own code.

***Your code can be any size, but you should only output the first 50 characters of your code concatenated to the end of the first 50-bytes of the previous answer's code.***

---

# Restrictions:

This uses the definition of a proper quine, and, in addition to this, the following things:

* Comments are disallowed, entirely.
* ***PAY ATTENTION TO THIS SECTION, IT MAY EVOLVE IF ABUSIVE LOOPHOLES ARISE***

---

# How to Post a Chained-Answer:

1. Post a placeholder:
    * Mention your answer number and the language you'll use.
2. Sort-by-date, if you notice someone else posted a placeholder 1 millisecond before you:
    * Delete yours, wait for the next opportunity, sorry.
3. If you've secured the next spot, ***PLEASE ANSWER WITHIN 6 HOURS***:
    * If you can't answer, remove your reserved space.
4. IF the space has been hogged for more than 6 hours.
    * Vote to delete reserved space, I'll handle it.

---

# Your Post Format:

```
#[Answer #]:[Character Count] Characters, [Language Used]

{TIO MARKDOWN}

{LINE_SEPARATOR="---"}

{ADDITIONAL EXPLANATION OR INFORMATION}

```

---

# Some specific notes (Important for Ease-of-Competition):

* If the person before you has included newlines or non-ASCII characters in their source, you may STRIP them. This means that `x="a\nb"` becomes `ab`, where `x[0]=a;x[1]=b;`.
    + You must state the mutation you've applied to the previous source.
* All characters are counted as a single character, despite code-pages or language encoding. Please do not use byte-count, use character-count.

---

The accepted answer will be the `50th` answer, just because; I mean, it's SE afterall.

# Answer
# 1: 96 Characters, Haskell

```
abcdefghijklmnopqrstuvwxyzACDEFGHIJKLMNOPQRSTUVWXY:z=['`'..'z']++'A':['C'..'Y']
main=putStr$z++z

```

Try it online!

---

I was feeling silly, and saw nothing forbidding the first entry starting with the exact *same* 50 characters as the initial string.

* `['`'..'z']++'A':['C'..'Y']` is an expression evaluating to the string of those characters, with a ``` prepended.
* The result is pattern matched on, making the variable `abcdefghijklmnopqrstuvwxyzACDEFGHIJKLMNOPQRSTUVWXY` equal to `'`'`, and `z` equal to the 50 characters.
* `main=putStr$z+z` then does the actual output.
> 7 votes

# Answer
# 2:119 Characters, Javascript

```
alert(eval(c="'abcdefghijklmnopqrstuvwxyzACDEFGHIJKLMNOPQRSTUVWXY'+`alert(eval(c=${JSON.stringify(c).substr(0,37)}`"))

```

Try It Online(uses `console.log` instead of `alert` to output)

Based on this JS quine.

## Old version(reads source code):

```
f=_=>`abcdefghijklmnopqrstuvwxyzACDEFGHIJKLMNOPQRSTUVWXYf=${(f+"").substr(0,48)}`;alert(f())

```

Based on this JS quine
> 5 votes

# Answer
# 5:76 characters, Emojicode

```
as=:'"alert(eval(c="''abcdefghijklmnopqrstuvwxyzACDaa❌a 0 45

```

Try it online!

---

Explanation:

```
		 start
   a ...	 define variable a as that string
      	 print:
    		 combine those strings:
      a		 a, and:
      a❌	 string literal. the ❌ works like \"
      a 0 45	 between indexes 0 and 45 of a

		 end
```
> 5 votes

# Answer
# 8: 70 characters, Stax

```
"v->{String t=`"⛽as=:'\`"alert(eval(c=\`"''abcdefghijk"c'".`"R34|S50(+

```

Run and debug online

## Explanation

```
"..."c'".`"R34|S50(+
"..."                   The string from last output
     c'".`"R            Escape all double quotes
            34|S        Surround with double quotes
                50(     Take the first 50 characters
                   +    Append to the string from last output
                        Implicit output

```
> 3 votes

# Answer
# 3:56 Characters, SOGL

```
"alert(eval(c="'abcdefghijklmnopqrstuvwxyzACDEFGHIJ”1#Οj

```

---

Try it Here!

Explanation:

```
"...”      push the first 50 bytes of the previous answer
     1#Ο   wrap a quote around with that
        j  take the last letter off, as my answer has one more byte for the starting quote.

```

The Javascript answer had a quote in it, so I had to add a starting quote, but as this isn't code-golf, it doesn't matter.
> 2 votes

# Answer
# 4:81 characters,

```
s=:'"alert(eval(c="''abcdefghijklmnopqrstuvwxyzACDEFGHI'
echo s,50{.'s=:',quote s

```

Try it online!

---
> 2 votes

# Answer
# 7: 137 characters, Java 8

```
v->{String t="⛽as=:'\"alert(eval(c=\"''abcdefghijklmnopqrstuvwxyzA";return t+("v->{String t=\""+t.replace("\"","\\\"")).substring(0,50);}

```

Try it online.

**Explanation:**

```
v->{        // Method with empty unused parameter and String return-type
  String t="⛽as=:'\"alert(eval(c=\"''abcdefghijklmnopqrstuvwxyzA";
            //  String containing the first 50 characters of the previous answer
  return t  //  Return those first 50 characters
   +"v->{String t=\""+t.replace("\"","\\\"")).substring(0,50);}
            //  Concatted with the first 50 characters of my answer
            //  with correct escape-slashes

```
> 2 votes

# Answer
# 6: 70 characters, Emoji

```
⛽as=:'"alert(eval(c="''abcdefghijklmnopqrstuvwxyzAC⛽0-1✂➡

```

Try it online!

It seems that it is impossible to make it not output the trailing newline. If that's not OK then I'll remove the answer.

**Explanation:**

```
⛽ ... 	String literal
		Duplicate
⛽		Push ⛽ as a string
		Swap the top two strings. Stack: [long literal] "⛽" [long literal]
		Concatenate.
0-1✂	Remove the last character
		Concatenate.
➡		Print.

```
> 1 votes

# Answer
# 12: 202 characters, Ruby

```
puts "21ipdgmtwkkke7ynvzpcnlzt7kl".to_i(36).to_s(7).gsub('0','>').gsub('1','+').gsub('2','-').gsub('3','<').gsub('4','[').gsub('5','.').gsub('6',']')+'puts "21ipdgmtwkkke7ynvzpcnlzt7kl".to_i(36).to_s(7'

```

Try it online!

---

Encodes the first fifty characters of the previous answer in base seven

* 0: \>
* 1: +
* 2: -
* 3: \<
* 4: \[
* 5: .
* 6: \]

Then converts it to base 36 to get "21ipdgmtwkkke7ynvzpcnlzt7kl"
> 1 votes

# Answer
# 9: 55 characters, Jelly

```
“"v->{String t=`"as=:'\`"alert(eval(c=\`"''abcdefg”;”“;

```

Try it online!

---

I removed the non-ASCII character  from the the output since that is allowed and Jelly was ignoring it.

**Explanation**

This begins with the string literal of the first 50 characters (minus ) of the previous answer then appends the character  to it with `;”“` then appends the original string literal to the end again with the final `;`. Since a character was removed the first 50 characters of my source code are the 49 from the previous answer with a  in front which allows this program to be so short. (Yes I realize this is not but why not golf it if you can?)
> 0 votes

# Answer
# 10:116 Characters, Python 3

```
print('''“"v->{String t=`"as=:'\`"alert(eval(c=\`"''abcdefgprint(\'\'\'“"v->{String t=`"as=:'\`"alert(eval(c=\`"''')

```

---

Simply prints a string consisting of the first 50 characters of answer 9, followed by the first 50 characters of its own source. No quine-like cleverness is needed, becuase the escaped quotes (`\'\'\'`) appear after the 50th character and hence don't need to be reproduced in the output.

This method will work in virtually any language - you'd just have to escape any quote characters that appear in the previous answer. Accordingly, I don't think there is much challenge in this challenge.
> 0 votes

# Answer
# 11: 723 Characters, Brainf\***

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

```

Stripped unprintable  character. Almost completely generated by Brainfuck Text Generator. Might as well be lazy, right?

TIO

```
Print [print('''"v->{String t=`"as=:'\`"alert(eval(c=\`"] +[------->++<]>++.++.---------.+++++.++++++.+[--->+<]>+.-...-----------.++++++.[----->++<]>++.--[++>---<]>-.---[-->+++<]>-.[->++<]>-.[--->++<]>+.[--->+<]>+++.--.---------.+++++.-------.-[--->+<]>--.---[->++++<]>.[-->+<]>+++.+++[-->+++<]>.[->+++<]>++.+[--->+<]>.--[--->+<]>--.+[-->+<]>+++.---.-[--->++<]>+.+[------>+<]>.++++.[->+++<]>++.+[--->+<]>.+++++++++++.-------.+++++++++++++.++.+[--->+<]>+.+[--->+<]>++.[--->+<]>-.[->+++<]>-.+++++++++++.[--->+<]>++++.+[--->+<]>.[--->++<]>-----.+[-->+++<]>-.++++.[->+++<]>++.
Clear all cells to left until first empty cell [[-]<]
Print [+[------->++<]>++.++.---------.+++++.++++++.+[--->] ++[------>+<]>.++[->++<]>+.-[-->+<]>.......---[-->+++<]>-.+[--->++<]>+..+[----->+<]>.++[-->+++<]>.[--->++<]>.+[--->++<]>+..+++.---..+++.-.........+.---.....+++.---......+++.---.++[->++<]>+.-[-->+<]>...---[-->+++<]>-.

```
> 0 votes

---
Tags: quine, answer-chaining
---


title: Was it a Superb Shuffle™

text:
# Question
Title: Was it a Superb Shuffle™
According to this question a Superb Shuffle™ is defined as a full deck of cards (including jokers) which follows this set of rules:

* No two cards (except Jokers) of the same suit are adjacent.
* No card (except Jokers) is adjacent to one of the same value.
* No card (except Jokers) is adjacent to one of an adjacent value (one higher or one lower in this order, A, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K, A. Notice that Ace can not be adjacent to either a 2 or a King).
* The Jokers can be in any position.

The cards are expressed as a value(A, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K), followed by a suit (C, D, H, S). For example 'AS' is the Ace of Spades. The Jokers are represented by a single letter J.

* Write some code to indicate if an array of cards is a Superb Shuffle™ or not.
* Use any language you like.
* Attempt to do so in the smallest number of bytes.

Test cases:

1: This is Superb™

```
[
  "AS", "5D", "9H", "KC", "2D", "6H", "10C", "QS", "3H", "7C", "9S",
  "KD", "4C", "6S", "10D", "AC", "3S", "7D", "JH", "J", "4D", "8H",
  "QC", "AD", "5H", "9C", "JS", "2H", "6C", "8S", "QD", "3C", "5S",
  "9D", "KH", "2S", "6D", "10H", "J", "3D", "7H", "JC", "KS", "4H",
  "8C", "10S", "AH", "5C", "7S", "JD", "2C", "4S", "8D", "QH"
]

# true

```

2: This is all sorted

```
[
  "AS", "2S", "3S", "4S", "5S", "6S", "7S", "8S", "9S", "10S", "JS", "QS", "KS",
  "AD", "2D", "3D", "4D", "5D", "6D", "7D", "8D", "9D", "10D", "JD", "QD", "KD",
  "AH", "2H", "3H", "4H", "5H", "6H", "7H", "8H", "9H", "10H", "JH", "QH", "KH",
  "AC", "2C", "3C", "4C", "5C", "6C", "7C", "8C", "9C", "10C", "JC", "QC", "KC",
  "J", "J"
]

# false

```

3: Aces together

```
[
  "AC", "AS", "AD", "AH", "5D", "9H", "KC", "2D", "6H", "10C", "QS",
  "9S", "KD", "4C", "6S", "10D", "3S", "7D", "JH", "J", "4D", "8H",
  "QC", "5H", "9C", "JS", "2H", "6C", "8S", "QD", "3C", "5S", "3H",
  "9D", "KH", "2S", "6D", "10H", "J", "3D", "7H", "JC", "KS", "4H",
  "8C", "10S", "5C", "7S", "JD", "2C", "4S", "8D", "7C", "QH"
]

# false

```

4: Crazy 8's

```
[
  "AS", "5D", "9H", "KC", "2D", "6H", "10C", "QS", "3H", "7C", "9S",
  "KD", "4C", "6S", "10D", "AC", "3S", "7D", "JH", "J", "4D", "AH",
  "QC", "AD", "5H", "9C", "JS", "2H", "6C", "QD", "3C", "5S", "10S",
  "9D", "KH", "2S", "6D", "10H", "J", "3D", "7H", "JC", "KS", "4H",
  "5C", "7S", "JD", "2C", "4S","QH", "8D", "8S", "8C", "8H"
]

# false

```

5: Also superb

```
[
  "AS", "6H", "9S", "AC", "4D", "9C", "QD", "2S", "7H", "10S", "2C",
  "5D", "10C", "KD", "3S", "8H", "JS", "3C", "6D", "JC", "AH", "4S",
  "9H", "QS", "4C", "7D", "QC", "2H", "5S", "10H", "KS", "5C", "8D",
  "KC", "3H", "6S", "JH", "AD", "6C", "9D", "J", "4H", "7S", "QH",
  "2D", "7C", "10D", "J", "5H", "8S", "KH", "3D", "8C", "JD"
]

# true

```

6: Ace by 2

```
[
  "AS", "2S", "6H", "9S", "AC", "4D", "9C", "QD",  "7H", "10S", "2C",
  "5D", "10C", "KD", "3S", "8H", "JS", "3C", "6D", "JC", "AH", "4S",
  "9H", "QS", "4C", "7D", "QC", "2H", "5S", "10H", "KS", "5C", "8D",
  "KC", "3H", "6S", "JH", "AD", "6C", "9D", "J", "4H", "7S", "QH",
  "2D", "7C", "10D", "J", "5H", "8S", "KH", "3D", "8C", "JD"
]

# false

```

7: Ace by King

```
[
  "AS", "KH", "2S", "6H", "9S", "AC", "4D", "9C", "QD",  "7H", "10S",
  "2C", "5D", "10C", "KD", "3S", "8H", "JS", "3C", "6D", "JC", "AH",
  "4S", "9H", "QS", "4C", "7D", "QC", "2H", "5S", "10H", "KS", "5C",
  "8D", "KC", "3H", "6S", "JH", "AD", "6C", "9D", "J", "4H", "7S",
  "QH", "2D", "7C", "10D", "J", "5H", "8S", "3D", "8C", "JD"
]

# false

```

8: Jokers together

```
[
  "AS", "5D", "9H", "KC", "2D", "6H", "10C", "QS", "3H", "7C", "9S",
  "KD", "4C", "6S", "10D", "AC", "3S", "7D", "JH", "J", "J", "4D",
  "8H", "QC", "AD", "5H", "9C", "JS", "2H", "6C", "8S", "QD", "3C",
  "5S", "9D", "KH", "2S", "6D", "10H", "3D", "7H", "JC", "KS", "4H",
  "8C", "10S", "AH", "5C", "7S", "JD", "2C", "4S", "8D", "QH"
]

# true

```

9: Adjacent suit/value separated by Jokers

```
[
  "AS", "6H", "9S", "AC", "4D", "J", "4H", "2S", "7H", "10S", "2C",
  "5D", "10C", "KD", "3S", "8H", "JS", "3C", "6D", "JC", "AH", "4S",
  "9H", "QS", "4C", "7D", "QC", "2H", "5S", "10H", "KS", "5C", "8D",
  "KC", "3H", "6S", "JH", "AD", "6C", "9D", "J", "QD", "7S", "QH",
  "2D", "7C", "10D", "8C", "5H", "8S", "KH", "3D", "9C", "JD"
]

# true

```

# Answer
# JavaScript (ES7), 88 bytes

Returns **true** for Superb™ or **false** for Ugly™.

```
a=>a.every(r=s=([a,b,c])=>!s|!b|!((r-(r='34567891JQKA'.search(a)))**2%13<2|s==(s=c||b)))

```

Try it online!

### How?

Each card is split into 3 characters **a**, **b** and **c**, some of which might be *undefined*.

The rank is given by the position of **a** in the string **"34567891JQKA"** (**'2'** gives **-1**). The suit is given by **b** for all cards but 10's, for which we need to test **c** instead, and *Jokers* that have an *undefined* suit.

We keep track of the previous rank in **r** and the previous suit in **s**.

We use the expression \\$(r - new\\\_rank)^2 \bmod 13\\$ to detect invalid consecutive ranks. This gives:

* \\$0\\$ if both ranks are equal
* \\$1\\$ if the absolute difference between the ranks is \\$1\\$
* \\$1\\$ if we have an *Ace* followed by a *Two* or a *Two* followed by an *Ace*, because the squared difference is \\$144\\$ and we have \\$144 \equiv 1 \pmod{13}\\$.
* an integer greater than \\$1\\$ in all other cases

We simply compare the new suit with **s** to detect identical consecutive suits.

We use the expression **!s | !b** to detect that either the previous or the current card is a *Joker*, in which case the results of the other tests are discarded.
> 9 votes

# Answer
# Retina 0.8.2, 68 bytes

```
.*,(.*)
$1,$&
J\b
--
10
T
\b\w
$&$&
T`Ao`2-9TJQKA`\b.
(\w).{2,4}\1.*

```

Try it online! Link includes test cases. Outputs `0` if superb, `1` if not. Explanation:

```
.*,(.*)
$1,$&

```

Copy the last card to the beginning to simulate wrap-around.

```
J\b
--

```

Replace the jokers with two-character placeholders, which is enough to ensure that the surrounding cards aren't matched with each other.

```
10
T

```

And replace the `10`s with tens.

```
\b\w
$&$&

```

Duplicate the rank of each card.

```
T`Ao`2-9TJQKA`\b.

```

Calculate the adjacent rank.

```
(\w).{2,4}\1.*

```

Look for adjacent cards of the same suit or same or adjacent rank.
> 4 votes

# Answer
# Java 10, ~~246~~ ~~210~~ ~~205~~ ~~178~~ 170 bytes

```
d->{var r=1>0;int p=-1,P=p,q,u;for(var c:d)r&=p<0|(u=(p-(p=(q=c.length())<2?-1:"A234567891JQK".indexOf(c.charAt(0))))%12)<-1|u>1&P!=(P=q<2?p:c.charAt(q>2?2:1));return r;}

```

Try it online.

**Explanation:**

```
d->{                   // Method with String-array parameter and boolean return-type
  var r=1>0;           //  Result-boolean, starting at true
  int p=-1,            //  Previous value, starting at -1
      P=p,             //  Previous suit, starting at -1
      q,u;             //  Temp integers
  for(var c:d)         //  Loop over the cards of the input-deck:
    r&=p<0             //   Validate whether the previous value is -1
       |(u=(p-         //   Or if the difference between the previous and current value,
          (p=          //   where the current value is:
                       //   (and replace the previous with the current value for the next
                       //   iteration at the same time)
             (q=c.length())<2?
                       //    Is it a Joker:
               -1      //     Use -1
              :        //    Else:
               "A234567891JQK".indexOf(c.charAt(0))
                       //     Use 0-12 depending on the order
        ))%12)         //   (Modulo-12 for 'A' and 'K')
              <-1|u>1  //   is more than 2
       &P!=            //   And the previous and current suits are not equal,
           (P=         //   where the current suit is:
                       //   (and replace the previous with the current suit for the next
                       //   iteration at the same time)
              q<2?     //    Is it a Joker:
               p       //     Use -1
              :        //    Else:
               c.charAt(q>2?2:1));
                       //     Use the suit-character
                       //     where the `q>2?2:1` is for cards of value 10
  return r;}           //  Return if all validations inside the loop have succeeded

```
> 3 votes

# Answer
# Python 2, 108 bytes

```
lambda l:all('J'in(a,b)or(q(a[0])-q(b[0])+1)%13>2<a[-1]!=b[-1]for a,b in zip(l,l[1:]))
q='234567891JQK'.find

```

Try it online!

---

# Python 3, 109 bytes

```
lambda l:all([(q(a[0])-q(b[0])+1)%13*(A!=B)>2for(*a,A),(*b,B)in zip(l,l[1:])if a>[]<b])
q='234567891JQK'.find

```

Try it online!

Python 3 wins bytes with iterable unpacking but loses bytes by refusing to chain together comparisons of differently-typed items. The unpacking needs to handle both `'J'` and `'10S'`, which means it can either extract the first value or the last value, but not both.
> 3 votes

# Answer
# Ruby, 123 bytes

```
->a{a.each_cons(2).all?{|a,b|a==?J||b==?J||(s="A234567891JQK".chars).zip(s.rotate).all?{|f|((a.chars|b.chars)-[?0]-f)[2]}}}

```

Try it online!

### Explanation:

Without going too much into detail:

* split every pair into single characters
* remove '0' if any
* remove duplicate characters
* try to remove pairs of adjacent values

If after the treatment, 3 characters are left, the pair is good.
> 2 votes

# Answer
# Python 3, 130 125 bytes

*5 bytes saved thanks to Chas Brown*

```
v="A234567891JQK".find;s=lambda d:len(d)<2or("J"in d[:2]or 1<abs(v(d[0][0])-v(d[1][0]))<12and d[0][-1]!=d[1][-1])and s(d[1:])

```

My first post here, so this could probably be golfed down a little more.

### Explanation

Recursive lambda; checks if the first two cards of the current list are of different suits, are different ranks, and their ranks differ by more than 1 (but less than 12, to account for Ace-King), or if one of the two cards is a Joker, in which case it's fine, then consumes the first element of the list and recurses.
> 2 votes

# Answer
# Ruby, 119 bytes

```
f=->s,c=20,d=?Z{a,*b=s;a ?(x=a[-1];x==?J||(e=((i="A234567891JQK".index(a[0]))-c)%13;e>1&&e<12)&&x!=d)&&f[b,i||20,x]:!p}

```

Try it online!

Recursive version.
It walks through the array and compares the current card to the last card. The rank is searched in the string "A234567891JQK" and jokers are skipped. It starts with a dummy previous card "20Z" which will accept any neighbour.
> 1 votes

# Answer
# Python 2, 122 bytes

```
lambda a:all((12>abs(R(c[0])-R(d[0]))>1and c[-1]!=d[-1])or'J'in c[-1]+d[-1]for c,d in zip(a,a[1:]))
R='A234567891JQK'.find

```

Try it online!
> 1 votes

---
Tags: code-golf, decision-problem, card-games
---