title: Complete the landscape

text:
# Question
Title: Complete the landscape
Carcassonne is a tile-based game, where the objective is to construct Roads, Cities and Monasteries, in order to score points. The game works by players taking turns to draw and place tiles to construct a landscape, then claiming roads, cities and monasteries. An example landscape is:

There are \\$19\\$ distinct tiles (ignoring rotations), each of which contains at least one feature (Road, City or Monastery):

Also, notice that the landscape must be consistent. This means that roads must connect to other roads, city edges must connect to other city edges and fields must connect to fields. Therefore, these tiles are inconsistent:

To avoid this challenge being about image processing, we can translate each tile into a list containing \\$5\\$ values, according to this legend:

```
[North edge, East edge, South edge, West Edge, # of cities]

0: Field
1: Road
2: City

```

For instance, this tile can be described as `[2, 0, 1, 1, 1]`. Using this legend, we can describe each tile uniquely, and it's rotations are rotations of the first four elements. The entire grid can be described as a rectangular matrix, with a \\$20^\text{th}\\$ distinct value for an empty square. Translating the first landscape into this format, we get:

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

```

using `[]` to represent an empty square. The complete list of tiles (ignoring rotations) in the same grid as the second image is

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

```

---

Your task is to take in a rectangular matrix where every element save one is one of the 19 tiles given above or one of their rotations. Tiles can appear more than once, and not every tile will appear in every input. This landscape will be consistent, as defined above. You should take in this input and output the tile that could fill the empty space in the array, keeping the landscape consistent, as defined above. You may output the tile in any rotation.

As the number of cities on a tile is redundant for this task, you may choose instead to only work with 17 tiles (as 2 tiles are duplicated when ignoring cities) and take input as lists in the form `[N, E, S, W]` instead, giving this list of tiles

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

```

If there are multiple tiles that would work, you may output any number of valid tiles. If no such tile exists, you may produce any output/result that could not be construed as a tile (i.e. it's not in the 19 tiles specified above, nor in any of their rotations). The representation of the "empty space" in the input may be your choice, so long as its consistent, and (although I'm not sure why you would) it isn't one of the 19 tiles above or their rotations, and there will only ever be a single empty space.

This is , so the shortest code in bytes wins.

## Test cases

```
Landscape -> Potential tiles
[[[]]] -> Any tile
[[[0, 0, 0, 0, 0], []]] -> [1, 0, 1, 0, 0], [0, 0, 1, 1, 0], [0, 1, 1, 1, 0], [2, 0, 0, 0, 1], [2, 2, 0, 2, 1], [0, 0, 0, 0, 0], [2, 2, 0, 0, 1], [2, 2, 0, 0, 2], [0, 0, 1, 0, 0], [2, 0, 1, 1, 1], [2, 1, 1, 0, 1], [0, 2, 0, 2, 1], [2, 1, 0, 1, 1], [2, 0, 2, 0, 2]
[[[], [0, 1, 0, 1, 0], [0, 1, 0, 1, 0], [0, 1, 0, 1, 0]]] -> [0, 0, 1, 1, 0], [1, 0, 1, 0, 0], [2, 1, 1, 2, 1], [2, 1, 0, 1, 1], [0, 1, 1, 1, 0], [2, 0, 1, 1, 1], [2, 1, 1, 1, 1], [2, 1, 1, 0, 1], [2, 2, 1, 2, 1], [0, 0, 1, 0, 0], [1, 1, 1, 1, 0]
[[0, 1, 0, 1, 0], [], [0, 1, 0, 1, 0], [0, 1, 0, 1, 0]] -> [1, 0, 1, 0, 0], [2, 1, 0, 1, 1], [0, 1, 1, 1, 0], [2, 1, 1, 1, 1], [1, 1, 1, 1, 0]
[[[0, 1, 1, 0, 0], [0, 1, 0, 1, 0], [0, 0, 1, 1, 0]], [[1, 1, 0, 0, 0], [0, 1, 0, 1, 0], []]] -> [0, 0, 1, 1, 0], [2, 1, 1, 2, 1], [0, 1, 1, 1, 0], [2, 0, 1, 1, 1], [2, 1, 1, 1, 1], [2, 1, 1, 0, 1], [1, 1, 1, 1, 0]
[[[2, 0, 0, 0, 1], [0, 2, 2, 0, 2], [0, 2, 0, 2, 1], [0, 0, 0, 2, 1]], [[0, 2, 2, 0, 1], [2, 1, 2, 2, 1], [0, 0, 1, 1, 0], [0, 0, 0, 0, 0]], [[2, 1, 1, 2, 1], [], [1, 1, 2, 0, 1], [0, 0, 0, 1, 0]]] -> [2, 0, 1, 1, 1]

```

# Answer
# Charcoal, 87 bytes

```
Ｆθ⊞ι⟦⁷⟧⊞θ⟦⟦⁷⟧⟧≔⊟Φθ№ιυηＩΦＥ⁸¹Ｅ⁴Ｘ²﹪÷ιＸ³λ³∧∧⊖↔⁻Σιχ⊙Φιμ⊖↔⁻λ§ιμ⬤ι＆λ§§§θ⁺⌕θη⁻⁼μ²¬μ⁺⌕ηυ∧μ⁻²μ⁺²μ

```

Try it online! Link is to verbose version of code. Takes input as a nested array of `[N, E, S, W]` values where `4` represents a field and outputs a double-spaced list of sets of four values representing all valid rotations of all valid tiles. Explanation:

```
Ｆθ⊞ι⟦⁷⟧⊞θ⟦⟦⁷⟧⟧

```

Add borders to the input allowing any edge.

```
≔⊟Φθ№ιυη

```

Find the row of the tile to be placed.

```
ＩΦＥ⁸¹Ｅ⁴Ｘ²﹪÷ιＸ³λ³

```

Output all rotations of all tiles, except...

```
∧∧⊖↔⁻Σιχ⊙Φιμ⊖↔⁻λ§ιμ⬤ι

```

... non-existent\* tiles, and...

```
＆λ§§§θ⁺⌕θη⁻⁼μ²¬μ⁺⌕ηυ∧μ⁻²μ⁺²μ

```

... tiles that don't fit.

\*There are two categories of non-existent tiles:

* A tile that features all three features must have two roads and one each of the other two features. Conveniently with this input format illegal tiles would have a feature sum of either `9` or `11` and no other tiles have this sum.
* A tile that features two roads and two city edges cannot have them alternating. Conveniently with this input format illegal tiles alternate between `1` and `2` thus their cyclic consecutive absolute differences are all `1`. (Note that by comparison it's possible for tiles to feature two fields and two other features and still have them be alternating.)
> 6 votes

# Answer
# Jelly, 40 bytes

(39 if we may output each tile as many times as it will fit up to rotational symmetry - remove `Q`)

```
3ṗ4o@U,ZƊṙ2=ḢʋƝ€€ȦʋƇ⁸ṙJṂƊ€Qḟ“[^go{~Ẉ‘b4¤

```

A monadic Link that accepts a list of lists of tiles as lists using the no-cities format of `[N,E,S,W]` with `Field=1`, `Road=2`, and `City=3`. Yields a list of tiles that can fit.

The outputted tiles are provided rotated such that their representation is the smallest it can be lexicographical (e.g. if `[3,2,2,1]` fits in any orientation(s) it would be given (once) as `[1,3,2,2]`)

**Try it online!** Or see the test-suite (with the IO tweaked to use `0`, `1`, and `2`, as in the question).

### How?

There are \\$17\\$ available tiles out of \\$24\\$ possible tiles (up to rotational symmetry), so we find all possible tiles that could fit in any rotation, rotate each of them to their lexicographically minimum and then filter out the \\$7\\$ unavailable tiles.

```
3ṗ4o@U,ZƊṙ2=ḢʋƝ€€ȦʋƇ⁸... - Link: Board
3ṗ4                      - {implict range 3 = [1,2,3]} Cartesian power 4
                             -> All Tiles including unavailable ones like [1,2,3,3]
                                with all of their uniquely identifiable rotations
                    ⁸    - chain's left argument -> Board
                   Ƈ     - filter {All Tiles} keeping those for which:
                  ʋ      -   last four links as a dyad - f(Potential Tile, Board):
   o@                    -     {Board} logical OR (vectorising) {Potential Tile}
                                 -> Board with Potential Tile inserted
     U,ZƊ                -     reverse all the tiles and pair with transpose
                                 (allows same logic for both E-W and S-N checks)
                €        -     for each of these two:
               €         -       for each row:
              Ɲ          -         for neighboring pairs of tiles:
             ʋ           -           last four links as a dyad - f(L, R):
         ṙ2              -             rotate {L} left two
           =             -             {that} equals (vectorising) {R}
            Ḣ            -             head -> relevant comparison
                 Ȧ       -     any an all? (0 if any comparison was falsey)
                             -> all rotations of all tiles that fit
                                (including the unavailable ones)

...ṙJṂƊ€Qḟ“[^go{~Ẉ‘b4¤   - ...continued:
       €                 - for each found tile:
      Ɗ                  -   last three links as a monad - f(T=rotated tile):
    J                    -     range of length {T} -> [1,2,3,4]
   ṙ                     -     {T} rotate left (vectorised) {[1,2,3,4]}
     Ṃ                   -     minimum -> lexicographically minimal rotation
        Q                - deduplicate -> Found Tiles (in their minimal rotation)
                     ¤   - nilad followed by link(s) as a nilad:
          “[^go{~Ẉ‘      -   code-page indices -> [91,94,103,111,123,126,187]
                   b4    -   to base four
                               -> Unavailable Tiles (in their minimal rotation) = [[1,1,2,3],[1,1,3,2],[1,2,1,3],[1,2,3,3],[1,3,2,3],[1,3,3,2],[2,3,2,3]]
         ḟ               - {Found Tiles} filter discard {Unavailable Tiles}

```
> 3 votes

# Answer
# Python3, 301 bytes:

```
E=enumerate
def f(b):
 for x,r in E(b):
  for y,P in E(r):
   if[]==P:return[i for i in[[v//d%3for d in(1,3,9,27)]for v in b"[$)'S>QPYDZ&_<( G"]if any(all(X in(Y,[])for X,Y in zip([c and b[x+~q%(2-2//q*4)][y+q%(2-q//5*4)][q%4]for q,c in E((b*x,r[y+1:],b[x+1:],b*y),2)],i[j:]+i[:j]))for j in range(4))]

```

Try it online!
> 2 votes

# Answer
# JavaScript (Node.js), 193 bytes

Expects a matrix of strings in `"NESW"` format (or an empty string for the missing tile).

Returns a list of strings in the same format. Only one rotation per tile is included.

```
m=>m.map((r,y)=>r.map((s,x)=>s||0xDB5ECDAAE7E20755344F4D6A4CEn.toString(3).replace(/..../g,s=>[...s].every((_,i,a)=>a.some((_,d)=>m[y+~-d%2]?.[x-(d-2)%2]?.[d^2]-s[d+i&3]))||o.push(s))),o=[])&&o

```

Attempt This Online!

### Commented

```
m =>                        // m[] = input matrix
m.map((r, y) =>             // for each row r[] at index y in m[]:
  r.map((s, x) =>           //   for each string s at index x in r[]:
    s ||                    //     abort if this is not the missing tile
    0xDB5E..A4CEn           //     lookup BigInt encoding the 17 tiles
    .toString(3)            //     convert it to base 3
    .replace(               //     -> "2222222122202211..0000"
      /..../g,              //     split into groups of 4 characters
      s =>                  //     for each string s:
      [...s]                //       split s
      .every((_, i, a) =>   //       for i = 0 to i = 3:
        a.some((_, d) =>    //         for d = 0 to d = 3:
          m[                //           extract the cell located at
            y + ~-d % 2     //           row y + dy
          ]?.[              //           and
            x - (d - 2) % 2 //           column x + dx
          ]?.[              //           take the character corresponding
            d ^ 2           //           to the opposite direction
          ] -               //           and test whether it's defined
          s[d + i & 3]      //           and different from the character
                            //           in s at index (d + i) mod 4
        )                   //         end of some()
      )                     //       end of every()
      || o.push(s)          //       if falsy, add s to o
    )                       //     end of replace()
  ),                        //   end of map()
  o = []                    //   initialize o to an empty array
) && o                      // end of map(); return o

```
> 2 votes

---
Tags: code-golf, array, board-game, tiling
---


title: Shamir's Secret Sharing

text:
# Question
Title: Shamir's Secret Sharing
Given `n` (the number of players), `t` (the threshold value), and `s` (the secret), output the `n` secrets generated by Shamir's Secret Sharing algorithm.

## The Algorithm

For the purposes of this challenge, the computations will be done in **GF(251)** (the finite field of size `251`, otherwise known as the integers *mod 251*). Ordinarily, the field would be chosen such that its size is a prime much greater than `n`. To simplify the challenge, the field size will be constant. `251` has been chosen because it is the largest prime representable by an 8-bit unsigned integer.

1. Generate `t-1` random integers in the (inclusive) range `[0, 250]`. Label these *a1* through *at-1*.
2. Construct a `t-1`th degree polynomial using `s` as the constant value and the random integers from step 1 as the coefficients of the powers of `x`: *f(x) = s + x\*a1 \+ x2\*a2 \+ ... + xt-1\*at-1*.
3. Output `(f(z) mod 251)` for each `z` in the (inclusive) range `[1, n]`.

## Reference Implementation

```
#!/usr/bin/env python
from __future__ import print_function
import random
import sys

# Shamir's Secret Sharing algorithm
# Input is taken on the command line, in the format "python shamir.py n t s"

n, t, s = [int(x) for x in sys.argv[1:4]]
if t > n:
    print("Error: t must be less than or equal to n")
    exit()
if n not in range(2, 251):
    print("Error: n must be a positive integer less than 251")
    exit()
if t not in range(2, 251):
    print("Error: t must be a positive integer less than 251")
    exit()
if s not in range(251):
    print("Error: s must be a non-negative integer less than 251")
    exit()
p = 251
a = [random.randrange(0, 251) for x in range(t-1)]

def f(x):
    return s + sum(c*x**(i+1) for i,c in enumerate(a))

# Outputting the polynomial is for explanatory purposes only, and should not be included
#  in the output for the challenge
print("f(x) = {0} + {1}".format(s, ' + '.join('{0}*x^{1}'.format(c, i+1) for i,c in enumerate(a))))
for z in range(1, n+1):
    print(f(z) % p)

```

## Verification

The following Stack Snippet can be used to verify outputs:

```
var validate = function() {
  $('#nts-error').attr('hidden', parseInt($('#n').val()) >= parseInt($('#t').val()));
  $('#check').prop('disabled', parseInt($('#n').val()) < parseInt($('#t').val()));
};

// the following function is taken from https://rosettacode.org/wiki/Combinations#JavaScript
var combinations = function(arr, k) {
  var i,
    subI,
    ret = [],
    sub,
    next;
  for (i = 0; i < arr.length; i++) {
    if (k === 1) {
      ret.push([arr[i]]);
    } else {
      sub = combinations(arr.slice(i + 1, arr.length), k - 1);
      for (subI = 0; subI < sub.length; subI++) {
        next = sub[subI];
        next.unshift(arr[i]);
        ret.push(next);
      }
    }
  }
  return ret;
};

// The following code is taken from https://en.wikipedia.org/wiki/Shamir%27s_Secret_Sharing#Javascript_example with the modification that the prime is 251, not 257

var prime = 251;

/* Gives the decomposition of the gcd of a and b.  Returns [x,y,z] such that x = gcd(a,b) and y*a + z*b = x */
function gcdD(a, b) {
  if (b == 0) return [a, 1, 0];
  else {
    var n = Math.floor(a / b),
      c = a % b,
      r = gcdD(b, c);
    return [r[0], r[2], r[1] - r[2] * n];
  }
}

/* Gives the multiplicative inverse of k mod prime.  In other words (k * modInverse(k)) % prime = 1 for all prime > k >= 1  */
function modInverse(k) {
  k = k % prime;
  var r = (k < 0) ? -gcdD(prime, -k)[2] : gcdD(prime, k)[2];
  return (prime + r) % prime;
}

/* Join the shares into a number */
function join(shares) {
  var accum, count, formula, startposition, nextposition, value, numerator, denominator;
  for (formula = accum = 0; formula < shares.length; formula++) {
    /* Multiply the numerator across the top and denominators across the bottom to do Lagrange's interpolation
     * Result is x0(2), x1(4), x2(5) -> -4*-5 and (2-4=-2)(2-5=-3), etc for l0, l1, l2...
     */
    for (count = 0, numerator = denominator = 1; count < shares.length; count++) {
      if (formula == count) continue; // If not the same value
      startposition = shares[formula][0];
      nextposition = shares[count][0];
      numerator = (numerator * -nextposition) % prime;
      denominator = (denominator * (startposition - nextposition)) % prime;
    }
    value = shares[formula][1];
    accum = (prime + accum + (value * numerator * modInverse(denominator))) % prime;
  }
  return accum;
}

$('#check').click(
  function() {
    var good = true;
    var problem = [];
    var n = parseInt($('#n').val());
    var t = parseInt($('#t').val());
    var s = parseInt($('#s').val());
    combinations([...Array(n + 1).keys()].slice(1), t).forEach(
      function(xArr) {
        var xfArr = xArr.map(
          function(x) {
            return [x, parseInt($('#f' + x).val())];
          }
        );
        var L = join(xfArr);
        if (L !== s) {
          good = false;
          problem.push(xArr);
        }
      }
    );
    $('#valid').html(good ? "True" : ("False (problematic secret sets: {" + problem.map(
      function(elem) {
        return "[" + elem.join(', ') + "]";
      }) + "})"));
  }
);

$('#n').change(
  function() {
    var inputHTML = "";
    for (var i = 1; i <= parseInt($('#n').val()); i++) {
      inputHTML += 'f(' + i + '): <input type="number" min="0" max="250" value="0" id="f' + i + '"><br>\r\n';
    }
    $('#inputs').html(inputHTML);
    validate();
  }
);

$('#t').change(
  function() {
    validate();
  }
);
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
n:
<input type="number" min="2" max="250" value="6" id="n">t:
<input type="number" min="2" max="250" value="3" id="t">s:
<input type="number" min="0" max="250" value="230" id="s">
<br>
<div id="nts-error" hidden="true">t must be less than or equal to n!</div>
<br>
<br>
<div id="inputs">
  f(1):
  <input type="number" min="0" max="250" value="35" id="f1">
  <br>f(2):
  <input type="number" min="0" max="250" value="95" id="f2">
  <br>f(3):
  <input type="number" min="0" max="250" value="159" id="f3">
  <br>f(4):
  <input type="number" min="0" max="250" value="227" id="f4">
  <br>f(5):
  <input type="number" min="0" max="250" value="48" id="f5">
  <br>f(6):
  <input type="number" min="0" max="250" value="124" id="f6">
</div>
<br>
<input type="submit" id="check" value="Verify">
<br>
<br>Valid:
<div id="valid"></div>
```

## Rules

* `s` will be a non-negative integer less than `251`, and `n` and `t` will be positive integers less than `251` and greater than `1`. Furthermore, you are guaranteed that the inputs are valid (meaning `t <= n`).
* Input and output can be in any reasonable, unambiguous, and consistent format.
* Random numbers are to be sampled from a uniform distribution - each possible value should have equal probability of being chosen.

# Answer
# Jelly, 15 bytes

```
251©xX€⁵0¦ḅÐ€%®

```

Expects **t**, **n**, and **s** as command-line arguments. Try it online!

### How it works

```
251©xX€⁵0¦ḅÐ€%®  Main link. Left argument: t. Right argument: n Third argument: s

251©             Yield 251 and copy it to the register.
    x            Repeat [251] t times.
     X€          Random choice each; pseudo-randomly choose t integers from
                 [1, ..., 251]. Since 251 = 0 (mod 251), this is equivalent to
                 choosing them from [0, ..., 250].
       ⁵0¦       Replace the last generated integer (index 0) with s (⁵).
          ḅÐ€    Interpret the resulting array as a base-k number, for each k in
                 [1, ..., n], and convert to integer.
              ®  Yield 251 from the register.
             %   Take the generated integers modulo 251.

```
> 13 votes

# Answer
# Mathematica, ~~59~~ 56 bytes

```
Mod[Power~Array~{#2,#-1}.RandomInteger[250,#-1]+#3,251]&

```

Takes three arguments in the order *t*, *n*, and *s*. Constructs a 2d-array with *n* rows and *t*-1 columns. Each row vector *j*, numbered from 1 thru *n*, contains the powers of *j* thru *j**t*-1. Then a vector of random integer coefficients in the range 0 thru 250 is created with *t*-1 values. That is matrix-multiplied with the 2d-array, and then *s* is added element-wise and taken module 251 to get the value of the polynomial at each of the *n* points.
> 8 votes

# Answer
## CJam, ~~27~~ 25 bytes

```
{,:)@({;251mr}%@+fb251f%}

```

Test it here.
> 5 votes

# Answer
# Pyth, 24 bytes

```
J+EmOK251tEm%s.e*b^dkJKS

```

Try it online!

Input order: `n` `s` `t` separated by linefeed.
> 3 votes

# Answer
# JavaScript, 181 bytes

```
(n,t,s)=>{r=Array(t-1).fill(0).map($=>{return Math.random()*251});f=(x=>{p = 0;r.map((k,c)=>p+=k*Math.pow(x, c));return s+p});_=Array(t-1).fill(0);_.map((l,i)=>_[i]=f(i));return _;}

```

Ungolfed:

```
(n, t, s) => {
    r = Array(t - 1).fill(0).map($ =>{return Math.random() * 251});
    f = (x => {
        p = 0;
        r.map((k, c) => p += k * Math.pow(x, c));
        return s + p
    });
    _ = Array(t - 1).fill(0);
    _.map((l, i) => _[i] = f(i));
    return _;
}

```

I don't know how to properly check it, but I do know that it was a pain to get JS to map across a new array since apparently `.map` skips undefined values. If anyone sees any ways to improve, or flaws, don't hesitate to let me know.
> 3 votes

# Answer
# MATL, ~~20~~ 19 bytes

```
251tliq3$Yrihi:ZQw\

```

Input order is `t`, `s`, `n`.

**Try it online!**

### Explanation

```
251t    % Push 251 twice
l       % Push 1
iq      % Take input t. Subtract 1
3$Yr    % Generate t-1 random integers in [1 2 ... 251]
ih      % Take input s. Concatenate with the random integers
i:      % Take input n. Generate range [1 2 ... n]
ZQ      % Evvaluate polynomial at those values
w       % Swap to move copy og 251 to the top of the stack
\       % Modulo. Implicitly display

```
> 3 votes

# Answer
# C#, ~~138~~ 134 bytes

```
(n,t,s)=>new int[n+1].Select((_,x)=>(s+new int[t-1].Select(k=>new Random(e).Next(251)).Select((c,i)=>c*Math.Pow(x+1,i+1)).Sum())%251);

```

C# lambda where inputs are `int` and output is an `IEnumerable<double>`. You can try my code on .NetFiddle.

I am not 100% sure about the validity of my algorithm, please comment if I misunderstood something.

4 bytes saved with @raggy's trick.
> 3 votes

# Answer
# Julia, 48 bytes

```
f(n,t,s)=(1:n).^(0:t-1)'*[s;rand(0:250,t-1)]%251

```

Try it online!
> 2 votes

# Answer
# , ~~32~~ 30 bytes

```
251|(1+i.@{.)p.~{:0}251?@#~1&{

```

Takes a list with the values *n*, *t*, and *s*.

Saved 2 bytes by using the *replace at index 0* idea from @Dennis's solution.

## Explanation

```
251|(1+i.@{.)p.~{:0}251?@#~1&{  Input: [n t s]
                           1&{  Select at index 1 (t)
                    251  #~     Create that many copies of 251
                       ?@       Generate that many random integers in [0, 251)
                {:              Get the tail of the input (s)
                  0}            Replace the value at index 0 of the random integer list
                                with s to make a coefficient list of the polynomial
          {.                    Get the head of the input (n)
       i.@                      Make the range [0, n-1]
     1+                         Add 1 to each to get [1, n]
             p.~                Evaluate the polynomial at each value [1, n]
251|                            Take each value mod 251 and return

```
> 2 votes

# Answer
## JavaScript (ES6), 116 bytes

```
(n,t,s)=>[...Array(n)].map((_,i)=>++i&&t.reduce((r,a)=>r*i+a)%251,t=[...Array(t)].map(_=>--t?Math.random()*251|0:s))

```

I'd like to think this is one of the rare cases where `reduce` beats `map`.
> 1 votes

# Answer
# Python 3 with NumPy, 103 bytes

```
from numpy import*
lambda n,t,s:[poly1d(append(random.randint(0,251,t-1),s))(i+1)%251for i in range(n)]

```

I can honestly say that I never expected to use NumPy for code golf...

An anonymous function that takes input via argument and returns a list.

**How it works**

```
from numpy import*         Import everything in the NumPy library
lambda n,t,s...            Function with input number of players n, threshold value t and
                           secret s
random.randint(0,251,t-1)  Generate a NumPy array R of t-1 random integers in [0,250]
append(...,s)              Append s to R
poly1d(...)                Generate a polynomial p of order t-1 with coefficients R and
                           constant term s
...for i in range(n)       For all integers i in [0,n-1]...
...(i+1)                   ...evaluate p(i+1), so for all integers in [1,n]...
...%251                    ...and take modulo 251
...:[...]                  return as list

```

Try it on Ideone
> 1 votes

# Answer
# Java 8, 224 bytes:

```
(n,t,s)->{int[]W=new int[t-1];for(int i=0;i<t-1;i++){W[i]=new java.util.Random().nextInt(251);};long[]O=new long[n];for(int i=1;i<=n;i++){long T=0;for(int h=1;h<t;h++){T+=W[h-1]*Math.pow(i,h);}O[i-1]=((T+s)%251);}return O;};

```

A Java 8 lambda expression. Outputs a comma separated integer array, and works perfectly until values in the output array reach beyond the range of the Java's `long`, or 64-bit signed integer, data type, upon which `-200` is output into the array.

Try It Online! (Ideone)
> 0 votes

# Answer
# Scala 3, 205 bytes

\\$ \text{205 bytes, It can be golfed much more.} \\$

---

Golfed version. Try it online!

```
(n,t,s)=>{val W=new Array[Int](t-1);for(i<-0 until t-1){W(i)=Random.nextInt(251)};val O=new Array[Long](n);for(i<-1 to n){var T=0L;for(h<-1 until t) {T=T+(W(h-1)*math.pow(i,h)).toLong};O(i-1)=(T+s)%251};O}

```

Ungolfed version. Try it online!

```
import scala.util.Random

object A {
  type G = (Int, Int, Int) => Array[Long]

  def main(args: Array[String]): Unit = {
    val J: G = (n, t, s) => {
      val W = new Array[Int](t - 1)
      for (i <- 0 until t - 1) {
        W(i) = Random.nextInt(251)
      }
      val O = new Array[Long](n)
      for (i <- 1 to n) {
        var T = 0L
        for (h <- 1 until t) {
          T = T+ (W(h - 1) * math.pow(i, h)).toLong
        }
        O(i - 1) = (T + s) % 251
      }
      O
    }

    val scanner = new java.util.Scanner(System.in)
    while (scanner.hasNextLine) {
      val n = scanner.nextInt()
      val t = scanner.nextInt()
      val s = scanner.nextInt()
      println(J(n, t, s).mkString("[", ", ", "]"))
    }
  }
}

```
> 0 votes

# Answer
# C (gcc), 133 bytes

-10 bytes thanks to @ceilingcat!

-1 byte thanks to @ceilingcat!

```
v[999];i,j,k,l;f(n,t,s){for(i=t;--i;)v[i]=rand()%251;for(*v=s;n/++i;printf("%d ",s%251))for(s=j=0;j<t;s+=k)for(k=v[l=j++];l--;)k*=i;}

```

Try it online!
> 0 votes

---
Tags: code-golf, number-theory, random, cryptography, polynomials
---


title: Calculate Standard Deviation

text:
# Question
Title: Calculate Standard Deviation
## Challenge

Given a list of numbers, calculate the population standard deviation of the list.

Use the following equation to calculate population standard deviation:

## Input

The input will a list of integers in any format (list, string, etc.). Some examples:

```
56,54,89,87
67,54,86,67

```

The numbers will always be integers.

Input will be to STDIN or function arguments.

## Output

The output must be a floating point number.

## Rules

You may use built in functions to find the standard deviation.

Your answer can be either a full program or a function.

## Examples

```
10035, 436844, 42463, 44774 => 175656.78441352615

45,67,32,98,11,3 => 32.530327730015607

1,1,1,1,1,1 => 0.0

```

## Winning

The shortest program or function wins.

## Leaderboard

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

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
# Clip, 3

```
.sk

```

`.s` is the standard deviation, `k` parses the input in the form `{1,2,3}`.
> 18 votes

# Answer
# Mathematica, ~~24~~ 22 bytes

Nice, Mathematica has a built-in `StandardDevi...` oh... that computes the sample standard deviation, not the population standard deviation.

But what if we use `Variance`... oh... same deal.

But there is yet another related built-in:

```
CentralMoment[#,2]^.5&

```

Yay. :)

This also works for 22 bytes:

```
Mean[(#-Mean@#)^2]^.5&

```

And this for 27:

```
N@RootMeanSquare[#-Mean@#]&

```
> 12 votes

# Answer
# Octave, 14 bytes

```
g=@(a)std(a,1)

```

Try it on ideone.
> 10 votes

# Answer
# kdb+, 3 bytes

```
dev

```

One of the APL derviates *had to* have this as a built-in.

### Test run

```
q)dev 56, 54, 89, 87
16.53028
q)f:dev
q)f 10035, 436844, 42463, 44774
175656.8
q)f 45,67,32,98,11,3
32.53033

```
> 10 votes

# Answer
# Dyalog APL, ~~24~~ ~~23~~ ~~21~~ ~~20~~ ~~19~~ 17 bytes

```
*∘.5∘M×⍨-M×M←+/÷≢

```

This defines an unnamed, monadic function train, which is equivalent to the following function.

```
{.5*⍨M(×⍨⍵)-M⍵×(M←{(+/⍵)÷≢⍵})⍵}

```

Try them online on TryAPL.

### How it works

The code consists of several trains.

```
M←+/÷≢

```

This defines a monadic 3-train (fork) `M` that executes `+/` (sum of all elements) and  (length) for the right argument, then applies `÷` (division) to the results, returning the arithmetic mean of the input.

```
M×M

```

This is another fork that applies `M` to the right argument, repeats this a second time, and applies `×` (product) to the results, returning **μ2**.

```
×⍨-(M×M)

```

This is yet another fork that calculates the square of the arithmetic mean as explained before, applies `×⍨` (product with itself) to the right argument, and finally applies `-` (difference) to the results.

For input **(x1, …, xN)**, this function returns **(x1 \- μ2, …, xN \- μ2)**.

```
*∘.5∘M

```

This composed function is applies `M` to its right argument, then `*∘.5`. The latter uses right argument currying to apply map input `a` to `a*0.5` (square root of `a`).

```
(*∘.5∘M)(×⍨-(M×M))

```

Finally, we have this monadic 2-train (atop), which applies the right function first, then the left to its result, calculating the standard deviation as follows.
> 8 votes

# Answer
# R, ~~41~~ ~~40~~ ~~39~~ ~~36~~ ~~30~~ 28 bytes

### code

Thanks to beaker, Alex A. and MickyT for much bytes.

```
cat(sd(c(v=scan(),mean(v))))

```

### old codes

```
v=scan();n=length(v);sd(v)/(n/(n-1))**0.5
m=scan();cat(sqrt(sum(mean((m-mean(m))^2))))
m=scan();cat(mean((m-mean(m))^2)^.5)

```

This should yield the population standard deviation.
> 6 votes

# Answer
# CJam, ~~24~~ ~~22~~ 21 bytes

```
q~_,_@_:+d@/f-:mh\mq/

```

*Thanks to @aditsu for golfing off 1 byte!*

Try it online in the CJam interpreter.

### How it works

```
q~                    e# Read all input and evaluate it.
  _,                  e# Copy the array and push its length.
    _@                e# Copy the length and rotate the array on top.
      _:+d            e# Copy the array and compute its sum. Cast to Double.
          @/          e# Rotate the length on top and divide the sum by it.
            f-        e# Subtract the result (μ) from the array's elements.
              :mh     e# Reduce by hypotenuse.
                      e# a b mh -> sqrt(a^2 + b^2)
                      e# sqrt(a^2 + b^2) c mh -> sqrt(sqrt(a^2 + b^2)^2 + c^2)
                      e#                           = sqrt(a^2 + b^2 + c^2)
                      e# ⋮
                 \mq/ e# Divide the result by the square root of the length.

```
> 5 votes

# Answer
# Pyth, ~~20~~ ~~19~~ ~~17~~ 13 bytes

```
@.O^R2-R.OQQ2

```

*Thanks to @FryAmTheEggman for golfing off 4 bytes!*

Try it online.

### How it works

```
        .OQ    Compute the arithmetic mean of the input (Q).
      -R   Q   Subtract the arithmetic mean of all elements of Q.
   ^R2         Square each resulting difference.
 .O            Compute the arithmetic mean of the squared differences.
@           2  Apply square root.

```
> 5 votes

# Answer
# Julia, ~~26~~ 19 bytes

```
x->std([x;mean(x)])

```

This creates an unnamed function that accepts an array and returns a float.

Ungolfed, I guess:

```
function f(x::Array{Int,1})
    # Return the sample standard deviation (denominator N-1) of
    # the input with the mean of the input appended to the end.
    # This corrects the denominator to N without affecting the
    # mean.
    std([x; mean(x)])
end

```
> 5 votes

# Answer
# TI-BASIC, 7 bytes

```
stdDev(augment(Ans,{mean(Ans

```

I borrowed the algorithm to get population standard deviation from sample standard deviation from here.

The shortest solution I could find without `augment(` is 9 bytes:

```
stdDev(Ans√(1-1/dim(Ans

```
> 4 votes

# Answer
# APL, 24 bytes

```
{.5*⍨+/(2*⍨⍵-+/⍵÷≢⍵)÷≢⍵}

```

A little different approach than Dennis' Dyalog APL solution. This should work with any APL implementation.

This creates an unnamed monadic function that computes the vector (*x* \- *µ*)2 as `2*⍨⍵-+/⍵÷≢⍵`, divides this by *N* (`÷≢⍵`), takes the sum of this vector using `+/`, and then takes the square root (`.5*⍨`).

Try it online
> 4 votes

# Answer
# Python 3.4+, 30 bytes

```
from statistics import*;pstdev

```

Imports the builtin function `pstdev`, e.g.

```
>>> pstdev([56,54,89,87])
16.53027525481654

```
> 3 votes

# Answer
# Haskell, 61 bytes

```
d n=1/sum(n>>[1])
f a=sqrt$d a*sum(map((^2).(-)(d a*sum a))a)

```

Straightforward, except maybe my custom length function `sum(n>>[1])` to trick Haskell's strict type system.
> 3 votes

# Answer
# Jelly

**11 bytes**

```
S÷L
Ç²_²ÇN½

```

This is a direct translation of my APL answer to Jelly. Try it online!

### How it works

```
S÷L        Helper link. Argument: z (vector)

S          Compute the sum of z.
  L        Compute the length of z.
 ÷         Divide the former by the latter.
           This computes the mean of z.

Ç²_²ÇN½    Main link. Argument: z (vector)

Ç          Apply the previous link, i.e., compute the mean of z.
 ²         Square the mean.
   ²       Square all number in z.
  _        Subtract each squared number from the squared mean.
    Ç      Take the mean of the resulting vector.
     N     Multiply it by -1.
      ½    Take the square root of the result.

```
> 3 votes

# Answer
# J, 18 bytes

```
[:%:@M*:-M*M=:+/%#

```

This is a direct translation of my APL answer to J.

Try it online!
> 2 votes

# Answer
# Prolog (SWI), 119 bytes

**Code:**

```
q(U,X,A):-A is(X-U)^2.
p(L):-sumlist(L,S),length(L,I),U is S/I,maplist(q(U),L,A),sumlist(A,B),C is sqrt(B/I),write(C).

```

**Explanation:**

```
q(U,X,A):-A is(X-U)^2.   % calc squared difference of X and U
p(L):-sumlist(L,S),      % sum input list
      length(L,I),       % length of input list
      U is S/I,          % set U to the mean value of input list
      maplist(q(U),L,A), % set A to the list of squared differences of input and mean
      sumlist(A,B),      % sum squared differences list
      C is sqrt(B/I),    % divide sum of squares by length of list
      write(C).          % print answer

```

**Example:**

```
p([10035, 436844, 42463, 44774]).
175656.78441352615

```

Try it out online here
> 2 votes

# Answer
# Haskell, 45 bytes

```
(?)i=sum.map(^i)
f l=sqrt$2?l/0?l-(1?l/0?l)^2

```

Try it online!

The value `i?l` is the sum of the i'th powers of elements in `l`, so that `0?l` is the length and `1?l` is the sum.
> 2 votes

# Answer
# 05AB1E, ~~10~~ 7 bytes

```
ÅA-nÅAt

```

-3 bytes thanks to *@ovs*.

Try it online or verify all test cases.

**Explanation:**

```
ÅA       # Get the arithmetic mean of the (implicit) input-list
  -      # Subtract it from each value in the (implicit) input-list
   n     # Square each of those
    ÅA   # Take the arithmetic mean of that
      t  # And take the square-root of that
         # (after which it is output implicitly as result)

```
> 2 votes

# Answer
# Arn, ~~19~~ ~~18~~ 14 bytes

```
¯‡iʠØbmÅQƥªÈªÆ

```

Try it!

# Explained

Unpacked: `:/mean(n{:*n-mean:s}\`

```
:/                      Square root
  mean                  Mean function
    (                   Begin expression
        n{              Block with key of n
          :*            Square
              n
            -           Subtraction
              mean
                    _   Variable initialized to STDIN; implied
                  :s    Split on spaces
         }              End of block
       \                Mapped over
         _              Implied
    )                   End of expression; Implied

```
> 2 votes

# Answer
# Brachylog, 16 bytes

```
⟨∋-⟨+/l⟩⟩ᶠ^₂ᵐ↰₂√

```

Try it online! (all cases at once)

I feel like *maybe* there's some shorter way to compute the squared deviations than 13 bytes.
> 2 votes

# Answer
# JavaScript (ES6), 73 bytes

```
a=>Math.sqrt(a.reduce((b,c)=>b+(d=c-eval(a.join`+`)/(l=a.length))*d,0)/l)

```
> 1 votes

# Answer
# Simplex v.0.5, 43 bytes

Just 'cuz. I really need to golf this one more byte.

```
t[@u@RvR]lR1RD@wA@T@{j@@SR2ERpR}u@vR@TR1UEo
t[      ]                                     ~~ Applies inner function to entire strip (left-to-right)
  @                                           ~~ Copies current value to register
   u                                          ~~ Goes up a strip level
    @                                         ~~ Dumps the register on the current byte
     R                                        ~~ Proceeds right (s1)
      v                                       ~~ Goes back down
       R                                      ~~ Proceeds right (s0)
                                              ~~ Go right until an empty byte is found
         lR1RD                                ~~ Push length, 1, and divide.
              @                               ~~ Store result in register (1/N)
               wA                             ~~ Applies A (add) to each byte, (right-to-left)
                 @T@                          ~~ Puts 1/N down, multiplies it, and copies it to the register
                    {          }              ~~ Repeats until a zero-byte is met
                     j@@                      ~~ inserts a new byte and places register on it
                        SR                    ~~ Subtract it from the current byte and moves right
                          2E                  ~~ Squares result
                            RpR               ~~ Moves to the recently-created cell, deletes it, and continues
                                u@v           ~~ takes 1/N again into register
                                   R@T        ~~ multiplies it by the new sum
                                      R1UE    ~~ takes the square root of previous
                                          o   ~~ output as number

```
> 1 votes

# Answer
# Perl5, ~~39~~ 38

---

16 for the script
+22 for the `M` switch
\+ 1 for the `E` switch
=39

```
perl -MStatistics::Lite=:all -E"say stddevp@ARGV" .1 .2 300

```

Tested in Strawberry 5.20.2.

---

Oh, but then I realized that you said our answers can be functions instead of programs. In that case,

```
{use Statistics::Lite":all";stddevp@_}

```

has just 38. Tested in Strawberry 5.20.2 as

```
print sub{use Statistics::Lite":all";stddevp@_}->( .1, .2, 300)

```
> 1 votes

# Answer
# MathGolf, ~~10~~ 7 bytes

```
ë_▓-²▓√

```

Port of my 05AB1E answer.

Try it online.

**Explanation:**

```
ë        # Read all inputs as float-list
 _       # Duplicate that list
  ▓      # Get the average of that list
   -     # Subtract that average from each value in the list
    ²    # Square each value
     ▓   # Take the average of that again
      √  # And take the square root of that
         # (after which the entire stack joined together is output implicitly as result)

```
> 1 votes

# Answer
# Whispers v2, 105 bytes

```
> Input
>> #1
>> ∑1
>> 3÷2
>> L-4
>> L²
>> Each 5 1
>> Each 6 7
>> ∑8
>> 9÷2
>> √10
>> Output 11

```

Try it online!

In the latest version of Whispers, the builtin `σ` can be used to shave off around 70 bytes.

## How it works

For those unfamiliar with Whispers, the language works by using numbers as line references in order to pass values between lines. For example, the line `>> 3÷2` doesn't calculate \\$3 \div 2\\$, rather it takes the values of lines **3** and **2** and calculates their division. Execution always begins on the last line.

This program simply implements the standard formula for standard deviation:

$$\sigma = \sqrt{\frac{1}{N}\sum^N\_{i=1}{(x\_i-\bar{x})^2}}$$ $$\bar{x} = \frac{1}{N}\sum^N\_{i=1}{x\_i}$$

Lines **2**, **3** and **4** define \\$\bar{x}\\$, with it's specific value accessible on line **4**. Line **2** stores \\$N\\$. We then calculate \\$(x\_i-\bar{x})^2\\$ for each \\$x\_i \in x\\$ with the lines **5**, **6**, **7** and **8**:

```
>> L-4
>> L²
>> Each 5 1
>> Each 6 7

```

Line **7** runs line **5** over each element in the input, which takes the difference between each element in the input and the mean, We then square these differences using lines **8** and **6**. Finally, we take the sum of these squares (line **9**), divide by \\$N\\$ (line **10**) and take the square root (line **11**). Finally, we output this result.
> 1 votes

# Answer
# Shasta v0.0.10, 65 bytes

```
{(**(/(sum(map${|x|(**(- x(/(sum$)(length$)))2)}))(length$)).5)}

```

Online interpreter not set up yet, tested on my machine

Explanation:

`{...}` Function taking argument $

`(** ... .5)` Square root of

`(/ ... (length $))` Dividing ... by the length of $

`(sum ...)` The sum of

`(map $ {|x| ...})` Mapping each x in $ to

`(** ... 2)` The square of

`(- x ...)` The difference between x and

`(/ (sum $) (length $))` The mean of $
> 1 votes

# Answer
# Python, 57 bytes

```
lambda l:(sum((x-sum(l)/len(l))**2for x in l)/len(l))**.5

```

Takes input as a list

Thanks @xnor
> 0 votes

# Answer
### PowerShell, 122

```
:\>type stddev.ps1
$y=0;$z=$args -split",";$a=($z|?{$_});$c=$a.Count;$a|%{$y+=$_};$b=$y/$c;$a|%{$x+
=(($_-$b)*($_-$b))/$c};[math]::pow($x,0.5)

```

explanation

```
<#
$y=0                            init
$z=$args -split","              split delim ,
$a=($z|? {$_})                  remove empty items
$c=$a.Count                     count items
$a|%{$y+=$_}                    sum
$b=$y/$c                        average
$a|%{$x+=(($_-$b)*($_-$b))/$c}  sum of squares/count
[math]::pow($x,0.5)             result
#>

```

result

```
:\>powershell -nologo -f stddev.ps1 45,67,32,98,11,3
32.5303277300156

:\>powershell -nologo -f stddev.ps1 45,  67,32,98,11,3
32.5303277300156

:\>powershell -nologo -f stddev.ps1 45,  67,32, 98 ,11,3
32.5303277300156

:\>powershell -nologo -f stddev.ps1 10035, 436844, 42463, 44774
175656.784413526

:\>powershell -nologo -f stddev.ps1 1,1,1,1,1,1
0

```
> 0 votes

# Answer
# Fortran, 138 bytes

Just a straightforward implementation of the equation in Fortran:

```
double precision function std(x)
integer,dimension(:),intent(in) :: x
std = norm2(dble(x-sum(x)/size(x)))/sqrt(dble(size(x)))
end function

```
> 0 votes

# Answer
# SmileBASIC, 105 bytes (as a function)

I just noticed it's allowed to be a function. Whoops, that reduces my answer dramatically. This defines a function `S` which takes an array and returns the population standard deviation. Go read the other one for an explanation, but skip the parsing part. I don't want to do it again.

```
DEF S(L)N=LEN(L)FOR I=0TO N-1U=U+L[I]NEXT
U=1/N*U FOR I=0TO N-1T=T+POW(L[I]-U,2)NEXT RETURN SQR(1/N*T)END

```

## As a program, 212 bytes

Unfortunately, I have to take the input list as a string and parse it myself. This adds over 100 bytes to the answer, so if some input format other than a comma-separated list is allowed I'd be glad to hear it. Also note that because `VAL` is buggy, having a space *before* the comma or trailing the string breaks the program. After the comma or at the start of the string is fine.

```
DIM L[0]LINPUT L$@L I=INSTR(O,L$,",")IF I>-1THEN PUSH L,VAL(MID$(L$,O,I-O))O=I+1GOTO@L ELSE PUSH L,VAL(MID$(L$,O,LEN(L$)-O))
N=LEN(L)FOR I=0TO N-1U=U+L[I]NEXT
U=1/N*U FOR I=0TO N-1T=T+POW(L[I]-U,2)NEXT?SQR(1/N*T)

```

Ungolfed and explained:

```
DIM L[0]  'define our array
LINPUT L$ 'grab string from input

'parse list
'could've used something cleaner, like a REPEAT, but this was shorter
@L
I=INSTR(O,L$,",")                 'find next comma
IF I>-1 THEN                      'we have a comma
 PUSH L,VAL(MID$(L$,O,I-O))       'get substring of number, parse & store
 O=I+1                            'set next search location
 GOTO @L                          'go again
ELSE                              'we don't have a comma
 PUSH L,VAL(MID$(L$,O,LEN(L$)-O)) 'eat rest of string, parse & store
ENDIF                             'end

N=LEN(L) 'how many numbers we have

'find U
'sum all of the numbers, mult by 1/N
FOR I=0 TO N-1
 U=U+L[I]
NEXT
U=1/N*U

'calculate our popstdev
'sum(pow(x-u,2))
FOR I=0 TO N-1
 T=T+POW(L[I]-U,2)
NEXT
PRINT SQR(1/N*T) 'sqrt(1/n*sum)

```
> 0 votes

# Answer
# Axiom, 137 bytes

```
m(a:List Float):Complex Float==(#a=0=>%i;reduce(+,a)/#a)
s(a:List Float):Complex Float==(#a=0=>%i;n:=m(a);sqrt(m([(x-n)^2 for x in a])))

```

The function m() would return the mean of the list in input. Both the functions on error return %i the imaginary constant sqrt(-1). Code for test and results. \[but the result if it is ok, it is the real part of one complex number\]

```
(6) -> s([45,67,32,98,11,3])
   (6)  32.5303277300 15604966

(7) -> s([10035,436844,42463,44774])
   (7)  175656.7844135261 4035

(8) -> s([1,1,1,1,1,1])
   (8)  0.0

```
> 0 votes

# Answer
# Python 3, 49 bytes

```
lambda l,N:(sum((i-sum(l)/N)**2for i in l)/N)**.5

```

Try it online!

Takes in `l`, a list of integers, and `N`, the number of integers present.
> 0 votes

# Answer
# Pyt, 13 bytes

```
←Đ↔Ł↔Đµ-²Ʃ⇹/√

```

Implements the formula for standard deviation
> 0 votes

# Answer
# Scala, 80 bytes

Golfed version. Try it online!

```
l=>{val s=(0 to 2).map(i=>l.map(pow(_,i)).sum);sqrt(s(2)/s(0)-pow(s(1)/s(0),2))}

```

Ungolfed version. Try it online!

```
object Main {

  def powerSum(i: Int, list: List[Int]): Double =
    list.map(scala.math.pow(_, i)).sum

  def f(l: List[Int]): Double = {
    val sum0 = powerSum(0, l)
    val sum1 = powerSum(1, l)
    val sum2 = powerSum(2, l)

    scala.math.sqrt(sum2 / sum0 - scala.math.pow(sum1 / sum0, 2))
  }

  def main(args: Array[String]): Unit = {
    println(f(List(45, 67, 32, 98, 11, 3)))
  }

}

```
> 0 votes

---
Tags: code-golf, math, arithmetic, statistics
---


title: Laguerre Polynomials

text:
# Question
Title: Laguerre Polynomials
Laguerre polynomials are nontrivial solutions to Laguerre's equation, a second-order linear differential equation: \\$xy''+(1-x)y'+ny=0\\$. For a given value of \\$n\\$, the solution, \\$y\\$, is named \\$L\_n(x)\\$. To avoid trivial solutions, the polynomials are non-constant except for \\$n=0\\$.

The polynomials can be found without calculus using recursion:

\\$L\_0(x)=1\\$

\\$L\_1(x)=1-x\\$

\\$L\_{k+1}(x)=\frac{(2k+1-x)L\_k(x)-kL\_{k-1}(x)}{k+1}\\$

Summation can be used to the same end:

\\$L\_n(x)=\sum\limits\_{k=0}^{n}{n\choose k}\frac{(-1)^k}{k!}x^k\\$

\\$L\_n(x)=\sum\limits\_{i=0}^n\prod\limits\_{k=1}^i\frac{-(n-k+1)x}{k^2}\\$

The first Laguerre polynomials are as follows:

Coefficients can be found here.

# The Challenge

Given a nonnegative integer \\$n\\$ and a real number \\$x\\$, find \\$L\_n(x)\\$.

# Rules

* This is so the shortest answer in bytes wins.
* Assume only valid input will be given.
* Error should be under one ten-thousandth (±0.0001) for the test cases.

# Test Cases

Here, \\$n\\$ is the first number and \\$x\\$ is the second.

```
In: 1 2
Out: -1

In: 3 1.416
Out: -0.71360922

In: 4 8.6
Out: −7.63726667

In: 6 -2.1
Out: 91.86123261

```

# Answer
# MATL, 5 bytes

```
_1iZh

```

Inputs are \\$n\\$, then \\$x\\$. Try it online! Or verify all test cases.

### How it works

This uses the equivalence of Laguerre polynomials and the (confluent) hypergeometric function:

\\$ L\_n(x) = {} \_1F\_1(-n,1,x) \\$

```
_    % Implicit input: n. Negate
1    % Push 1
i    % Input: x
Zh   % Hypergeometric function. Implicit output

```
> 6 votes

# Answer
# Python 2, 53 bytes

```
f=lambda n,x:n<1or((2*n-1-x)*f(n-1,x)-~-n*f(n-2,x))/n

```

Try it online!
> 12 votes

# Answer
# Wolfram Language (Mathematica), 9 bytes

```
LaguerreL

```

Try it online!
> 11 votes

# Answer
# Jelly,  ~~11~~  10 bytes

```
ŻṚṀc÷!ƲḅN}

```

A dyadic Link accepting \\$n\\$ on the left and \\$x\\$ on the right which yields \\$L\_n(x)\\$.

**Try it online!**

### How?

This makes the observation that
\\$L\_n(x)=\sum\limits\_{k=0}^{n}{n\choose k}\frac{(-1)^k}{k!}x^k=\sum\limits\_{k=0}^{n}{(-x)^k}\frac{n\choose k}{k!}\\$
which is the evaluation of a base \\$-x\\$ number with n+1 digits of the form \\$\frac{n\choose k}{k!}\\$.

```
ŻṚṀc÷!ƲḅN} - Link: n, x
Ż          - zero-range (n) -> [0, 1, 2, ..., n]
 Ṛ         - reverse -> [n, ..., 2, 1, 0]
      Ʋ    - last four links as a monad - f(I=that):
  Ṁ        -   maximum -> n
   c       -   {that} binomial (I) -> [nCn, ..., nC2, nC1, nC0]
     !     -   {I} factorial -> [n!, ..., 2!, 1!, 0!]
    ÷      -   division -> [nCn÷n!, ..., nC2÷2!, nC0÷0!]
        N} - negate right argument -> -x
       ḅ   - convert from base (-x) -> -xⁿnCn÷n!+...+-x²nC2÷2!+-x¹nC1÷1!+-x°nC0÷0!

```
> 8 votes

# Answer
# JavaScript (ES6),  ~~48 42~~  41 bytes

Expects `(x)(n)`. May output **true** instead of **1**.

```
x=>g=k=>k<1||((x-k---k)*g(k)+k*g(k-1))/~k

```

Try it online!
> 5 votes

# Answer
# Python 3.8 (pre-release), 66 bytes

```
L=lambda n,x:((2*n-1-x)*L(d:=n-1,x)-d*L(n-2,x))/n if n>1else 1-n*x

```

Try it online!

Direct implementation of the recursive algorithm, with one interesting part: `L(1,x)` and `L(0,x)` can be combined as `L(n,x)=1-n*x`.

Could save 2 bytes using `L=lambda n,x:n>1and((2*n-1-x)*L(d:=n-1,x)-d*L(n-2,x))/n or 1-n*x`, but `L(n)` is not necessarily zero.
> 4 votes

# Answer
# APL (Dyalog Unicode), 16 bytes

```
1⊥⍨0,⎕×(-÷⌽×⌽)⍳⎕

```

Try it online!

A full program that takes `n` and `x` from two separate lines of stdin.

### How it works

```
1⊥⍨0,⎕×(-÷⌽×⌽)⍳⎕
              ⍳⎕  ⍝ Take n and generate 1..n
       (-÷⌽×⌽)    ⍝ Compute i÷(n+1-i)^2 for i←1..n
   0,⎕×           ⍝ Multiply x to each and prepend 0, call it B
1⊥⍨               ⍝ Convert all ones from base B to single number

```

The mixed base conversion looks like this:

```
1..n:                ... n-3          n-2          n-1          1
B:            0      ... (n-3)x/4^2   (n-2)x/3^2   (n-1)x/2^2   nx
digits:       1      ... 1            1            1            1
digit values: x^n/n! ... (nC3 x^3/3!) (nC2 x^2/2!) (nC1 x^1/1!) (nC0 x^0/0!)

```

It is essentially a fancy way to write the sum of product scan over `1, nx, (n-1)x/2^2, (n-2)x/3^2, ...`. This happens to be shorter than a more straightforward `-x`-base conversion (evaluating a polynomial at `-x`):

# APL (Dyalog Unicode), 18 bytes

```
(-⎕)⊥⌽1,(!÷⍨⊢!≢)⍳⎕

```

Try it online!
> 4 votes

# Answer
# Python 3.8 (pre-release), 61 bytes

```
L=lambda k,x:k<1or[1-x,L(w:=k-1,x)*(k+w-x)-L(k-2,x)*w][k>1]/k

```

Try it online!
> 3 votes

# Answer
# JavaScript (Node.js), 36 bytes

```
x=>(i=0,g=n=>n?1-x*n/++i/i*g(n-1):1)

```

Try it online!

Just convert the formula to this, and use recursive:

$$ L\_n(x) = \sum\_{i=0}^n\prod\_{k=1}^i\frac{-(n-k+1)x}{k^2} $$
> 3 votes

# Answer
# , 37 20 bytes

*-5 thanks to @Bubbler*

Calculates the polynomial adapted from the summation formula and uses J's `p.` operator to calculate that polynomial with a given x.

```
(p.-)~i.((!]/)%!)@,]

```

Try it online!

# , 45 byte

Alternative Recursive function.

```
1:`-@.[~ ::((>:@]%~($:*[-~1+2*])-]*($:<:))<:)

```

Try it online!

### How it works

We define a hook `(fg)`, which is `x f (g n)`. `f` is `(p.-)~` so it will be evaluated as `((i.((!]/)%!)@,]) n) p. (- x)`.

```
(p.-)~i.((!]/)%!)@,]
      i.         @,] enumerate 3 -> 0 1 2, append 3 -> 0 1 2 3, …
         (!]/)       3 over i
              %      divided by
               !     !i
   -                 negate x
 p.                  apply -x to the polynomial expressed in J as
                     1 3 1.5 0.166667, so 1-3(-x)+1.5(-x)^2+0.16(-x)^3

```
> 2 votes

# Answer
# Pari/GP, 39 bytes

Using the formula \\$L\_n(x)=\sum\_{k=0}^n \binom{n}{k}\frac{(-1)^k}{k!} x^k\\$.

```
l(n,x)=sum(k=0,n,n!*(-x)^k/(n-k)!/k!^2)

```

Try it online!

---

# Pari/GP, 45 bytes

Using the generating function \\$\sum\_{n=0}^\infty x^n L\_n(t)= \frac{1}{1-x} e^{-xt/(1-x)}\\$.

```
l(n,t)=Vec(exp(-x*t/(1-x)+O(x^n++))/(1-x))[n]

```

Try it online!
> 2 votes

# Answer
# Charcoal, 29 bytes

```
⊞υ¹ＦＮ⊞υ×⌈υＬυＩ↨Ｅυ∕⌈υ×ιＸ§⮌υκ²±Ｎ

```

Try it online! Link is to verbose version of code. Uses a slightly modified version of the summation given in the question. Explanation:

```
⊞υ¹ＦＮ⊞υ×⌈υＬυ

```

Calculate the factorials from \\$0!\\$ to \\$n!\\$.

```
Ｉ↨Ｅυ∕⌈υ×ιＸ§⮌υκ²±Ｎ

```

For each index \\$i\\$ from \\$0\\$ to \\$n\\$ calculate \\$\frac{n!}{i!(n-i)!^2}\\$ and then perform base conversion from base \\$-x\\$ which multiplies each term by \\$(-1)^{n-i}x^{n-i}\\$ and takes the sum.

If we set \\$k=n-i\\$ we see that we calculate \\$\sum\limits\_{k=0}^{n}{\frac{n!(-1)^k}{(n-k)!k!^2}x^k}=\sum\limits\_{k=0}^{n}{n\choose k}\frac{(-1)^k}{k!}x^k\\$ as required.
> 1 votes

# Answer
# 05AB1E, ~~16~~ 11 bytes

```
DÝR©c®!/I(β

```

Port of *@JonathanAllan*'s Jelly answer, so make sure to upvote him as well!

Try it online or verify all test cases.

**Original 16 bytes answer:**

```
1λèN·<I-₁*N<₂*-N/

```

Try it online or verify all test cases.

**Explanation:**

```
D                 # Duplicate the first (implicit) input-integer `n`
 Ý                # Pop one, and push a list in the range [0,n]
  R               # Reverse it to range [n,0]
   ©              # Store this list in variable `®` (without popping)
    c             # Get the binomial coefficient of `n` and each value in this list
     ®!           # Push list `®` again, and get the factorial of each
       /          # Divide the values at the same positions of the two lists
        I(        # Push the second input `x`, and negate it
          β       # Convert the list from base-(-x) to a single decimal value
                  # (which is output implicitly as result)

```

---

Uses the recursive formula:

$$a(n)=\frac{a(n-1)\times(2n-1-x)-(n-1)\times a(n-2)}{n}$$

```
 λ                # Create a recursive environment
  è               # to get the 0-based n'th value afterwards
                  # (where `n` is the first implicit input)
                  # (which will be output implicitly as result at the end)
1                 # Starting with a(-1)=0 and a(0)=1,
                  # and for every other a(N), we'll:
                  #  (implicitly push a(N-1))
   N·             #  Push `N` doubled
     <            #  Decrease it by 1
      I-          #  Decrease it by the second input `x`
        *         #  Multiply it by the implicit a(N-1)
         N<       #  Push `N`-1
           ₂*     #  Multiply it by a(N-2)
             -    #  Decrease the a(N-1)*(2N-1-x) by this (N-1)*a(N-2)
              N/  #  And divide it by `N`: (a(N-1)*(2N-1-x)-(N-1)*a(N-2))/N

```
> 1 votes

# Answer
# Japt `-x`, ~~28~~ ~~27~~ 26 bytes

```
ò@l *VpX /Xl ²*JpX /(U-X l

```

Try it

# Japt, ~~30~~ ~~29~~ 28 bytes

```
ò x@l *VpX /Xl ²*JpX /(U-X l

```

Try it

## Explanation

```
ò x@l *VpX /Xl ²*JpX /(U-X l
ò                               // Create a array [0, 1, ..., U]
  x                             // sum the array after mapping through
   @                            // Function(X)
    l                           //    U!
      *VpX                      //    times V ** X
           /Xl ²                //    divided by X! ** 2
                *JpX            //    times (-1) ** X
                     /(U-X l    //    divided by (U - X)!

```
* `U` is the first input
* `V` is the second input
* `**` represents exponentiation
* `!` represents factorial
> 1 votes

# Answer
## Fortran (GFortran), ~~69~~ 68 bytes

```
read*,n,a
print*,sum([(product([((j-n-1)*a/j/j,j=1,i)]),i=0,n)])
end

```

*-1 byte thanks to @ceilingcat*

The program reads in an implicit integer n and real a. Summation and product operations are performed using arrays (initialized using implicit loops) with the intrinsics sum() and product().

Try it online!
> 1 votes

# Answer
# C (gcc), 91 bytes

```
i;k;float f(n,x)float x;{float p,s=0;for(i=++n;k=i--;s+=p)for(p=1;--k;)p*=(k-n)*x/k/k;x=s;}

```

Try it online!

Straighforward implementation of polynomial expansion. Slightly golfed less

```
i;k;
float f(n,x)float x;{
  float p,s=0;
  for(i=++n;k=i--;s+=p)
    for(p=1;--k;)
      p*=(k-n)*x/k/k;
  x=s;
}

```
> 1 votes

# Answer
# Scala, 81 bytes

Use the recursive formula of Laguerre Polynomials.

---

Golfed version. Try it online!

```
def f(n:Int,x:Double):Double={if(n<1)1 else((2*n-1-x)*f(n-1,x)-(n-1)*f(n-2,x))/n}

```

Ungolfed version. Try it online!

```
object Main {
  def f(n: Int, x: Double): Double = {
    if(n < 1) 1
    else ((2*n - 1 - x) * f(n - 1, x) - (n - 1) * f(n - 2, x)) / n
  }

  def main(args: Array[String]): Unit = {
    println(f(1, 2.0))
    println(f(3, 1.416))
    println(f(4, 8.6))
    println(f(6, -2.1))
  }
}

```
> 0 votes

# Answer
# HTML, 1 Byte, Invalidated by newest edit.

```
0
```

\\$y=0\\$ is a solution to the equation stated in the question for all \\$x\\$ and \\$n\\$.
> 0 votes

# Answer
# Jelly, 0 Bytes, invalidated by newest edit

Try it online! Note that \\$y=0\\$ is a solution for all \\$x\\$ and \\$n\\$. Port of my HTML answer.

Thanks to Jonathan Allen for pointing out this port, and also that this might be a polyglot.
> 0 votes

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


# Question
Title: Keep elements in sequence that have a letter repeated at least 3 times
## Challenge:

Given the input array `l` with a list of strings, only keep the elements in the sequence that have a letter that's repeated at least 3 times. Like `'lessons'` has 3 `s` letters, so it should be kept in the sequence. But, `'lesson'` has only two `s` letters, so it should be removed.

## Notes:

* `l` will always be a sequence, and its elements will always be strings with only alphabetical characters.
* I am using the example output with Python Lists. You can use any type of sequence in your own language.

## Test cases:

```
['element', 'photoshop', 'good'] -> ['element', 'photoshop']
['happy', 'colorful', 'luggage'] -> ['luggage']
['reference', 'tomorrow', 'today'] -> ['reference', 'tomorrow']

```

This is , so the shortest code in bytes wins!

# Answer
> 10 votes
# Python 3, ~~51~~ 50 bytes

```
lambda l:{s for s in l for c in s if s.count(c)>2}

```

Try it online!

# Answer
> 6 votes
# QuadS, 13 bytes

Takes linebreak-separated text

```
(.).*\1.*\1
%

```

Try it online!

Search for…

`(.)` any character (1)
`.*` zero or more characters
`\1` character (1)
`.*` zero or more characters

and for each match, return:

`%` the entire line the match occurred on

# Answer
> 6 votes
# Japt `-f`, ~~7~~ 4 bytes

```
ü d¤

```

Try it

```
ü d¤     :Implicit filter of input array
ü        :Group & sort
  d      :Any truthy (a non-empty string)
   ¤     :  Slice off the first 2 characters

```

## Without flag, 6 bytes

```
fÈü d¤

```

Try it

# Answer
> 6 votes
# Nibbles, ~~6.5~~ 5.5 bytes (11 nibbles)

*Edit: -2 bytes by using transpose, inspired by Jonathan Allan's Jelly answer*

```
|$>2`'=~$$

```

```
|$              # filter each word int the input by
      =~$       #   group the letters by
         $      #     themselves,
    `'          #   transpose this list of lists,
  >2            #   and remove the first 2 elements
                #   (so if there is at least one letter
                #   present >2 times, the resulting
                #   list will have nonzero length)

```

# Answer
> 6 votes
# Python 3, 55 bytes

```
lambda a:filter(lambda x:any(x.count(i)>2for i in x),a)

```

Returns a filter object. The asterisk is used in the output to unpack the filter object automatically.

Try it online!

# Python 2, 55 bytes

```
lambda a:filter(lambda x:any(x.count(i)>2for i in x),a)

```

Exactly the same code, just returns a normal Python list instead of a filter object, meaning you don't need to use the asterisk in the output (if that matters).

Try it online!

# Answer
> 5 votes
# GNU grep -P, 11 bytes

```
(.).*\1.*\1

```

P.a. to selecting the language flavour for perl, I'm not counting -P (which sets the language flavour to PCRE from the default BRE).

"List of string" defined as "text file" (POSIX).

Test case typescript:

```
$ printf '%s\n' \
  'element' 'photoshop' 'good' \
  'happy' 'colorful' 'luggage' \
  'reference' 'tomorrow' 'today' \
| grep -P '(.).*\1.*\1'
element
photoshop
luggage
reference
tomorrow

```

# Answer
> 5 votes
# Python 3, 48 bytes

```
lambda s:[c for c in s if max(map(c.count,c))>2]

```

Try it online!

# Answer
> 4 votes
# Ruby, 25 bytes

```
->l{l.grep /(.).*\1.*\1/}

```

Try it online!

# Answer
> 4 votes
# Pip `-p`, 11 bytes

```
gFI2<M:^_N_

```

Try It Online!

### Explanation

```
gFI2<M:^_N_
g            List of command-line arguments
 FI          Filter by this function:
   2<          2 is less than
     M         the maximum of
      :        (force the precedence of unary M to be lower than its rhs)
         N_    the number of occurrences in the argument string of
       ^_      each character in the argument string

```

# Answer
> 3 votes
# Vyxal, ~~7~~ 6 bytes

```
'sĠ'ḢḢ

```

Try it Online!

## Explained

```
'sĠ'ḢḢ
'      # Filter input where:
 sĠ    #   sorted and grouped by consecutive
   'ḢḢ #   has items where length >= 3

```

# Answer
> 3 votes
# JavaScript, 37 bytes

I/O as an array of strings, using ~~GB's~~ Adám's RegEx.

```
a=>a.filter(s=>/(.).*\1.*\1/.test(s))

```

Try it online!

## ~~44~~ 42 bytes

I/O as an array of character arrays.

```
a=>a.filter(a=>a.some(c=>(a[c]=-~a[c])>2))

```

Try it online!

# Answer
> 3 votes
# Pip `-p`, 14 bytes

```
{FIaM_Na>2}FIg

```

Try It Online!

```
{FIaM_Na>2}FIg
{         }FIg   Keep words that return truthy resuts for ...
   aM_Na>2       Does the letter appear more than two times?
 FI              Filter out falsy results (return either "1" or "")

```

# Answer
> 3 votes
# sed `-En`, 14 bytes

```
/(.).*\1.*\1/p

```

Attempt This Online!

# Answer
> 3 votes
# x86 .COM, 48 bytes

```
0100  BA 2F 01 B8 03 0A 89 C7-89 C1 F3 AA CD 21 BE 31
0110  01 8A 4C FF 0F B6 D9 C7-40 01 0A 24 AC 89 C3 FE
0120  0F 74 04 E2 F7 EB D9 B2-31 B4 09 CD 21 EB D1 FF

org 100h
sta:    mov dx, bu
    mov ax, 0x0A03
    mov di, ax
    mov cx, ax
la: rep stosb
    int 21h
    mov si, bu+2
    mov cl, [si-1]
    movzx bx, cl
    mov [bx+si+1], word '$'*256+10
lb: lodsb
    mov bx,ax
    dec byte [bx]
    jz ok
    loop lb
    jmp sta
ok: mov dl, bu+2-$100
    mov ah, 9
    int 21h
    jmp sta
bu: db -1

```

Unluckily it behaves bad, input is also displayed

# Answer
> 3 votes
# Jelly, 6 bytes

```
ĠZṫɗƇ3

```

A monadic Link that accepts a list of lists of characters and yields the filtered list.

**Try it online!**

### How?

```
ĠZṫɗƇ3 - Link: words
     3 - set the right argument to three
    Ƈ  - filter (words) keeping those for which:
   ɗ   -   last three links as a dyad - f(word, 3):
Ġ      -     group indices by value - e.g. "aardvark" -> [[1,2,6],[4],[8],[3,7],[5]]
 Z     -     transpose                                   [[1,4,8,3,5],[2,7],[6]]
  ṫ    -     tail from index (3)                         [[6]]
       -     (an empty list is falsey)                   true (the third "a" gives the 6)

```

# Answer
> 2 votes
# Python 3, ~~541 53~~ 50 bytes

To get the ball rollin'...

*-1 thanks to a fix pointed out by xnor
-3 bytes because sets are also fine*

```
lambda n:{i for i in n for y in i if i.count(y)>2}

```

1: crossed out 54 still looks like 54 :(

# Answer
> 2 votes
# Retina 0.8.2, 13 bytes

```
G`(.).*\1.*\1

```

Try it online! Takes newline-separated words. Explanation: `G` is Retina's "grep" operation, which just keeps matching lines, according to the obvious regular expression.

# Answer
> 2 votes
# Charcoal, 12 bytes

```
ＷＳ¿⊙ι›№ικ²⟦ι

```

Try it online! Link is to verbose version of code. Takes newline-terminated words. Explanation:

```
ＷＳ

```

Loop through the words.

```
¿⊙ι›№ικ²

```

If any character appears more than twice, then...

```
⟦ι

```

... output the word on its own line.

9 bytes by taking the input in JSON format:

```
Φθ⊙ι›№ιλ²

```

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

```
 θ          Input array
Φ           Filtered where
   ι        Current word
  ⊙         Any character satisfies
     №      Count of
       λ    Current character
      ι     In current word
    ›       Is greater than
        ²   Literal integer `2`
            Implicitly output each match on its own line

```

# Answer
> 2 votes
# Jelly, 7 bytes

```
ĠẈ>2ẸµƇ

```

Try it online!

## How it works

```
ĠẈ>2ẸµƇ - Main link. Takes a list of words L on the left
     µƇ - Filter L by the following:
Ġ       -   Group the indices of identical letters
 Ẉ      -   Length of each group
  >2    -   Greater than 2?
    Ẹ   -   Any true?

```

# Answer
> 2 votes
# C (gcc), ~~95~~ ~~90~~ 85 bytes

* -5 thanks to l4m2
* -5 thanks to ceilingcat and c--

Lowercase strings only.

Iterates through each string and prints it as soon as it encounters 3 of a letter, skipping the string otherwise. Rather than clear the counters each time, I simply create brand new counters.

```
f(int**s){for(char*t,*i;t=*s;*t&&puts(*s),s++)for(i=calloc(99,9);*t&&++i[*t]<3;t++);}

```

Try it online!

# Answer
> 2 votes
# Java 8, 100 bytes

```
l->{l.removeIf(s->s.chars().noneMatch(c->s.length()-s.replace(""+(char)c,"").length()>2));return l;}

```

Try it online!

# Answer
> 1 votes
# APL (Dyalog Extended), 11 bytes

Anonymous tacit prefix function taking a list of strings

```
⊢/⍨3∊¨3⌊⍧⍨¨

```

Try it online!

the argument…

`/⍨` filtered by…

`3∊¨` whether 3 is a member of each,…

`3⌊` where 3 caps the values of…

`⍧⍨¨` the self-counts for each

# Answer
> 1 votes
# Pyth, 7 bytes

```
.-#+GGQ

```

Try it online!

### Explanation

```
  #        # filter each element of
      Q    # eval(input())
.-         # on the bag-wise subtraction of
   +GG     # two alphabets concatenated

```

# Answer
> 1 votes
# Factor \+ `math.unicode`, 43 bytes

```
[ [ histogram values [ 2 > ] ∃ ] filter ]

```

Attempt This Online!

* `[ ... ] filter` Select sequences whose
* `histogram` histograms
* `values [ ... ] ∃` contain any values
* `2 >` greater than two

# Answer
> 1 votes
# Haskell, 54 bytes

```
import Data.List
r=filter(any((>2).length).group.sort)

```

Try it online!

# Answer
> 1 votes
# 05AB1E, ~~7~~ 6 bytes

```
ʒD¢à3@

```

I/O as a list of lists of characters.

Try it online.

**Old 7 bytes answers with I/O as a list of strings:**

```
ʒ{Åγà3@

```

Try it online.

`{Åγà` could alternatively be `D.M¢` for the same byte-count:
Try it online.

**Explanation:**

```
ʒ       # Filter the (implicit) input-list of lists of characters:
 D      #  Duplicate the current list of characters
  ¢     #  Pop both, and count how many times each character occurs in the list
   à    #  Pop and leave the maximum
    3@  #  Check whether this maximum is >= 3
        # (after which the filtered list of lists of characters is output implicitly)

ʒ       # Filter the (implicit) input-list of strings:
 {      #  Sort the characters in the string
  Åγ    #  Run-length encode it; pushing a list of characters and lengths separated to
        #  the stack
    à   #  Pop the list of lengths and leave its maximum
     3@ #  Check whether this maximum is >= 3
        # (after which the filtered list of strings is output implicitly)

 D      #  Duplicate the current string
  .M    #  Pop and push its most frequently occurring character
    ¢   #  Pop both, and count how many times this most frequent character occurs in the
        #  string

```

# Answer
> 1 votes
# QB45, 122 bytes

```
for t=1to n:redim p(26):for i=1to len(a$(t)):v=asc(mid$(a$(t),i,1))-96:p(v)=p(v)+1:if p(v)>2then ?a$(t):exit for
next:next

```

# Answer
> 1 votes
# PowerShell Core, 30 bytes

```
$args|?{$_-match'(.).*\1.*\1'}

```

Try it online!

Or 40 bytes without a regex: `$args|?{($_|% t*y|group|%{$_|% c*})-ge3}`

# Answer
> 1 votes
# Arturo, ~~62~~ 35 bytes

```
$=>[select&=>[tally&|some?=>[&>2]]]

```

Try it

-27 due to 0.9.82 introducing `tally`.

# Answer
> 1 votes
# Julia 1.7, 37 bytes

```
!l=l[l.|>i->any(count.([i...],i).>2)]

```

Try it online!

# Answer
> 0 votes
# Thunno, \\$10\log\_{256}(96)\approx\\$ 8.23 bytes

```
gz:zy.L2>S

```

Attempt This Online!

```
gz:zy.L2>S  # Implicit input
g           # Filter the input for items where:
         S  #  There is at least one item where:
     .L     #   The lengths of
 z:zy       #   The string, sorted and grouped
       2>   #   Is greater than 2
            # Implicit output

```

# Answer
> 0 votes
# Scala, 100 bytes

Golfed version. Try it online!

```
_.filter(w=>ListMap(w.groupBy(identity).mapValues(_.size).toSeq.sortBy(_._1):_*).values.exists(_>2))

```

---
Tags: code-golf, string, sequence, array, data-structures
---


# Question
Title: Reverse a string while maintaining the capitalization in the same places
The goal here is to simply reverse a string, with one twist:
Keep the capitalization in the same places.

Example Input 1: `Hello, Midnightas`
Example Output 1: `SathginDim ,olleh`

Example Input 2: `.Q`
Exmaple Output 2: `q.`

**Rules**:

* Output to STDOUT, input from STDIN
* The winner will be picked 13th of July on GMT+3 12:00 (One week)
* The input may only consist of ASCII symbols, making it easier for programs that do not use any encoding that contains non-ASCII characters.
* Any punctuation ending up in a position where there was an upper-case letter must be ignored.

# Answer
> 6 votes
## TCC - 4 bytes

```
<>ci

```

Try it online!

Explanation:

```
     - output is implicit in TCC
<>   - reverse string
  c  - preserve capitalization
   i - get input

```

# Answer
> 16 votes
## Python, 71 bytes

```
lambda s:''.join((z*2).title()[c.isupper()-1]for c,z in zip(s,s[::-1]))

```

Try it online

-3 bytes from Ruud, plus the inspiration for 2 more.

-4 more bytes from FryAmTheEggman

# Answer
> 13 votes
## Perl, 31 + 2 (`-lp`) = 33 bytes

*This solution is from @Ton Hospel (13 bytes shorter thant mine).*

```
s%.%(lc$&gt$&?u:l)."c chop"%eeg

```

But you'll need `l` and `p` switches on. To run it :

```
perl -lpe 's%.%(lc$&gt$&?u:l)."c chop"%eeg'

```

# Answer
> 13 votes
# Python 2, 73 bytes

Since the rules specify the input is ascii:

```
lambda s:''.join([z.lower,z.upper]['@'<c<'[']()for c,z in zip(s,s[::-1]))

```

All the credit goes to @Mego though, but I had not the reputation to just comment on his answer.

# Answer
> 9 votes
# Pyth, ~~13~~ ~~11~~ ~~10~~ 9 bytes

*Thanks to @FryAmTheEggman for reminding me about `V` and @LeakyNun for another byte.*

```
srV_Qm!/G

```

Try it online! now on mobile, updating link in a bit

# Answer
> 8 votes
## Python, 66 bytes

```
f=lambda s,i=0:s[i:]and(s[~i]*2).title()[~('@'<s[i]<'[')]+f(s,i+1)

```

Recurses through the indices `i`, taking the character `s[~i]` from the back and the case of `s[i]` from the front. Being capital is checked as lying in the contiguous range `@ABC...XYZ[`. Credit to FryAmTheEggman from the `(_*2).title()` trick.

# Answer
> 5 votes
## Pyke, ~~11~~ ~~10~~ 9 bytes

```
_FQo@UhAl

```

Try it here!

```
_         -   reversed(input)
 F        -  for i in ^
   o      -      o+=1
  Q @     -     input[^]
     Uh   -    ^.is_upper()+1
       Al -   [len, str.lower, str.upper, ...][^](i)
          - "".join(^)

```

# Answer
> 5 votes
## JavaScript (ES6), ~~95~~ 83 bytes

```
s=>[...t=s.toLowerCase()].reverse().map((c,i)=>s[i]==t[i]?c:c.toUpperCase()).join``

```

Edit: Saved a massive 12 bytes thanks to @edc65.

# Answer
> 5 votes
## Retina, ~~75~~ ~~67~~ 65 bytes

Byte count assumes ISO 8859-1 encoding.

```
$
±·$`
O$^`\G[^·]

s{T`L`l`±.
T01`l`L`±.*·[A-Z]
±·

±(.)
$1±
·.
·

```

Try it online! (The first line enables a test suite with multiple linefeed-separated test cases.)

# Answer
> 4 votes
# 05AB1E, ~~19~~ ~~16~~ ~~15~~ 13 bytes

Thanks to **Emigna** for saving a 3 bytes!

Probably gonna get beat by Jelly... Code:

```
Âuvy¹Nè.lil}?

```

Uses the **CP-1252** encoding. Try it online!.

# Answer
> 4 votes
# , 30 bytes

```
(={"_1 toupper@]|.@,.])tolower

```

Doesn't support non-ASCII

# Answer
> 4 votes
# Brachylog, 28 bytes

```
@lr:?z:1ac.
h@u.,@A@um~t?|h.

```

### Explanation

* Main Predicate:

```
@lr                 Reverse the lowercase version of the Input
   :?z              Zip that reversed string with the Input
      :1a           Apply predicate 1 to each couple [char i of reverse, char i of Input]
         c.         Output is the concatenation of the result

```
* Predicate 1:

```
h@u.,               Output is the uppercase version of the first char of Input
     @A@um~t?       The second char of Input is an uppercase letter
             |      Or
              h.    Output is the first char of Input

```

# Answer
> 4 votes
# MATL, 13 bytes

```
PktGtk<)Xk5M(

```

**Try it online!**

```
Pk      % Implicit inpput. Flip, lowercase
t       % Duplicate
Gtk<    % Logical index of uppercase letters in the input string
)       % Get letters at those positions in the flipped string
Xk      % Make them uppercase
5M(     % Assign them to the indicated positions. Implicit display

```

# Answer
> 3 votes
## Actually, 25 bytes

```
;`úíuY"ùû"E£`M@ùRZ`i@ƒ`MΣ

```

Try it online!

Explanation:

```
;`úíuY"ùû"E£`M@ùRZ`i@ƒ`MΣ
;                          create a copy of the input
 `úíuY"ùû"E£`M             for each character in input:
  úíuY                       0-based index in lowercase English letters, or -1 if not found, increment, boolean negate (1 if uppercase else 0)
      "ùû"E£                 `û` if the character is lowercase else `ù` (str.lower vs str.upper)
              @ùRZ         make the other copy of the input lowercase, reverse it, and zip it with the map result
                  `i@ƒ`M   for each (string, function) pair:
                   i@ƒ       flatten, swap, apply (apply the function to the string)
                        Σ  concatenate the strings

```

# Answer
> 3 votes
# Haskell, ~~83~~ ~~80~~ ~~75~~ 71 bytes

The most straightforward way I could think of.

```
import Data.Char
f a|isUpper a=toUpper|1>0=toLower
zipWith f<*>reverse

```

# Answer
> 3 votes
# TSQL, 175 bytes

Golfed:

```
DECLARE @ varchar(99)='Hello, Midnightas'

,@o varchar(99)='',@i INT=0WHILE @i<LEN(@)SELECT
@i+=1,@o+=IIF(ascii(x)=ascii(lower(x)),lower(y),upper(y))FROM(SELECT
SUBSTRING(@,@i+1,1)x,SUBSTRING(@,len(@)-@i,1)y)z
PRINT @o

```

Ungolfed

```
DECLARE @ varchar(99)='Hello, Midnightas'

,@o varchar(99)=''
,@i INT=0

WHILE @i<LEN(@)
  SELECT @i+=1,@o+=IIF(ascii(x)=ascii(lower(x)),lower(y),upper(y))
  FROM
    (SELECT SUBSTRING(@,@i+1,1)x,SUBSTRING(@,len(@)-@i,1)y)z

PRINT @o

```

**Fiddle**

# Answer
> 3 votes
# PowerShell, ~~154~~, ~~152~~, ~~99~~, 86 bytes

Thank you @TimmyD for saving me a whopping 47 bytes (I also saved an additional 6)

Thank you @TessellatingHeckler for saving an additional 13 bytes.

Latest:

```
param($a)-join($a[$a.length..0]|%{("$_".ToLower(),"$_".ToUpper())[$a[$i++]-in65..90]})

```

Original:

```
param($a);$x=0;(($a[-1..-$a.length])|%{$_=$_.tostring().tolower();if([regex]::matches($a,"[A-Z]").index-contains$x){$_.toupper()}else{$_};$x++})-join''

```

Normal formatting:

Latest (looks best as two lines in my opinion):

```
param($a)
-join($a[$a.length..0] | %{("$_".ToLower(), "$_".ToUpper())[$a[$i++] -in 65..90]})

```

Explanation:

```
param($a)-join($a[$a.length..0]|%{("$_".ToLower(),"$_".ToUpper())[$a[$i++]-in65..90]})
param($a)
# Sets the first passed parameter to variable $a
         -join(                                                                      )
# Converts a char array to a string
               $a[$a.length..0]
# Reverses $a as a char array
                               |%{                                                  }
# Shorthand pipe to foreach loop
                                  ("$_".ToLower(),"$_".ToUpper())
# Creates an array of the looped char in lower and upper cases
                                                                 [$a[$i++]-in65..90]
# Resolves to 1 if the current index of $a is upper, which would output "$_".ToUpper() which is index 1 of the previous array

```

Original:

```
param($a)
$x = 0
(($a[-1..-$a.length]) | %{
    $_ = $_.tostring().tolower()
    if([regex]::matches($a,"[A-Z]").index -contains $x){
            $_.toupper()
        }else{
            $_
        }
        $x++
    }
) -join ''

```

First time poster here, was motivated because I rarely see PowerShell, ~~but at ~~154~~ 152 bytes on this one... I can see why!~~ Any suggestions appreciated.

I have learned that I must completely change my way of thinking to golf in code and its fun!

# Answer
> 2 votes
# Dyalog APL, 12 bytes

```
⌽f¨⍨⊢≠f←819⌶

```

`819⌶` is the case folding function

`f←` because its name is long, we assign it to *f*

`⊢≠f` Boolean where text differs from lower-cased text

`f¨⍨` use that (1 means uppercase, 0 means lowercase) to fold each letter...

... of the reversed text

Handles non-ASCII according to the Unicode Consortium's rules.

# Answer
> 2 votes
## CJam, 22 bytes

```
q_W%.{el\'[,65>&{eu}&}

```

Test it here.

# Answer
> 2 votes
# C#, ~~86~~ 85 bytes

```
s=>string.Concat(s.Reverse().Select((c,i)=>s[i]>96?char.ToLower(c):char.ToUpper(c)));

```

A C# lambda where the input and the output is a string. You can try it on .NetFiddle.

---

~~I am struggling to understand why I cant achieve to convert `char.ToLower(c)` to `c+32`. I hope to fix it!~~

12 bytes saved thanks to @PeterTaylor (`c|32` to add 32 to the ascii value of `c` and `c&~32` to substract 32). The result would be 72 bytes (but can fail on non alpha char).

```
s=>string.Join("",s.Reverse().Select((c,i)=>(char)(s[i]>96?c|32:c&~32)));

```

# Answer
> 2 votes
# Racket, 146 bytes

```
(λ(s)(build-string(string-length s)(λ(n)((if(char-upper-case?(string-ref s n))char-upcase char-downcase)(list-ref(reverse(string->list s))n)))))

```

Racket is bad at this whole "golfing" thing.

*Shrug* As always, any help with shortening this would be much appreciated.

# Answer
> 2 votes
# Jolf, 21 bytes

Try it here!

```
Μid?&γ._pXiS=pxHHpxγγ

```

## Explanation

```
Μid?&γ._pXiS=pxHHpxγγ
Μid                   (Μ)ap (i)nput with (d)is fucntion:
   ?        =pxHH     (H is current element) if H = lowercase(H)
    &γ._pXiS          and set γ to the uppercase entity in the reversed string
                 pxγ  lowercase γ
                    γ else, return γ

```

# Answer
> 2 votes
# Perl 6, 29 bytes

```
$_=get;put .flip.samecase($_)

```

# Answer
> 2 votes
# Jelly, ~~13~~ 10 bytes

```
ŒlðUŒuT}¦n

```

Try it online!

Did I say this was extremely golfable by someone who understands `¦`? Turns out it's just understanding anything at all about chaining in general.

```
Œl            Lowercase the input,
   U          reverse it,
    Œu        then uppercase it
      T}¦     at indices where
  ð      n    the lowercase input doesn't equal the original input.

```

# Answer
> 2 votes
# Vyxal `r`, ~~9~~ 2 bytes

```
Ṙ•

```

Try it online!

# Answer
> 2 votes
# Julia 1.0, ~~114~~ ~~92~~ 78 bytes

```
~x=(b=reverse(lowercase(x));prod(i->b[i]-32('@'<x[i]<'['<b[i]-5<'v'),keys(b)))

```

Try it online!

* -22 bytes thanks to amelies: use `prod`
* -10 bytes thanks to MarcMush: avoid `uppercase` and `isuppercase`
* -4 bytes thanks to MarcMush: use `keys(b)` instead of `1:length(b)`

# Answer
> 2 votes
# Julia 1.0, ~~73, 65~~  64 bytes

```
!s=prod(titlecase(s[end-i+1]^2)[2-('@'<s[i]<'[')] for i=keys(s))

```

Try it online!

-9 MarcMush

# Answer
> 2 votes
# C (gcc), 139 bytes

```
#define B v[c+~i]
#define C(x,y)isupper(x)?toupper(y):tolower(y)
i,t,c;f(char*v){for(c=strlen(v);i<c/2;i++)t=C(B,v[i]),v[i]=C(v[i],B),B=t;}

```

Try it online!

# Answer
> 1 votes
# Octave, ~~51~~ 50 bytes

~~`@(s)merge(isupper(s),b=flip(toupper(s)),tolower(b))`~~

```
@(s)merge(s>64&s<91,b=flip(toupper(s)),tolower(b))

```

# Answer
> 1 votes
# PHP, 128 bytes

```
$s=$argv[1];$l=strrev($s);for($i=0;$i<strlen($s);++$i){echo(strtolower($s[$i])!==$s[$i]?strtoupper($l[$i]):strtolower($l[$i]));}

```

I may attempt to optimize this further but I'll just leave it as is for now.

# Answer
> 1 votes
## Javascript (using external library) (224 bytes)

```
(s)=>{t=_.From(s);var cnt=t.Count();var caps=t.Select(x=>{return x.toUpperCase()===x&&x.toLowerCase()!==x}).ToArray(),i=-1;return t.AggregateRight((a,b)=>{i++;var c=caps[i];return c?a+b.toUpperCase():a+b.toLowerCase()},"");}

```

Disclaimer: Using a library I wrote to bring C#'s LINQ to Javascript

# Answer
> 1 votes
# VIM, 46 bytes

It'd be three bytes `g~G` if we didn't need to read from stdin or write to stdout, but oh well...

```
vim -es '+normal! g~G' '+%print|q!' /dev/stdin

```

To test this, run

```
echo "testString" | vim -es '+normal! g~G' '+%print|q!' /dev/stdin

```

This is my first submission on here, not sure if this kind of submission is acceptable.

# Answer
> 1 votes
# Java 7, ~~221~~ ~~217~~ 180 bytes

```
void c(char[]s){int x=0,y=s.length-1;for(char t;x<y;s[x]=s(t,s[y]),s[y]=s(s[y],t),x++,y--)t=s[x];}char s(char a,char b){return(char)(64<a&a<91?96<b&b<123?b-32:b:64<b&b<91?b+32:b);}

```

Loads of bytes saved thanks to *@LeakuNun*'s approach.

**Ungolfed & test cases:**

Try it here.

```
class Main{
  void c(char[] s){
    int x = 0,
        y = s.length-1;
    for(char t; x < y; s[x] = s(t, s[y]),
                       s[y] = s(s[y], t),
                       x++,
                       y--){
       t = s[x];
    }
  }

  char s(char a, char b){
    return (char)(64 < a & a < 91
                    ? 96 < b & b < 123
                        ? b-32
                        : b
                    : 64 < b & b < 91
                        ? b+32
                        : b);
  }

  public static void main(String[] a){
    print("Hello, Midnightas");
    print("TEST");
    print("test");
    print("Test");
    print(".,..,,!@");
    print("ABCDefgHijklMNOPqrsTuVWxyz");
    print("AbCdEfGHIJKlmnop123");
  }

  static void print(String s){
    char[] t = s.toCharArray();
    c(t);
    System.out.println(t);
  }
}

```

**Output:**

```
SathginDim ,olleh
q.
TSET
tset
Tset
@!,,..,.
ZYXWvutSrqpoNMLKjihGfEDcba
321pOnMLKJIhgfedcba

```

# Answer
> 1 votes
# Sed, 113 + 1 = 114 bytes

Why? Because it's fun to use the *wrong* tool to do things :P

Usage: Run `sed -rf file`, enter text and press `Ctrl` \+ `D` (send EOF).

Golfed:

```
s/[A-Z]/\a\l&/g;s/^.*$/\f&\v/;:x;s/\f\a/\a\f/;s/\a\v/\v\a/;s/\f(.)(.*)(.)\v/\3\f\2\v\1/;tx;s/\f|\v//g;s/\a./\U&/g

```

Ungolfed:

```
s/[A-Z]/\a\l&/g #Prepend all upper-case letters with a
                #BEL ASCII character and make them lowercase
s/^.*$/\f&\v/   #Wrap text between a from feed (\f) and a vertical tab (\v)
                #These are used as markers

:x #Define a label named x

s/\f\a/\a\f/;s/\a\v/\v\a/ #Move BEL characters outside of the boundary, so they're not moved later
s/\f(.)(.*)(.)\v/\3\2\1/  #This part does the switching itself
                          #It grabs a character preceded by a form feed and another
                          #one followed by a vertical tab and swaps them, while keeping the text in-between
                          #and replaces the marker \f and \v

tx             #Conditional jump (t) to label x
               #Jumps to the label x if the last substitution (s command) was successful
s/\f|\v//g     #Delete markers
s/\a(.)/\u\1/g #Make letters preceded by a BEL upper-case

```

# Answer
> 1 votes
# Lua, 132 Bytes

```
function(s)o=""i=0 for m in s:gmatch(".")do n=s:sub(#s-i,#s-i)l=m:lower()o=o..(m==l and n:lower()or n:upper())i=i+1 end print(o)end

```

There might be a better way to do this in lua, but I think this works.

# Answer
> 1 votes
# Ruby, 64 bytes

Try it online!

```
->s{i=0;s.gsub(/./){c=s[i-=1];$&=~/[A-Z]/?c.upcase: c.downcase}}

```

# Answer
> 1 votes
# Pip, 24 bytes

```
{b?UCaa}MZLCRVa(_NAZ Ma)

```

Gets a binary array for the uppercase indices and uppercases those places in the reversed lowercase string.

Try it online!

# Answer
> 1 votes
# 05AB1E, 9 bytes

```
Âls€.uÅÏu

```

Try it online!

**Commented:**

```
Â          # Push input and input reversed
 l         # lowercase reversed input
  s        # swap to normal input
   €.u     # map is_upper
      ÅÏ   # where this is true,
           # apply to the reversed input:
        u  # uppercase

```

# Answer
> 1 votes
# Japt, 12 bytes

```
£ÔgY mvc-X¦v

```

Try it

```
£ÔgY mvc-X¦v     :Implicit input of string U
£                :Map each character X at 0-based index Y
 Ô               :  Reverse U
  gY             :  Get the character at index Y
     m           :  Map
      v          :    Literal "v"
       c-        :    Reduce charcode by
         X¦      :      X does not equal
           v     :      Its lowercase
                 :(This results in mapping the character by either "v",
                 : which is Japt's lowercase method or "u",
                 : which is Japt's uppercase method)

```

# Answer
> 1 votes
# Arturo, 62 bytes

```
$->s[i:0map reverse lower s'c[if<=>s\[i]`A``Z`->upper'c'i+1c]]

```

Try it

Takes a string, returns a list of characters.

# Answer
> 1 votes
# Commodore C64 (just for fun/non-competing), 194 Tokenised BASIC Bytes

To enter this on a real C64, you must use BASIC keyword abbreviations, as you are not able to enter more than 80 characters onto a C64 BASIC line though once entered the interpreter will show the keywords in full. The listing is shown as abbreviations with switched character modes to upper/lower case. You may do this by pressing SHIFT + C=. The program will switch modes anyway on line 0 with the control character N (achieved by pressing `CTRL+N` after the opening quote).

```
0input"{CTRL+N}";a$:ifa$=""tHeN
1l=len(a$):dIp(l),b(l):fOx=1tol:p(x)=aS(mI(a$,x,1))>127:nE:i=1:fOx=lto1stE-1
2b(i)=aS(mI(a$,x,1))aN127:i=i+1:nE:fOx=1tol
3ifb(x)>64tH?cH(b(x)-128*p(x));
4ifb(x)<65tH?cH(b(x));
5nE

```

**Note** I've marked this as non-competing because whilst the character encoding on the Commodore C64 (PETSCII) is compatible with ASCII, it is not ASCII. As this question is six years old at the time of writing, and the questioner has left, I'm sure no one will mind.

Some caveats, string handling with the `INPUT` command has some limitations. For instance, if you wanted to enter `Hello, World!` as a test, you would need to enter it starting with a double quotation mark, so `"Hello, World!"`.

A quick explanation:

* Line 0 switches the character set to upper/lower case, rather than PETSCII graphics mode, and waits for a user input; if there is an empty string entered then the program terminates. I added this otherwise it will error, as the `FOR/NEXT` loops are expecting at least one character to iterate over.
* Line 1 will set l to the length of the string, and set up two numeric arrays, called `p(l)` and `b(l)`. `p(l)` is used for determines whether the positional character is upper case or not, by checking if the character code is 128 or more. If so, a `-1` is added to the array at position `x`, otherwise it is `0`. When that loop ends, we set variable `i` to `1`, and start a new loop counting down from the string length to 1.
* Line 2 sets the array `b(l)` at position `i` to the PETSCII character code; this value is `AND`ed with 127 so that each position will be the lower-case character code. `i` is then incremented by `1` and the loop ends. We then set up a final `FOR/NEXT` loop, again counting up from 1 to `l`.
* Line 3 checks if array position `b(x)` is 65 or greater (this is for characters `a` \- `z` inclusive). If so, it prints the character -128 multiplied by the contents of `p(x)`, which is `-1` for upper-case at that position, or `0` if not. `-128*-1` will add `128` so converting the character at that position to upper case.
* Line 4 checks if array position `b(x)` has a value below 64; if so, we don't want to convert this to upper case or we will get some odd results for numbers and punctuation etc.
* Line 5 iterates the loop again until it is done. When the loop is finished, the program will end gracefully.

The screen shot below shows the BASIC program as the interpreter lists it.

This was a fun challenge and took a little while to get the logic right, so it's quite likely that there are some further optimisations to save some BASIC bytes.

# Answer
> 0 votes
# Excel VBA, 256 bytes

```
Function z(d)
r = Len(d)
ReDim E(1 To r)
For i = 1 To r
b = Mid(d, i, 1)
If Asc(b) > 64 And Asc(b) < 91 Then E(i) = 1
Next i
i = 1
For p = r To 1 Step -1
v = Mid(d, p, 1)
If E(i) = 1 Then z = z & UCase(v) Else z = z & LCase(v)
i = i + 1
Next p
End Function

```

# Answer
> 0 votes
# Google Sheets, 133

Closing parens already discounted.

Input: `A1`

* `A2`: `=LEN(A1)`
* `B1`: `=ArrayFormula(MID(A1,1+A2-SEQUENCE(A2),1))`
    + Reverse string
* `C1`: `=JOIN(,ArrayFormula(if(REGEXMATCH(MID(A1,SEQUENCE(A2),1),"[A-Z]"),UPPER(B:B),LOWER(B:B))))`
    + Compare capital positions, capitalize if originally upper, lower if not. Then join. `EXACT(UPPER(...),...)` is worse because we're dealing with a range here.
    + It's a little sluggish because we don't chop off the `B:B` at the blanks.

# Answer
> -1 votes
C

```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[])
{
  char *a,*b,*c;

  a=c=strdup(argv[1]);
  b=&argv[1][strlen(a)-1];
  for(;*a;a++,b--){
    *a=(*a>='A'&&*a<='Z')?((*b>='a'&&*b<='z')?*b-32:*b):((*b>='A'&&*b<='Z')?*b+32:*b);
  }
  puts(c);
  free(c);
  return 0;
}

```

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