title: Column-wise Sum

text:
# Question
Title: Column-wise Sum
Given a nonempty list of nonempty rows of numbers, compute the *column wise sum*, which is another list that has the length of the longest input row. The first entry of the output list is the sum of all the first entires of the input rows, the second one is the sum of all the second elements (if available) etc. I think following example will explain it way better:

```
Input:      {[1,2,3,4],[1],[5,2,3],[6,1]}
Computation: [1,2,3,4]
              + . . .
             [1]. . .
              + + + .
             [5,2,3].
              + + . .
             [6,1]. .
              = = = =
    Output: [13,5,6,4]

```

### Test Cases

```
{[0]}                         -> 0
{[1],[1,1,1,1]}               -> [2,1,1,1]
{[1],[1,2],[1,2,3],[1,2,3,4]} -> [4,6,6,4]
{[1,6,2,-6],[-1,2,3,5]}       -> [0,8,5,-1]

```

# Answer
# Jelly, 1 byte

```
S

```

Try it online! or verify all test cases.

### How it works

The sum atom `S` is a shorthand for `+/`, which performs reduction by addition.

The quick `/` reduces along the outmost dimension, so it calls its link for the elements of the input. Here, the elements are the rows.

The addition atom `+` vectorizes, so adding two row vectors perform element-by-element addition. When the arguments have different lengths, the elements of the longer argument that have no counterpart in the shorter one are left unaltered.

All in all, with an irregular matrix as argument, `S` computes the column-wise sum, skipping missing entries in the shorter rows.
> 20 votes

# Answer
# Python 2, ~~47~~ 45 bytes

```
lambda x:map(lambda*y:sum(filter(None,y)),*x)

```

*Thanks to @vaultah for golfing off 2 bytes!*

Try it online!
> 11 votes

# Answer
# Perl 6, 23 bytes

```
{roundrobin(|$_)».sum}

```
> 9 votes

# Answer
# Mathematica, 15 bytes

```
Total@*PadRight

```
> 9 votes

# Answer
# Haskell, 34 bytes

```
import Data.List
map sum.transpose

```

Try it online! Usage:

```
Prelude Data.List> map sum.transpose $ [[1,2,3,4],[1],[5,2,3],[6,1]]
[13,5,6,4]

```
> 8 votes

# Answer
# CJam, ~~7~~ 5 bytes

*2 bytes off thanks to Dennis!*

```
{:.+}

```

This defines an anonymous block that takes a list of lists, such as `[[1 2 3 4] [1] [5 2 3] [6 1]]`, and replaces it by a list, `[13 5 6 4]`.

Try it online! Or verify all test cases.

### Explanation

```
{   }   e# Define block
 :      e# Fold over the following dyadic function
  .+    e# Vectorized addition

```
> 8 votes

# Answer
# MATL, 3 bytes

```
oXs

```

(*MATL doesn't know that the plural of "ox" is "oxen"...*)

Input is a cell array of numeric row vectors, in the same format as in the challenge text:

```
{[1,2,3,4],[1],[5,2,3],[6,1]}

```

Try it online! Or verify all test cases.

```
     % Implicit input
o    % Convert cell array to a matrix, right-padding with zeros each row
Xs   % Sum of each column
     % Implicit display

```
> 7 votes

# Answer
## JavaScript (ES6), ~~51~~ 48 bytes

*Saved 3 bytes, thanks to ETHproductions*

```
a=>a.map(b=>b.map((v,i)=>r[i]=~~r[i]+v),r=[])&&r

```

### Test cases

```
let f =

a=>a.map(b=>b.map((v,i)=>r[i]=~~r[i]+v),r=[])&&r

console.log(f([[1,2,3,4],[1],[5,2,3],[6,1]])); // -> [13,5,6,4]
console.log(f([[0]]));                         // -> [0]
console.log(f([[1],[1,1,1,1]]));               // -> [2,1,1,1]
console.log(f([[1],[1,2],[1,2,3],[1,2,3,4]])); // -> [4,6,6,4]
console.log(f([[1,6,2,-6],[-1,2,3,5]]));       // -> [0,8,5,-1]
```
> 4 votes

# Answer
# Haskell, ~~61 41~~ 40 bytes

Thanks @Laikoni for -20 bytes, @nimi for -1 byte!

```
f[]=[]
f l=sum[h|h:_<-l]:f[t:u|_:t:u<-l]

```

**Explanation:** It is just a recursive summation of the first elements of the list, also dealing with discarding empty lists in every intermediate step:

```
    sum[h|h:_<-l]                    -- sums up all the first elemetns of the list
                    [t:u|_:t:u<-l]   -- removes the first element of all the list, and removes empty lists
                   f                 -- applies f to the remaining list
                 :                   -- prepends the sum to the rest

```
> 3 votes

# Answer
# Wonder, 11 bytes

```
@->#sum '#0

```

Transpose and map with sum function. Usage:

```
(@->#sum '#0)[[1 2 3 4];[1];[5 2 3];[6 1]]

```
> 3 votes

# Answer
# C++14, 130 bytes

As unnamed generic lambda:

```
[](auto C,auto&r){r.clear();int i=0,b=1;while(b--){r.push_back(0);for(auto c:C)r.back()+=i<c.size()?c[b=1,i]:0;++i;}r.pop_back();}

```

Requires `C` to be like `vector<vector<int>>` and return value `r` to be like `vector<int>` (should be okay according to meta).

Ungolfed & usage:

```
#include<vector>
#include<iostream>

auto f=
[](auto C, auto&r){
 r.clear();         //clearing r just to be sure
 int i=0,b=1;       //i is the position in the row, b is a boolean
 while(b--){        //while something was added
  r.push_back(0);   //add zero
  for(auto c:C)     //for each container
   r.back() += i<c.size() ?   //add to the last element
    c[b=1,i] : 0;             //set b and get the element or zero
  ++i;
 }
 r.pop_back();      //remove last unnecessary zero
}
;

using namespace std;

int main(){
 vector<vector<int> > C = { {1,2,3,4}, {1}, {5,2,3}, {6,1} };
 vector<int> r;
 f(C,r);
 for (int i: r)
  cout << i << ", ";
 cout << endl;
}

```
> 3 votes

# Answer
# Pyth - 4 bytes

```
sM.T

```

Try it online here.
> 3 votes

# Answer
# Dyalog APL, 3 bytes

```
+⌿↑

```

`+⌿` sum column-wise

the mixed (list of list, stacked into matrix, padding with zeros) argument

TryAPL online!
> 3 votes

# Answer
# J, 5 bytes

```
+/@:>

```

Takes input as a boxed list of lists.

## Test cases

```
   1 ; 1 1 1 1
+-+-------+
|1|1 1 1 1|
+-+-------+
   (+/@:>) 1 ; 1 1 1 1
2 1 1 1
   1 ; 1 2 ; 1 2 3 ; 1 2 3 4
+-+---+-----+-------+
|1|1 2|1 2 3|1 2 3 4|
+-+---+-----+-------+
   (+/@:>) 1 ; 1 2 ; 1 2 3 ; 1 2 3 4
4 6 6 4

```
> 3 votes

# Answer
# , ~~53~~ ~~52~~ 51 bytes

```
\(x){for(i in x)F=F+i*!seq(!i)-1:max(lengths(x));F}

```

Attempt This Online!

Thanks to Giuseppe for a byte saved.
> 3 votes

# Answer
# Octave, 69 bytes

```
@(a){g=1:max(s=cellfun(@numel,a))<=s';f=g'+0;f(g')=[a{:}];sum(f')}{4}

```
> 2 votes

# Answer
# Japt, 5 bytes

```
Uz mx

```

Test it online!

`U` is the input array, and `z` on arrays rotates the array clockwise by 90 degrees. Therefore,

```
[
 [1,2,3,4],
 [1      ],
 [5,2,3  ],
 [6,1    ]
]

```

becomes

```
[
 [6,5,1,1],
 [1,2,  2],
 [  3,  3],
 [      4]
]

```

(Spacing added only for display purposes.)

`mx` then `m`aps by summation (`x`), which gives the desired result: `[13,5,6,4]`.
> 2 votes

# Answer
# Uiua, 4 bytes

```
⬚0/+

```

Try it!

```
⬚0/+
  /+  # sum columns
⬚0    # filling needed nonexistent elements with zero

```
> 2 votes

# Answer
# , 52 bytes

```
\(x)colSums(t(sapply(x,\(v)v[1:max(lengths(x))])),T)

```

Attempt This Online!

Only one byte longer than Kirill L.'s answer, so I thought it's worth posting as well.
> 2 votes

# Answer
## Pyke, 4 bytes

```
.,ms

```

Try it here!
> 1 votes

# Answer
# Java 8, 124 bytes

this is a lambda expression for a `Function< int[ ][ ], int[ ] >`

```
i->{int L=0,t,r[];for(int[]a:i)L=(t=a.length)>L?t:L;r=new int[L];for(;0>L--;)for(int[]a:i)r[L]+=a.length>L?a[L]:0;return r;}

```

it takes the largest array length from the input, creates a new array of that size, and then writes the sums of each column to the array.
> 1 votes

# Answer
## R, ~~105~~ 97 bytes

```
a=c();l=length;for(i in 1:l(w)){length(w[[i]])=max(sapply(w,l));a=rbind(a,w[[i]])};colSums(a,n=T)

```

This takes in input a `list` object called `w` in the form :

```
w=list(c(1,2,3,4),c(1),c(1,2))

```

It outputs the column-wise sum : `[1] 3 4 3 4`

This solution is quite long to me. **R** has the particularity to recycle when you try to bind vectors of different length. For example :

```
a=c(1,2,3,4)
b=c(1,2)

cbind(a,b)

     a b
[1,] 1 1
[2,] 2 2
[3,] 3 1
[4,] 4 2

```

`b` is re-used once to fit, which is why I begin with a list.

The program adjusts the length of all the elements of the list as the one of the longest, binds the elements and computs the column-wise sum. The length adjusting produces `NA`'s, that are ignored by the `sum`.

*-8 bytes* thanks to @Jarko Dubbeldam !
> 1 votes

# Answer
**Clojure, 70 bytes**

```
#(for[i(range(apply max(map count %)))](apply +(for[v %](get v i 0))))

```

A basic nested loop.
> 1 votes

# Answer
# PHP, 63 bytes

```
<?foreach($_GETas$a)foreach($a as$i=>$x)$r[$i]+=$x;print_r($r);

```

call in browser with GET parameters as list of inputs.

Example:
`script.php?a[]=1&a[]=2&a[]=3&a[]=4&b[]=1&c[]=5&c[]=2&c[]=3&d[]=6&d[]=1`
(Array names are ignored, so you can name them any way you want.)

Try this function for testing:

```
function s($a){foreach($a as$b)foreach($b as$i=>$x)$r[$i]+=$x;return$r;}

```

or use `http_build_query($array,a)` to convert a given array of arrays to GET parameters.
> 1 votes

# Answer
# Husk, 4 bytes

```
mΣT0

```

Try it online!

## Explanation

```
mΣT0
  T0 Transpose matrix, padding with 0's where needed
mΣ   map each column to its sum

```
> 1 votes

# Answer
# Scala, 64 bytes

Golfed version. Try it online!

```
l=>{l.map(x=>x.padTo(l.map(_.size).max,0)).transpose.map(_.sum)}

```

Ungolfed version. Try it online!

```
object Main {

  def columnSum(lists: List[List[Int]]): List[Int] = {
    // Ensure the lists are of uniform length for transposing, fill shorter ones with 0s
    val maxLength = lists.map(_.length).max
    val uniformLists = lists.map(list => list.padTo(maxLength, 0))

    // Transpose the list of lists (turns columns into rows) and sum each row
    uniformLists.transpose.map(_.sum)
  }

  def main(args: Array[String]): Unit = {
    // Test cases
    println(columnSum(List(List(1,2,3,4), List(1), List(5,2,3), List(6,1)))) // Output: List(13, 5, 6, 4)
    println(columnSum(List(List(0)))) // Output: List(0)
    println(columnSum(List(List(1), List(1,1,1,1)))) // Output: List(2, 1, 1, 1)
    println(columnSum(List(List(1), List(1,2), List(1,2,3), List(1,2,3,4)))) // Output: List(4, 6, 6, 4)
    println(columnSum(List(List(1,6,2,-6), List(-1,2,3,5)))) // Output: List(0, 8, 5, -1)
  }
}

```
> 0 votes

---
Tags: code-golf, arithmetic, array
---


title: Get multi-dimensional indices in a list

text:
# Question
Title: Get multi-dimensional indices in a list
Given a matrix of non-negative numbers (of arbitrary dimension) and a number, get all multi-dimensional indices of the number in that list.

For example, let's say we have the list `[[0,1,0],[1,0,0]]` and the number `1`. In the first list, we see one `1` at the second index. If we were using one-based indices, this would be index `[1,2]`. In the second list, there is another `1` at the first index, so this would be index `[2,1]`. The final list would be `[[1,2], [2,1]]`.

## Rules

* Standard loopholes apply
* Matrix will:
    + only use non-negative numbers
    + not be ragged
    + never be empty
    + every inner list will always have the same length at its depth
    + always be at least 2-D, and never 1-D or 0-D
* You may take input/output in any reasonable format
* You can use one-based or zero-based indexes
* Built-ins are allowed, but I encourage giving non-builtin answers if you do use them
* This is , so shortest code wins

## Test cases (zero-based indexes)

```
[[0, 1, 0], [1, 0, 0], [1, 1, 1]], 1 => [[0, 1], [1, 0], [2, 0], [2, 1], [2, 2]]
[[[2, 3, 4], [3, 1, 5]], [[0, 2, 3], [3, 2, 3]]], 3 => [[0, 0, 1], [0, 1, 0], [1, 0, 2], [1, 1, 0], [1, 1, 2]]

```

# Answer
# K (ngn/k), 2 bytes

*where equal?* Returns a matrix with a column for each index.

```
&=

```

Try it online!

---

A non-builtin solution, 32 bytes:

```
{$[x~*x;!'&x~y;,/(!#x),''x o'y]}

```

Try it online!

This is recursive function taking the array as first argument `x` and the element as second argument `y`.

`$[ ; ; ]` is the ternary operator.
`x~*x` If the first value of the array matches the array (this is only the case if `x` is a number) ...
`x~y` does the single number match the searched value? (booleans are 0 and 1)
`&` A list with that many 0s.
`!'` Convert each zero to an empty range. This results in the empty list if x and y are different, and in a list containing an empty list otherwise. Returns a list of indices.

Otherwise, if `x` is an array with at least one axis ...
`x o'y` Call the function recursively on each subarray in `x`.
`!#x` Range from 0 to length of x - 1.
`,''` Prepend the index of the subarray to each index in the recursive results.
`,/` Flatten into a single list of indices.
> 7 votes

# Answer
# Python, ~~91~~ ~~85~~ 83 bytes

*-6 bytes thanks to @Steffan*

*-2 bytes thanks to @movatica*

```
f=lambda a,b,c:c and[(i,*j)for i,d in enumerate(a)for j in f(d,b,c-1)]or[[]]*(a==b)
```

Attempt This Online!
> 4 votes

# Answer
# Python NumPy, 33 bytes

```
lambda a,b:zip(*(a==b).nonzero())
```

Attempt This Online!

Admittedly a bit trivial.

Test harness borrowed from @mousetail.
> 3 votes

# Answer
# , 19 bytes

```
\(m,x)which(m==x,T)
```

Attempt This Online!

R has almost exactly the correct built-in for this.

---

# , ~~64~~ 59 bytes

*Edit: -5 bytes thanks to pajonk*

```
\(m,x,k=t(t(expand.grid(lapply(dim(m),`:`,1)))))k[m[k]==x,]
```

Attempt This Online!

Roll-your-own solution without using `which`.

`expand.grid` is used to generate all possible sets of indices, which are then tested to see whether the element is equal to the searched-for `x`. Unfortunately, `expand.grid` outputs a "data.frame" (an R-specific matrix-like data type, but that isn't a matrix): pajonk's golf is to transpose twice (`t(t(...))`) to convert into a matrix, saving 5 bytes compared to the more-conventional `as.matrix(...)`...
> 3 votes

# Answer
# JavaScript (V8), 60 bytes

Expects `(n)(array)`. Prints the 0-based multi-dimensional indices.

```
n=>g=(a,...b)=>a.map?a.map((v,i)=>g(v,...b,i)):a-n||print(b)

```

Try it online!

Or **57 bytes** by using optional chaining, as suggested by @tsh:

```
n=>g=(a,...b)=>a.map?.((v,i)=>g(v,...b,i))||a-n||print(b)

```

(not supported by either TIO or ATO)
> 2 votes

# Answer
# JavaScript, 60 bytes

```
n=>g=(m,...p)=>m.flatMap?.((v,i)=>g(v,...p,i))??(m-n?[]:[p])

```

```
f=

n=>g=(m,...p)=>m.flatMap?.((v,i)=>g(v,...p,i))??(m-n?[]:[p])

console.log(JSON.stringify(f(1)([[0, 1, 0], [1, 0, 0], [1, 1, 1]]))) // [[0, 1], [1, 0], [2, 0], [2, 1], [2, 2]]
console.log(JSON.stringify(f(3)([[[2, 3, 4], [3, 1, 5]], [[0, 2, 3], [3, 2, 3]]]))) // [[0, 0, 1], [0, 1, 0], [1, 0, 2], [1, 1, 0], [1, 1, 2]]
```
> 2 votes

# Answer
# Python 2, 70 bytes

```
f=lambda l,t,a=[]:l>[]and f(l.pop(),t,a+[len(l)])+f(l,t,a)or[a]*(t==l)

```

Try it online!

This takes advantage of Python 2's comparison treating lists as greater than integers. This lets us use a single check `l>[]` which is false for integers as well as the empty list, which both are directed to the base case. Here, if the input is an integer that matches the target value, we return a singleton list of the list of indices `a` that we've built up if, and otherwise the empty list.

The recursive call either goes deeper into the last element which is popped, appending the length of the resulting list as the newest index, or continuing with the now-shorter list.
> 2 votes

# Answer
# JavaScript (Node.js), ~~65~~ 64 bytes

```
z=>f=x=>x.at?x.flatMap((y,i)=>f(y).map(w=>[i,...w])):x-z?[]:[[]]

```

Try it online!
> 1 votes

# Answer
# C (gcc), ~~200~~ 196 bytes

*-4 bytes thanks to @ceilingcat*

```
f(a,x,n)char*a,*x;{for(int i[n],d=-1,c;*a;){*a==91?i[++d]=0:*a-93?*a-44?:++i[d]:--d;for(c=0;*a>47&*a<58;)c+=c<0|*a++-x[c]?~c:1;a+=!c;if(c==strlen(x)){for(c=0;c<n;)printf("%d ",i[c++]);puts("");}}}

```

Try it online!
> 1 votes

# Answer
# Retina, 58 bytes

```
Lv$`(\b\d+\b).*\b\1$
$`
+`\[[^][]+]
0
%|',L$`\[(\d+,)*
$#1

```

Try it online! Link includes test cases. Explanation:

```
Lv$`(\b\d+\b).*\b\1$
$`

```

Extract the prefixes of the input at every instance of the given number.

```
+`\[[^][]+]
0

```

Simplify irrelevant elements from lists into numbers.

```
%|',L$`\[(\d+,)*
$#1

```

Calculate the multidimensional index corresponding to each found element.
> 1 votes

# Answer
# 05AB1E, ~~29~~ 24 bytes

```
QI<Ý"€"×€"Dÿƶ˜0Ks"J.V\)ø

```

1-based output.

-5 bytes (replacing `DΔ€`}\N` with `I<`) by taking the dimensions as additional third input

Try it online or verify all test cases.

**Explanation (of original answer):**

```
Q                # Given the (implicit) multi-dimensional input-list and (implicit)
                 # input-integer, check which are equal
 DΔ€`}\N         # Determine the depth-1 of this multi-dimensional list:
 D               #  Duplicate the multi-dimensional list of 0s/1s
  Δ              #  Loop until the result no longer changes:
   €`            #   Flatten it one level down
     }\          #  After the loop: discard the resulting flattened list
       N         #  And push the last (0-based) index of the loop instead
Ý                # Pop and push a list in the range [0,depth-1]
 "€"×            # Map each to that many "€" as string
     €           # Then map each string to:
      "Dÿƶ˜0Ks"  #  String "Dÿƶ˜0Ks", where `ÿ` is replaced with the "€"-string
               J # Join this list of strings together
.V               # Evaluate and execute it as 05AB1E code:
       D         #  Duplicate the multi-dimensional list of 0s/1s
        €        #  Zero or more `€`: map to a certain depth:
         ƶ       #   Multiply each value by its 1-based index
          ˜      #  Flatten the multi-dimensional list
           0K    #  Remove all 0s
             s   #  Swap, so the multi-dimensional list of 0s/1s is at the top again
  \              # Discard the last multi-dimensional list of 01s/1s
   )             # Wrap all flattened lists on the stack into a list
    ø            # Zip/transpose; swapping rows/columns
                 # (after which the result is output implicitly)

```

Minor note: `"€"×` cannot be `'€×`, because this is the dictionary word for `"view"`: try it online.
> 1 votes

# Answer
# Uiua, 2 bytes

```
⊚=

```

Try it!

0-indexed.
> 1 votes

# Answer
# Scala, 108 bytes

Golfed version. Try it online!

```
(m,n)=>m.zipWithIndex.flatMap{case(i,a)=>i.zipWithIndex.flatMap{case(x,b)=>if(x==n)Seq(Seq(a,b))else Seq()}}

```

Ungolfed version. Try it online!

```
object Main {
  def findIndices(matrix: Seq[Seq[Int]], num: Int): Seq[Seq[Int]] = {
    def helper(matrix: Seq[Seq[Int]], num: Int, prefix: Seq[Int]): Seq[Seq[Int]] = matrix.zipWithIndex.flatMap {
      case (inner: Seq[Int], i) =>
        inner.zipWithIndex.flatMap {
          case (x, j) => if (x == num) Seq(prefix :+ i :+ j) else Seq()
        }
      }
    helper(matrix, num, Seq())
  }

  def main(args: Array[String]): Unit = {
    val matrix = Seq(Seq(0, 1, 0), Seq(1, 0, 0), Seq(1, 1, 1))
    val num = 1
    println(findIndices(matrix, num))  // [[0, 1], [1, 0], [2, 0], [2, 1], [2, 2]]
  }
}

```
> 1 votes

# Answer
# Ruby, 59 bytes

```
->a,n{r=0;a.map{|b|r+=1;c=0;b.map{|d|c+=1;d==n&&p([r,c])}}}

```

Try it online!
> 0 votes

---
Tags: code-golf, array
---


# Question
Title: Determine if an Array contains something other than 2
Take an array which consists of positive integers or arrays, output if it only contains `2`s.

Output should be a truthy or falsey value (Sorry if this destroys answers)

## Truthy Test Cases

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

```

## Falsey Test Cases

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

```

Standard Loopholes Are forbidden.

Default IO rules apply.

Code-golf, Fewest bytes wins!

# Answer
# MATL, 3 bytes

```
2=p

```

Try it online!

Technically, this could just be

```
2=

```

Since an array containing any zero elements is falsy, but this seems cheap.
> 8 votes

# Answer
# Python 2, ~~43~~ 40 bytes

```
f=lambda l:l>=[]and all(map(f,l))or l==2

```

Try it online!

---

At time of posting this answer, it was still allowed per this meta consensus to output via throwing an error / not throwing an error. Therefore this answer at 26 bytes was valid:

```
f=lambda l:l==2or map(f,l)

```

Try it online!
> 16 votes

# Answer
# Prolog (SWI), ~~43~~ 33 bytes

I smell... ***recursion***.

Thanks to *Emigna* and *Leaky Nun* for saving 10 bytes!

### Code

```
a([]).
a([X|T]):-(X=2;a(X)),a(T).

```

Try it online! or Verify all test cases!

### Explanation:

For non-Prolog users, a list is formatted in the following way: `[Head | Tail]`.

The `Head` is the first element of the list, and tail is the remaining list. Test it here!. An important case here is that the **tail** of a list with 1 element is equal to `[]`. You can test that here.

```
% State that an empty array is truthy.
a([]).

% If the list is not empty (covered by the previous line), we need to check
% whether the Head is equal to 2 or whether the head is truthy.
% After that, we only need to check if the remaining list is truthy.
a([Head | Tail]) :- (Head = 2; a(Head)), a(Tail).

```
> 11 votes

# Answer
# Jelly, 4 bytes

```
F;2E

```

Try it online!

## How it works

```
F;2E
F    flatten
 ;2  append 2
   E all elements are equal

```
> 10 votes

# Answer
# Octave, 13 bytes

```
@(x)~any(x-2)

```

**Verify all test cases.**

This is an anonymous function taking one input argument, `x`. It subtracts `2` from all elements, checks if there are any non-zero elements. It negates the output to get `true` for cases where all values are zero.

This works because `x-2` works for matrices of all sizes, including the empty matrix, `[]`.

`x-2` would be sufficient if there couldn't be empty matrices in the input.
> 9 votes

# Answer
# Mathics, 28 bytes

```
Select[Flatten@#,#!=2&]=={}&

```

Try it online!
> 7 votes

# Answer
# JavaScript (ES6), ~~22~~ ~~19~~ ~~23~~ 22 bytes

```
a=>!/[^2,]|22/.test(a)

```

---

## Test it

```
f=
a=>!/[^2,]|22/.test(a)
console.log(" "+f([2])+": "+JSON.stringify([2]))
console.log(" "+f([2,2])+": "+JSON.stringify([2,2]))
console.log(" "+f([[2],[2,2],2])+": "+JSON.stringify([[2],[2,2],2]))
console.log(" "+f([])+": "+JSON.stringify([]))
console.log(" "+f([[],[]])+": "+JSON.stringify([[],[]]))
console.log(f([1])+": "+JSON.stringify([1]))
console.log(f([22])+": "+JSON.stringify([22]))
console.log(f([2,2,2,1])+": "+JSON.stringify([2,2,2,1]))
console.log(f([[1,2],2])+": "+JSON.stringify([[1,2],2]))
```
> 6 votes

# Answer
## Retina, ~~13~~ 10 bytes

*Thanks to Kritixi Lithos for saving 3 bytes.*

```
\W|\b2

^$

```

Try it online!
> 6 votes

# Answer
# 05AB1E, 4 bytes

```
˜YQP

```

Try it online!

**Explanation**

```
˜      # flatten list
 YQ    # check each element for equality to 2
   P   # product of list

```
> 6 votes

# Answer
# APL (Dyalog), 5 bytes

```
∧/2=∊

```

Try it online!

### Explanation

```
∧/                         Only
  2=                       2s are equal to
    ∊                      any of the elements in the enlisted form of the right argument

```
> 5 votes

# Answer
# Mathematica, 15 bytes

```
FreeQ[x_/;x!=2]

```

It also works in Mathics. Try it online!
> 5 votes

# Answer
# Mathematica, 24 bytes

```
Cases[t=Flatten@#,2]==t&

```

Pure function returning `True` or `False`. After `Flatten`ing the nested array and calling it `t`, `Cases[t,2]` returns the list of elements that match the "pattern" `2`, and `==t` checks whether that's the whole list.

# Mathematica, 29 bytes

```
(#//.{2->{},{{}..}->{}})=={}&

```

Not as short, but more fun. Starting from the input `#`, two replacement rules are applied until the result stops changing (`//.`): first, all `2`s are replaced by `{}`s; and then any list whose entries are all empty sets (`{{}..}`) are replaced (repeatedly) by empty sets. If the rest is an empty set (`=={}`), we win.
> 4 votes

# Answer
# Ruby, ~~28~~ ~~23~~ 22 bytes - 5 bytes saved by G B

```
->x{x.flatten-[2]==[]}

```

Despite "flatten" being really long, it's still shorter than regex based solutions or recursive stuff that has to rescue errors in the base case. Ruby's built-in conflation of sets and arrays, however, is amazingly useful sometimes.
> 4 votes

# Answer
# Haskell, 36 bytes

An anonymous function, takes a `String` and returns a `Bool`.

Use as `(all((==2).fst).(reads=<<).scanr(:)[]) "[2,2,2,1]"`

```
all((==2).fst).(reads=<<).scanr(:)[]

```

Try it online!

# How it works

* Haskell doesn't have builtin mixed-type lists, so we take a string as argument.
* `scanr(:)[]` generates a list of all suffixes of the string.
* `(reads=<<)` tries to parse a number at the beginning of each suffix, combining the successes into a list of tuples `(n,restOfString)`.
* `all((==2).fst)` checks if all the parsed numbers are `2`.
> 4 votes

# Answer
# Python 2, 38 bytes

```
lambda l:l.strip('[],2')==l*('22'in l)

```

Try it online!

Takes in a string without spaces, outputs a bool.

Checks if removing all the characters `'[],2'` of `l` gives the empty string. Also checks that `22` is not a substring -- if it is, the input `l` is used in place of the empty string to compare to the result of removal, and that always fails.
> 4 votes

# Answer
## JavaScript (ES6), 26 bytes

```
f=a=>a.map?a.every(f):a==2

```

### Test cases

```
f=a=>a.map?a.every(f):a==2

console.log(f([2]))
console.log(f([2,2]))
console.log(f([[2],[2,2],2]))
console.log(f([]))
console.log(f([[],[]]))

console.log(f([1]))
console.log(f([22]))
console.log(f([2,2,2,1]))
console.log(f([[1,2],2]))
```
> 3 votes

# Answer
# MATL, 4 bytes

```
2-a~

```

Try it online!

**Breakdown:**

```
           % Implicit input
2-         % Push 2 to the stack, and subtract from input
  a        % Any non-zero elements?
    ~      % Negate to get true for cases where all elements are zero.

```

---

Well, outgolfed. But I'm keeping this, since I'm quite happy I managed this all on my own (even though the task is super simple).
> 3 votes

# Answer
# R, 28 bytes

```
function(x)!any(unlist(x)-2)

```

`unlist(x)` turns a (nested) list into a vector. Then `2` is subtracted from that vector. `any` converts (with a warning) numeric to logical and checks if there are any `TRUE`s. This is inverted with `!` and output.

This works with nested lists because `unlist` by default works recursively to unlist all list entries of the initial list.

This also works with empty lists, because `unlist(list())` becomes `numeric()`, an empty numerical vector. Coercion by `any` makes it `logical()`, which is interpreted as `FALSE` by `any`, and then reversed to `TRUE` by `!`.
> 3 votes

# Answer
## JavaScript (ES6), ~~53~~ ~~50~~ 48 bytes

```
_=>(_+"").split`,`.map(c=>!c?2:c).every(c=>c==2)

```

*Saved 5 bytes, thanks to @Shaggy!*

### Test Cases :

```
let f =

_=>(_+"").split`,`.map(c=>!c?2:c).every(c=>c==2)

console.log(f([2]))
console.log(f([2,2]))
console.log(f([[2],[2,2],2]))
console.log(f([]))
console.log(f([[],[]]))

console.log(f([1]))
console.log(f([22]))
console.log(f([2,2,2,1]))
console.log(f([[1,2],2]))
```
> 2 votes

# Answer
# Python 3, 55 bytes

No cheating. Uses nested list as input.

```
f=lambda a:all(type(x)!=int and f(x)for x in a if x!=2)

```

Try it online!
> 2 votes

# Answer
# Retina, ~~14~~ 11 bytes

```
^(\W|2\b)+$

```

Try it online!
> 2 votes

# Answer
# 05AB1E, 4 bytes

```
2‚˜Ë

```

Try it online!
> 2 votes

# Answer
# Jelly, 4 bytes

```
F=2Ạ

```

Try it online!

Slightly different than Leaky's algorithm.

Explanation:

```
F=2Ạ
F    Flatten
 =2  Check if equal to 2 (vectorizes)
   Ạ Check if there isn't any falsey value

```
> 2 votes

# Answer
# 05AB1E, 7 bytes

```
˜DOsg·Q

```

Try it online! or Try All Tests!

```
˜D      # Flatten and duplicate
  O     # Sum one copy
   sg·  # Get double the length of the other copy
      Q # Check if they are equal

```
> 2 votes

# Answer
# Java 8, ~~126~~ ~~55~~ 27 bytes

```
s->s.matches("(\\W|2\\b)+")

```

Port of *@KritixiLithos*'s amazing Retina answer, excluding the `^...$`, since `String#matches` always matches the entire String and adds the `^...$` implicitly.

-2 bytes thanks to @Jakob for reminding me of `^...$` isn't necessary for `String#matches`.

Try it here.
> 2 votes

# Answer
# Ruby, 21 bytes

```
->x{x*?!!~/[^2!]|22/}

```

Using a regex is actually shorter, because joining an array also flattens it.

## How it works

```
->x{
    x*?!                -> Join array using an exclamation mark
        !~              -> String does not contain
          /[^2!]        -> characters different from '2' or '!'
                |       -> or
                 22/    -> '2' repeated at least twice
                    }

```

Try it online!
> 2 votes

# Answer
# Jelly, 3 bytes

```
2ṁ⁼

```

Try it online!

### How it works

```
2ṁ⁼  Main link. Argument: A (array)

2ṁ   Mold 2 like A. This replaces each number in A by 2.
  ⁼  Test if the result is equal to A.

```
> 2 votes

# Answer
# Thunno 2, 4 bytes

```
Ḟ2=p

```

Try it online!

#### Explanation

```
Ḟ2=p  # Implicit input
Ḟ     # Flatten the list
 2=   # Check for == 2
   p  # All are true?
      # Implicit output

```
> 2 votes

# Answer
# Nekomata \+ `-e`, 3 bytes

```
2-ž

```

Attempt This Online!

```
2-      Minus 2
  ž     Check if all elements are zero

```
> 2 votes

# Answer
# Wolfram Language (Mathematica), ~~13~~ 10 bytes

```
2#2&

```

Try it online!

is `\[VectorLessEqual]`.
> 2 votes

# Answer
# Python 2, ~~44~~ ~~43~~ 42 bytes

Takes `x` as the string representation of the list. This also assumes like in the example the representations have no spaces.

```
lambda x:set(x)<=set("[],2"*0**("22"in x))

```

Try it online!

---

## Explanation

Both of these take the characters in the string representation of the input and determine if any characters other than `[], 2` are in it. They do this by casting to a set and comparing to the set of just those characters. However this fails if we have a number other than 2 which has only digits of 2 (e.g. 22 or 222), in order to patch this case we multiply the string used to create the set by the negation of whether or not `x` contains `"22"`. If it contains it this will be the empty set, otherwise it will be the same as before.
> 1 votes

# Answer
# PHP\<7.0, 29 Bytes

Input as as string array JSON encoded

```
<?=!ereg("22|[013-9]",$argn);

```

# PHP\<7.0, 42 Bytes

use the deprecated function ereg

```
<?=!ereg("22|[013-9]",json_encode($_GET));

```

# PHP, 50 Bytes

prints 1 for true and nothing for false

-1 Byte for other wise remove `!`

or + 1 Byte for true 1, false 0 add `+` before `!`

```
<?=!preg_match('#22|[013-9]#',json_encode($_GET));

```

Try it online!
> 1 votes

# Answer
# Ohm, 6 bytes

```
∙e]Å2N

```

Uses `CP-437` encoding.

### Explanation:

```
∙e]Å2E
∙e           ■Evaluate the input to form an array
   Å         ■any(              ,             )
  ]          ■    flatten(input)
    2N       ■                   lambda x:x!=2
             ■implict end of any and print

```
> 1 votes

# Answer
# PHP, 46 bytes

```
<?=!preg_match('/:"(?!2")/',serialize($_GET));

```
> 1 votes

# Answer
## Pyth, 6 bytes

```
!-.nQ2

```

Very similar to my CJam answer. I'm still new to Pyth, so please tell me if there's anything I can golf off.

Explanation:

```
    Q   Input:     [[[], [2]], [1]]
  .n    Flatten:   [2, 1]
 -   2  Remove 2s: [1]
!       Not:       False

```
> 1 votes

# Answer
# Japt `-!`, ~~6~~ ~~5~~ 4 bytes

```
c dÍ

```

Try it

```
c dÍ     :Implicit output of array
c        :Flatten
  d      :Any truthy (non-zero) when
   Í     :Subtracted from 2
         :Implicit output of negation of result

```
> 1 votes

# Answer
# Ruby 1.9+, 19 bytes

```
->x{x*$/!~/^2?+.$/}

```

Form is stolen from G B's answer. The main difference is that I join on a newline (the default value of `$/`), which lets me write a shorter regex by using the `^.$` special characters that have specific interactions with newlines.

The trick that makes this version-specific (1.9 and higher) is the use of the "possessive" quantifier `2?+`. Like `2?`, it'll match zero or one instances of a `2`, but this form will hold onto that `2` forever and prevent it from being matched by the `.`, so a `2` on its own line won't match the overall regexp.
> 1 votes

# Answer
# Kotlin, 90 bytes

## Submission

```
fun r(i:String):Any{return i.replace(Regex("[\\[\\]2,]+"),"")==""&&!i.contains("22")}

```

# TryItOnline

TryItOnline
> 1 votes

# Answer
# Vyxal, 3 bytes

```
2J≈

```

Try it Online!

Append a 2, check if everything is equal
> 1 votes

# Answer
# Raku, 13 bytes

```
*.flat.all==2

```

Try it online!
> 1 votes

# Answer
## Clojure, 21 or 25 bytes

```
#(every?(set"[]2 ")%)
#(every? #{2}(flatten %))

```

The first one takes the argument as string, second one as an actual nested list.

`#{2}` is the set with one element `2`, calling it with an existing element returns it and for a non-existing it returns `nil` (falsy).
> 0 votes

# Answer
# Axiom, 280 bytes

```
w(x:Union(List(Any),NNI)):Boolean==(x case List(Any)=>(g:List(Any):=x;leaf? g=>return true;for i in g repeat(q:=w(i);q=false=>return false);return true);r:NNI:=x;r=2=>true;false)
m(b:List Any):Boolean==(for i in b repeat(q:=w(i::Union(List(Any),NNI));q=false=>return false);true)

```

ungolfed and test

```
f(x:Union(List(Any),NNI)):Boolean==
      x case List(Any)=>
              g:List(Any):=x
              leaf? g =>return true
              for i in g repeat
                         q:=f(i)
                         q=false => return false
              return true
      r:NNI:=x
      r=2=>true
      false

h(b:List Any):Boolean==
    for i in b repeat
          q:=f(i::Union(List(Any),NNI))
          q=false=> return false
    true

(5) -> [[i, m(i)] for i in [ [2],[2,2],[[2],[2,2],2],[],[[],[]] ] ]
   (5)
   [[[2],true],[[2,2],true],[[[2],[2,2],2],true],[[],true],[[[],[]],true]]
                                                      Type: List List Any
(6) -> [[i, m(i)] for i in [ [1],[22],[2,2,2,1], [[1,2],2] ]  ]
   (6)  [[[1],false],[[22],false],[[2,2,2,1],false],[[[1,2],2],false]]
                                                      Type: List List Any

```
> 0 votes

# Answer
## CJam, 7 bytes

Input is in the form of a CJam array literal.

```
q~e_2-!

```

## Explanation:

```
q  e# Read input: | "[[1 2] 2]"
~  e# Eval:       | [[1 2] 2]
e_ e# Flatten:    | [1 2 2]
2- e# Remove 2s:  | [1]
!  e# Not:        | 0

```
> 0 votes

# Answer
# Actually, 10 bytes

```
⌠♂i⌡Y2#@-b

```

Try it online!

Explanation:

```
⌠♂i⌡Y2#@-b
⌠♂i⌡Y       call the function until the result stops changing (fixed-point combinator):
 ♂i           for each item: flatten
     2#@-   set difference: all items that are not 2s
         b  cast to boolean (1 if list is not empty, else 0)

```
> 0 votes

# Answer
# Perl 5, 26 bytes

25 bytes of code + 1 for `-n`

```
map$.&=$_==2,/\d+/g;say$.

```

Try it online!
> 0 votes

# Answer
## TXR Lisp, 30 bytes

```
(opip flatten(all @1(op = 2)))

```

Run:

```
1> (opip flatten(all @1(op = 2)))
#<intrinsic fun: 0 param + variadic>
2> [*1 '()]
t
3> [*1 '(2)]
t
4> [*1 '(2 2 ())]
t
5> [*1 '(() ())]
t
6> [*1 '(() (1))]
nil
7> [*1 '((2) 1 ())]
nil

```
> 0 votes

# Answer
# MY, 6 bytes

```
⎕ḟ2=Π←

```

Try it online!

## How?

* evaluated input
* flatten
* `2=` element-wise equality with two
* `Π` product
* output with no newline
> 0 votes

# Answer
# Common Lisp, ~~68~~ 64 bytes

```
(defun n(l)(or(and(consp l)(n(car l))(n(cdr l)))(not l)(= l 2)))

```

Try it online!
> 0 votes

# Answer
# Pyth, 6 bytes

```
q]2{.n

```

**Try it here!**
> 0 votes

# Answer
# Jelly, ~~3~~ 4 bytes

```
F=2Ạ

```

Gained a byte because of a failed test case.

Try it online!
> 0 votes

# Answer
# Arturo, 19 bytes

```
$=>[[]=--flatten&2]

```

Try it

```
$=>[            ; a function
    []=         ; is the empty block equal to...
    --flatten&2 ; the input, flattened, with 2s removed?
]               ; end function

```
> 0 votes

# Answer
# Zsh, 9 bytes

```
<<<${@/2}

```

Try it online!

Falsey: output contains a number. Truthy: anything else (spaces or empty string). Link includes a test harness that prints `T` or `F`
> 0 votes

# Answer
# Pyt, 4 bytes

```
Ƒ2=Π

```

Try it online!

```
Ƒ           implicit input; Ƒlatten array
 2=         is each element equal to 2?
   Π        product (returns 1 for empty array); implicit print

```
> 0 votes

# Answer
# Fig, \\$3\log\_{256}(96)\approx\\$ 2.469 bytes

```
r=2

```

Try it online!

```
r=2
 =2 # Is each element equal to 2?
r   # Product

```
> 0 votes

# Answer
# Uiua, 8 bytes

```
/×⬚1/×=2

```

Try it!

```
/×⬚1/×=2
      =2  # where are elements equal to two?
  ⬚1/×    # multiply columns, filling missing elements with one
/×        # product

```
> 0 votes

# Answer
# APL(Dyalog Unicode), 9 bytes SBCS

```
(⊢≡2⍴⍨≢)∊

```

Try it on APLgolf!

Alternatively, another 9-byte solution:

```
∧/'2 '∊⍨⍕

```

Try it on APLgolf!
> 0 votes

---
Tags: code-golf, array, decision-problem
---


title: Is it a Cyclic number?

text:
# Question
Title: Is it a Cyclic number?
A cyclic number is a number of "n" digits that when multiplied by 1, 2, 3,...n, results in the same digits but in a different order.

For example, the number 142,857 is a cyclic number since 142,857 x 2 = 285,714, 142,857 x 3 = 428,571, 142,857 x 4 = 571,428, and so on. Given an integer input, determine if it is a cyclic number by outputting a truthy value if it is, and a falsy value if not.

Also, to be clear, the input can contain leading 0's: e.g. 0344827586206896551724137931

This is due to the fact that if leading zeros are not permitted on numerals, then 142857 is the only cyclic number in decimal.

Since it is code-golf, shortest answer in bytes wins!

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

Thanks to *Emigna* for saving 3 bytes!

```
ā*€{ïË

```

Explanation:

```
ā        # Push range(1, len(input) + 1)
 *       # Multiply by the input
  €{     # Sort each element
    ï    # Convert to int to remove leading zeros
     Ë   # Check if all elements are equal

```

Uses the **05AB1E** encoding. Try it online!

# Answer
> 4 votes
# Actually, 18 bytes

```
;;ru@≈*♂$♂S♂≈╔@S≈=

```

Try it online! (expects quoted input)

Explanation:

```
;;ru@≈*♂$♂S♂≈╔@S≈=
;;                  duplicate input twice
  ru                range(1, len(input)+1)
    @≈              convert input to an integer
      *             multiply input by each element in range
       ♂$♂S♂≈       convert each product to a string, sort the digits, and convert back to int
             ╔      uniquify: remove duplicate elements
              @S≈   sort input and convert to int
                 =  compare equality

```

# Answer
> 3 votes
# Python, 86 bytes

```
lambda n:all(sorted(n)==sorted(str(int(n)*i).zfill(len(n)))for i in range(2,len(n)+1))

```

Try it online!

Input numbers as strings.

# Answer
> 2 votes
# PHP, 64 Bytes

```
for(;$i++<9;)$r+=($c=count_chars)($argn)==$c($argn*$i);echo$r>1;

```

Online Version

# Answer
> 2 votes
# Haskell, 36 33 32 45 bytes

```
c n=let l=length n in(10^l-1)`div`read n==l+1

```

Example usage:

```
*Main> c "142857"
True

```

I don't think this algorithm needs any explanation.

TOL

Thanks for suggestions: Generic Display Name, Laikoni.

Thanks for correction: Antony Hatchkins.

**EDIT** Nope, fails on "33".

# Answer
> 2 votes
# dc, 24 25 bytes

```
[1]sa0?dZd10r^1-r1+/rx=ap

```

Prints "0" if the number is not cyclic, otherwise "1". Requires the number to be entered as a string.

Example usage:

```
$ echo "[052631578947368421]" | dc -e '[1]sa0?dZd10r^1-r1+/rx=ap'
1
$ echo "[052631578947368422]" | dc -e '[1]sa0?dZd10r^1-r1+/rx=ap'
0

```

TOL

Explanation: Same algorithm as my Haskell submission.

EDIT Nope, fails on "33".

# Answer
> 1 votes
## Mathematica, 81 bytes

```
Length@Union@PadLeft[Sort/@IntegerDigits[ToExpression@#*Range@StringLength@#]]<2&

```

Try it online!

input string

**Input**

> "010309278350515463917525773195876288659793814432989690721649484536082474226804123711340206185567"

**Output**

> True

# Answer
> 0 votes
# Scala 3, 85 bytes

```
n=>(2 to n.size).forall(i=>n.sorted==(BigInt(n)*i).toString.padTo(n.size,'0').sorted)

```

Attempt This Online!

---
Tags: code-golf, number, arithmetic
---


title: ROT-13 transform standard input

text:
# Question
Title: ROT-13 transform standard input
# Task

Read a string of characters and produce the ROT13 of it. All characters besides `[a-zA-Z]` should be output verbatim. Each letter in the output may be in any case you wish (you do not have to preserve it).

ROT13 is a simple substitution cipher where each letter of the alphabet is rotated by 13 places (it doesn't matter whether you do it forward or backward, since ROT13 is it's own inverse).

# Examples

```
Input
Output

Hello, world!
Uryyb, jbeyq!

Code Golf and Coding Challenges is awesome.
Pbqr Tbys naq Pbqvat Punyyratrf vf njrfbzr.

Mod abuse!1!!1
Zbq nohfr!1!!1

```

# Answer
> 26 votes
# Bash, 23 bytes

Canonical 23-character answer:

```
tr A-Za-z N-ZA-Mn-za-m

```

# Answer
> 22 votes
# Python 2, 34 bytes

```
print raw_input().encode('rot13')

```

# Answer
> 21 votes
## Bash - 5 chars

```
rot13

```

# Answer
> 17 votes
## Befunge - 7x30 = 210 6x26 = 156 characters

New streaming version that supports both upper and lower case and should support unlimited input.

```
v,<               <<     <
  ^-4-9<    >:"A"\`|
     >:"a"\`|     #>:"Z"`|
>~:0`| #    >:"z"`|
,    @ |    <`"m":<v`"M":<
^  +4+9<    ^      <

```

### The old version

This stores the values inside its own source code. Really shows off how horrible it is to try and output stored values in the same order that you receive them. Only supports lowercase characters.

```
vp0p11:+1g11<      < <
v                    ^-4-9<
v    >:"a"\`|>:"z"`|>:"m"`|
>~:0`|      >^     >^#
                     ^+4+9<
     >$011g1+0p>12g1+:12p0g:v
               ^           ,_@

```

I'm not sure exactly what limitations this has, using http://www.quirkster.com/iano/js/befunge.html as the interpreter it does appear to break with large inputs.

# Answer
> 11 votes
## Ruby - 60 57 38 37 chars

Edit: And just realised Ruby strings have a `tr` method.

```
puts$<.read.tr'A-Za-z','N-ZA-Mn-za-m'

```

### Test

```
input = "The challenge: To read an input of arbitrary length and produce the ROT13 of the input. All characters besides A-Z should be copied to the output verbatim, and case should be preserved if possible.

Any language that can read and write standard streams is fair game."

output = `echo '#{input}' | ruby golf-rot13.rb`

puts "Input:"
puts input
puts "-------"
puts "Output:"
puts output

```

Gives:

```
Input:
The challenge: To read an input of arbitrary length and produce the ROT13 of the input. All characters besides A-Z should be copied to the output verbatim, and case should be preserved if possible.

Any language that can read and write standard streams is fair game.
-------
Output:
Gur punyyratr: Gb ernq na vachg bs neovgenel yratgu naq cebqhpr gur EBG13 bs gur vachg. Nyy punenpgref orfvqrf N-M fubhyq or pbcvrq gb gur bhgchg ireongvz, naq pnfr fubhyq or cerfreirq vs cbffvoyr.

Nal ynathntr gung pna ernq naq jevgr fgnaqneq fgernzf vf snve tnzr.

```

# Answer
> 10 votes
# vim, 5 keystrokes

Assuming normal mode and that the text is already written in the buffer:

`g``g``g``?``G`

Or, fallowing vimgolf's conventions:

`g``?``G``Z``Z`

You can also invoke it as a terminal command, something like this:

```
$ vim -c 'norm g?G' -
< your text here ...
... multiple lines if you want ...
... terminate input with ctrl+D on a blank line >

```

I guess the latter would count as a "program" of 8 characters (`norm g?G`)

# Answer
> 10 votes
# R, 37 bytes

```
example("chartr");cat(rot(scan(,"")))

```

`example("chartr")` runs the examples for `chartr`, which includes the `rot` function, which is `ROT13` by default....

# Answer
> 7 votes
`tr///` solution in Perl (39 characters), boilerplate can be removed with `-p`:

```
while(<>){y/a-zA-Z/n-za-mN-ZA-M/;print}

```

Using `-p` (23 characters including the extra switch):

```
perl -pe'y/a-zA-Z/n-za-mN-ZA-M/'

```

# Answer
> 7 votes
## C - 83 79 characters

```
main(c,b){while((c=getchar())>=0)b=c&96,putchar(isalpha(c)?b+1+(c-b+12)%26:c);}

```

Readable version:

```
#include <ctype.h>
#include <stdio.h>

int main(void)
{
    int c, base;

    while ((c = getchar()) >= 0) {
        if (isalpha(c)) {
            base = (c & 96) + 1; /* First letter of the upper or lower case. */
            c = base + (c - base + 13) % 26;
        }
        putchar(c);
    }

    return 0;
}

```

# Answer
> 7 votes
## Python (117 bytes)

Here's a Python version that avoids the `rot13()`-method.

```
import sys
print"".join([chr(x/32*32+1+(x%32+12)%26if 64<x<91or 96<x<123 else x)for x in map(ord,sys.stdin.read())])

```

# Answer
> 6 votes
**DC (111 108 for the dc itself)**

Ok, here it is in (mostly) dc and some sed and od magic to get it into the right format for the code. If you don't count the input thing (`echo -n MESSAGE |`) it's 160 bytes:

```
od -An -t dC|sed 's/^\ *//;s/\ \{2,3\}/\n/g'|dc -e'[13+26%]sm[65-lmx65+]su[97-lmx97+]sl[96<b64<dPc]sa[91>c]sd[123>e]sb[lux]sc[llxdd]se[ddddlaxlrx]sy[?z0<y]dsrx'

```

As a point of interest, the *dc programme* itself is only a *108 bytes* long, shorter than the non-library python version. It even preserves case and punctuation, and *beats* Javascript in the above submission! If only I could better parse the output of od, or better yet replace it altogether.

EDIT: It's worth noting that the question doesn't indicate a trailing new line `10P` which saves me three further bytes.

EDIT 2: There's no specification for the format of the input, so I assume it's taken in as is convenient for my programme :P

# Answer
> 5 votes
Perl6 (54)

```
$*IN.lines».trans("a..zA..Z"=>"n..za..mN..ZA..M").say

```

# Answer
> 5 votes
# PHP - ~~103~~ ~~98~~ 80 characters

(not using str\_rot13())

```
<?=preg_replace('#[a-zA-Z]#e','chr(($x=ord("\0"))-$x%32+1+($x%32+12)%26)',`cat`);

```

# Answer
> 5 votes
## Delphi, 110

```
var c:Char;begin repeat Read(c);Write(Chr(Ord(c)+(Ord(c in['A'..'M'])-Ord(c in['N'..'Z']))*13));until EOF;end.

```

# Answer
> 5 votes
## Haskell, 100 characters

```
a%b=([a..b]++)
main=interact$map$toEnum.((0%64$78%90$65%77$91%96$110%122$97%109$[123..])!!).fromEnum

```

# Answer
> 5 votes
# LispLisp (16,636)

I'm sorry.

```
((((lisp (lisp (lisp (lisp lisp)))) (lisp lisp))
  (lisp lisp))
 (((lisp (lisp (lisp (lisp lisp))))
   ((lisp (lisp (lisp lisp)))
    ((lisp (lisp (lisp (lisp lisp))))
     (((lisp (lisp (lisp (lisp lisp))))
       ((lisp (lisp (lisp lisp)))
        (((lisp (lisp (lisp (lisp lisp))))
          (((lisp (lisp (lisp (lisp lisp))))
            ((lisp (lisp (lisp lisp)))
             (lisp (lisp (lisp (lisp lisp))))))
           (((lisp (lisp (lisp (lisp lisp))))
             ((lisp (lisp (lisp lisp)))
              (lisp (lisp (lisp lisp)))))
            (((lisp (lisp (lisp (lisp lisp))))
              ((lisp (lisp (lisp lisp)))
               (lisp (lisp (lisp (lisp lisp))))))
             (((lisp (lisp (lisp (lisp lisp))))
               ((lisp (lisp (lisp lisp)))
                ((lisp (lisp (lisp (lisp lisp)))) (lisp lisp))))
              (lisp (lisp (lisp lisp))))))))
         ((lisp (lisp (lisp lisp)))
          (lisp (lisp (lisp lisp)))))))
      (((lisp (lisp (lisp (lisp lisp))))
        ((lisp (lisp (lisp lisp)))
         (((lisp (lisp (lisp (lisp lisp))))
           (((lisp (lisp (lisp (lisp lisp))))
             ((lisp (lisp (lisp lisp)))
              (((lisp (lisp (lisp (lisp lisp)))) (lisp lisp))
               ((lisp (lisp (lisp lisp)))
                (lisp (lisp (lisp lisp)))))))
            (((lisp (lisp (lisp (lisp lisp))))
              (((lisp (lisp (lisp (lisp lisp)))) (lisp lisp))
               ((lisp (lisp (lisp lisp)))
                (((lisp (lisp (lisp (lisp lisp)))) (lisp lisp))
                 ((lisp (lisp (lisp lisp)))
                  ((lisp (lisp (lisp lisp))) (lisp lisp)))))))
             ((lisp (lisp (lisp lisp)))
              (((((lisp (lisp (lisp (lisp lisp))))
                  (((lisp (lisp (lisp (lisp lisp))))
                    ((lisp (lisp (lisp lisp)))
                     (lisp (lisp (lisp (lisp lisp))))))
                   (lisp (lisp (lisp lisp)))))
                 ((((lisp (lisp (lisp (lisp lisp))))
                    ((lisp (lisp (lisp (lisp lisp))))
                     (((lisp (lisp (lisp (lisp lisp))))
                       ((lisp (lisp (lisp lisp)))
                        (lisp (lisp (lisp (lisp lisp))))))
                      (lisp (lisp (lisp lisp))))))
                   (((lisp (lisp (lisp (lisp lisp)))) (lisp lisp))
                    (lisp lisp)))
                  (((lisp (lisp (lisp (lisp lisp))))
                    (((lisp (lisp (lisp (lisp lisp))))
                      ((lisp (lisp (lisp lisp)))
                       (lisp (lisp (lisp (lisp lisp))))))
                     (lisp (lisp (lisp lisp)))))
                   (lisp lisp))))
                (((lisp (lisp (lisp (lisp lisp))))
                  ((lisp (lisp (lisp lisp)))
                   ((lisp (lisp (lisp (lisp lisp))))
                    (((lisp (lisp (lisp (lisp lisp)))) (lisp lisp))
                     ((lisp (lisp (lisp lisp))) (lisp lisp))))))
                 (lisp (lisp (lisp lisp)))))
               ((((lisp (lisp (lisp (lisp lisp)))) (lisp lisp))
                 (((lisp (lisp (lisp (lisp lisp))))
                   ((lisp (lisp (lisp lisp)))
                    ((((lisp (lisp (lisp (lisp lisp))))
                       (((lisp (lisp (lisp (lisp lisp))))
                         ((lisp (lisp (lisp lisp)))
                          (lisp (lisp (lisp (lisp lisp))))))
                        (lisp (lisp (lisp lisp)))))
                      (lisp lisp))
                     ((((lisp (lisp (lisp (lisp lisp))))
                        (((lisp (lisp (lisp (lisp lisp))))
                          ((lisp (lisp (lisp lisp)))
                           (lisp (lisp (lisp (lisp lisp))))))
                         (lisp (lisp (lisp lisp)))))
                       (((lisp (lisp (lisp (lisp lisp))))
                         (((lisp (lisp (lisp (lisp lisp))))
                           ((lisp (lisp (lisp lisp)))
                            (lisp (lisp (lisp (lisp lisp))))))
                          (lisp (lisp (lisp lisp)))))
                        (lisp lisp)))
                      (((lisp (lisp (lisp (lisp lisp))))
                        ((lisp (lisp (lisp lisp)))
                         ((lisp (lisp (lisp (lisp lisp))))
                          (((lisp (lisp (lisp (lisp lisp)))) (lisp lisp))
                           ((lisp (lisp (lisp lisp))) (lisp lisp))))))
                       (lisp (lisp (lisp lisp))))))))
                  (((lisp (lisp (lisp (lisp lisp)))) (lisp lisp))
                   ((lisp (lisp (lisp lisp)))
                    ((((lisp (lisp (lisp (lisp lisp)))) (lisp lisp))
                      (lisp lisp))
                     (((lisp (lisp (lisp (lisp lisp))))
                       ((lisp (lisp (lisp lisp)))
                        (((lisp (lisp (lisp (lisp lisp))))
                          ((lisp (lisp (lisp lisp)))
                           ((lisp (lisp (lisp (lisp lisp))))
                            (((lisp (lisp (lisp (lisp lisp)))) (lisp lisp))
                             ((lisp (lisp (lisp lisp))) (lisp lisp))))))
                         (lisp (lisp (lisp lisp))))))
                      (((lisp (lisp (lisp (lisp lisp)))) (lisp lisp))
                       (lisp lisp))))))))
                (((lisp (lisp (lisp (lisp lisp))))
                  ((lisp (lisp (lisp lisp)))
                   ((((lisp (lisp (lisp (lisp lisp))))
                      (((lisp (lisp (lisp (lisp lisp))))
                        ((lisp (lisp (lisp lisp)))
                         (lisp (lisp (lisp (lisp lisp))))))
                       (lisp (lisp (lisp lisp)))))
                     (((lisp (lisp (lisp (lisp lisp))))
                       ((lisp (lisp (lisp lisp)))
                        (((lisp (lisp (lisp (lisp lisp))))
                          (((lisp (lisp (lisp (lisp lisp))))
                            ((lisp (lisp (lisp lisp)))
                             (lisp (lisp (lisp (lisp lisp))))))
                           (lisp (lisp (lisp lisp)))))
                         (((lisp (lisp (lisp (lisp lisp))))
                           (((lisp (lisp (lisp (lisp lisp))))
                             ((lisp (lisp (lisp lisp)))
                              (lisp (lisp (lisp (lisp lisp))))))
                            (lisp (lisp (lisp lisp)))))
                          (lisp lisp)))))
                      ((((lisp (lisp (lisp (lisp lisp)))) (lisp lisp))
                        (lisp lisp))
                       (((lisp (lisp (lisp (lisp lisp))))
                         (((lisp (lisp (lisp (lisp lisp))))
                           ((lisp (lisp (lisp lisp)))
                            (lisp (lisp (lisp (lisp lisp))))))
                          (lisp (lisp (lisp lisp)))))
                        (lisp lisp)))))
                    (((lisp (lisp (lisp (lisp lisp))))
                      ((lisp (lisp (lisp lisp)))
                       ((lisp (lisp (lisp (lisp lisp))))
                        (((lisp (lisp (lisp (lisp lisp)))) (lisp lisp))
                         ((lisp (lisp (lisp lisp)))
                          ((((lisp (lisp (lisp (lisp lisp))))
                             (((lisp (lisp (lisp (lisp lisp))))
                               ((lisp (lisp (lisp lisp)))
                                (lisp (lisp (lisp (lisp lisp))))))
                              (lisp (lisp (lisp lisp)))))
                            (((lisp (lisp (lisp (lisp lisp))))
                              ((lisp (lisp (lisp lisp)))
                               (((lisp (lisp (lisp (lisp lisp))))
                                 (((lisp (lisp (lisp (lisp lisp))))
                                   ((lisp (lisp (lisp lisp)))
                                    (lisp (lisp (lisp (lisp lisp))))))
                                  (lisp (lisp (lisp lisp)))))
                                (((lisp (lisp (lisp (lisp lisp))))
                                  (((lisp (lisp (lisp (lisp lisp))))
                                    ((lisp (lisp (lisp lisp)))
                                     (lisp (lisp (lisp (lisp lisp))))))
                                   (lisp (lisp (lisp lisp)))))
                                 (lisp lisp)))))
                             ((((lisp (lisp (lisp (lisp lisp)))) (lisp lisp))
                               (lisp lisp))
                              (((lisp (lisp (lisp (lisp lisp))))
                                (((lisp (lisp (lisp (lisp lisp))))
                                  ((lisp (lisp (lisp lisp)))
                                   (lisp (lisp (lisp (lisp lisp))))))
                                 (lisp (lisp (lisp lisp)))))
                               (lisp lisp)))))
                           ((lisp (lisp (lisp (lisp lisp))))
                            (((lisp (lisp (lisp (lisp lisp))))
                              ((lisp (lisp (lisp lisp)))
                               (lisp (lisp (lisp (lisp lisp))))))
                             (lisp (lisp (lisp lisp)))))))))))
                     (lisp (lisp (lisp lisp)))))))
                 ((((lisp (lisp (lisp (lisp lisp))))
                    (((lisp (lisp (lisp (lisp lisp))))
                      ((lisp (lisp (lisp lisp)))
                       (lisp (lisp (lisp (lisp lisp))))))
                     (lisp (lisp (lisp lisp)))))
                   (((lisp (lisp (lisp (lisp lisp))))
                     ((lisp (lisp (lisp lisp)))
                      (((lisp (lisp (lisp (lisp lisp))))
                        (((lisp (lisp (lisp (lisp lisp))))
                          ((lisp (lisp (lisp lisp)))
                           (lisp (lisp (lisp (lisp lisp))))))
                         (lisp (lisp (lisp lisp)))))
                       (((lisp (lisp (lisp (lisp lisp))))
                         (((lisp (lisp (lisp (lisp lisp))))
                           ((lisp (lisp (lisp lisp)))
                            (lisp (lisp (lisp (lisp lisp))))))
                          (lisp (lisp (lisp lisp)))))
                        (lisp lisp)))))
                    ((((lisp (lisp (lisp (lisp lisp)))) (lisp lisp))
                      (lisp lisp))
                     (((lisp (lisp (lisp (lisp lisp))))
                       (((lisp (lisp (lisp (lisp lisp))))
                         ((lisp (lisp (lisp lisp)))
                          (lisp (lisp (lisp (lisp lisp))))))
                        (lisp (lisp (lisp lisp)))))
                      (lisp lisp)))))
                  (((lisp (lisp (lisp (lisp lisp))))
                    ((lisp (lisp (lisp lisp)))
                     ((lisp (lisp (lisp (lisp lisp))))
                      (((lisp (lisp (lisp (lisp lisp)))) (lisp lisp))
                       ((lisp (lisp (lisp lisp)))
                        (((lisp (lisp (lisp (lisp lisp))))
                          ((lisp (lisp (lisp lisp)))
                           (((lisp (lisp (lisp (lisp lisp)))) (lisp lisp))
                            ((lisp (lisp (lisp lisp)))
                             (lisp (lisp (lisp lisp)))))))
                         (((lisp (lisp (lisp (lisp lisp))))
                           (((lisp (lisp (lisp (lisp lisp)))) (lisp lisp))
                            ((lisp (lisp (lisp lisp)))
                             (((lisp (lisp (lisp (lisp lisp)))) (lisp lisp))
                              ((lisp (lisp (lisp lisp)))
                               ((lisp (lisp (lisp lisp))) (lisp lisp)))))))
                          ((lisp (lisp (lisp lisp)))
                           (((((lisp (lisp (lisp (lisp lisp))))
                               (((lisp (lisp (lisp (lisp lisp))))
                                 ((lisp (lisp (lisp lisp)))
                                  (lisp (lisp (lisp (lisp lisp))))))
                                (lisp (lisp (lisp lisp)))))
                              (((lisp (lisp (lisp (lisp lisp))))
                                ((lisp (lisp (lisp lisp)))
                                 (((lisp (lisp (lisp (lisp lisp))))
                                   (((lisp (lisp (lisp (lisp lisp))))
                                     ((lisp (lisp (lisp lisp)))
                                      (lisp (lisp (lisp (lisp lisp))))))
                                    (lisp (lisp (lisp lisp)))))
                                  (((lisp (lisp (lisp (lisp lisp))))
                                    (((lisp (lisp (lisp (lisp lisp))))
                                      ((lisp (lisp (lisp lisp)))
                                       (lisp (lisp (lisp (lisp lisp))))))
                                     (lisp (lisp (lisp lisp)))))
                                   (lisp lisp)))))
                               ((((lisp (lisp (lisp (lisp lisp)))) (lisp lisp))
                                 (lisp lisp))
                                (((lisp (lisp (lisp (lisp lisp))))
                                  (((lisp (lisp (lisp (lisp lisp))))
                                    ((lisp (lisp (lisp lisp)))
                                     (lisp (lisp (lisp (lisp lisp))))))
                                   (lisp (lisp (lisp lisp)))))
                                 (lisp lisp)))))
                             (((lisp (lisp (lisp (lisp lisp))))
                               ((lisp (lisp (lisp lisp)))
                                ((lisp (lisp (lisp (lisp lisp))))
                                 (((lisp (lisp (lisp (lisp lisp))))
                                   (lisp lisp))
                                  ((lisp (lisp (lisp lisp))) (lisp lisp))))))
                              (lisp (lisp (lisp lisp)))))
                            (((((lisp (lisp (lisp (lisp lisp)))) (lisp lisp))
                               (lisp lisp))
                              (((lisp (lisp (lisp (lisp lisp))))
                                ((lisp (lisp (lisp lisp)))
                                 ((lisp (lisp (lisp (lisp lisp))))
                                  (((lisp (lisp (lisp (lisp lisp))))
                                    ((lisp (lisp (lisp lisp)))
                                     (lisp (lisp (lisp (lisp lisp))))))
                                   (((lisp (lisp (lisp (lisp lisp))))
                                     ((lisp (lisp (lisp lisp)))
                                      ((lisp (lisp (lisp (lisp lisp))))
                                       (lisp lisp))))
                                    (lisp (lisp (lisp lisp))))))))
                               (((lisp (lisp (lisp (lisp lisp))))
                                 ((lisp (lisp (lisp lisp)))
                                  ((lisp (lisp (lisp (lisp lisp))))
                                   ((lisp (lisp (lisp lisp)))
                                    (lisp (lisp (lisp lisp)))))))
                                (((lisp (lisp (lisp (lisp lisp))))
                                  (((lisp (lisp (lisp (lisp lisp))))
                                    ((lisp (lisp (lisp lisp)))
                                     (lisp (lisp (lisp (lisp lisp))))))
                                   (((lisp (lisp (lisp (lisp lisp))))
                                     ((lisp (lisp (lisp lisp)))
                                      (lisp (lisp (lisp lisp)))))
                                    (((lisp (lisp (lisp (lisp lisp))))
                                      (lisp lisp))
                                     (lisp lisp)))))
                                 ((lisp (lisp (lisp lisp)))
                                  ((lisp (lisp (lisp (lisp lisp))))
                                   (((lisp (lisp (lisp (lisp lisp))))
                                     ((lisp (lisp (lisp lisp)))
                                      (lisp (lisp (lisp (lisp lisp))))))
                                    (lisp (lisp (lisp lisp))))))))))
                             ((lisp (lisp (lisp lisp))) (lisp lisp))))))))))))
                   (lisp (lisp (lisp lisp))))))))))))
          (lisp lisp))))
       (((lisp (lisp (lisp (lisp lisp)))) (lisp lisp))
        ((lisp (lisp (lisp lisp)))
         (lisp (lisp (lisp lisp))))))))))
  (((lisp (lisp (lisp (lisp lisp))))
    (((lisp (lisp (lisp (lisp lisp))))
      ((lisp (lisp (lisp lisp)))
       (lisp (lisp (lisp (lisp lisp))))))
     (((lisp (lisp (lisp (lisp lisp))))
       ((lisp (lisp (lisp lisp)))
        (lisp (lisp (lisp lisp)))))
      (((lisp (lisp (lisp (lisp lisp)))) (lisp lisp))
       (lisp lisp)))))
   ((lisp (lisp (lisp lisp)))
    (((lisp (lisp (lisp (lisp lisp)))) (lisp lisp))
     ((lisp (lisp (lisp lisp)))
      ((lisp (lisp (lisp lisp))) (lisp lisp))))))))

```

# Answer
> 5 votes
# C (clang), ~~200~~ ~~164~~ ~~113~~ 86 bytes

```
main(){char*s,*t=s;for(gets(s);*s;s++)isalpha(*s)?*s+=(*s&~32)<78?13:-13:0;printf(t);}

```

Try it online!

This uses a for-loop which converts each letter into ROT13 using their ASCII values to use lesser bytes. `scanf()`'s parameters are now longer to include spaces in the string, since the previous code revision can't take spaces for input, so now it's longer.

Thanks to ceiling cat for golfing 36 bytes. Thanks to EasyasPi, with the help of ceilingcat, for golfing 51 bytes. Thanks to a stone arachnid for golfing 27 bytes.

# Answer
> 4 votes
## PHP - 41 Characters

```
while($r=fgets(STDIN))echo str_rot13($r);

```

# Answer
> 4 votes
# Python 3 (107)

Ok, I promise to stop answering this question now, but I felt compelled to beat the DC answer in Python. This probably reflects poorly on me as a person :).

```
import sys;[print(x.isalpha()and chr((ord(x)&96)+1+(ord(x)%32+12)%26)or x,end='')for x in sys.stdin.read()]

```

# Answer
> 4 votes
# C: 69 68 characters

Alright, I know this thread is long dead, but I couldn't stand the (long) C-solution which doesn't even compile on Clang (but does on GCC).

```
main(c){putchar(isalpha(c=getchar())*((c|32)<110?13:-13)+c);main();}

```

It is probably almost still squeezable. It certainly was squeezable. And not only was it squeezable, it was possible to make it recursive.

# Answer
> 4 votes
# CHIQRSX9+, 1

```
R

```

You just have to use the right tool for the problem.
CHIQRSX9+ is Turing complete, and it can read and write from standard channels with `C`.

# Answer
> 4 votes
# 05AB1E, ~~13~~ 12 bytes

Saved a byte thanks to *robbie0630*

```
ADu)øJD2äRJ‡

```

Try it online!

**Explanation**

```
ADu           # push lower-case and uppercase alphabet
   )øJ        # zip, flatten and join, producing aAbB..zZ
      D2äRJ   # split a copy in 2 pieces, reverse and join producing nNoO..mM
           ‡  # translate input by replacing members of the alphabet
              # with the corresponding member of the rot-13 alphabet
              # implicitly display

```

# Answer
> 4 votes
# x86-16 Machine Code, IBM PC DOS, 37 bytes

**Binary:**

```
00000000: b408 cd21 3c20 7e1c 8ad0 0c20 3c61 7c0e  ...!< ~.... <a|.
00000010: 3c7a 7f0a b60d 3c6e 7c02 b6f3 02d6 b402  <z....<n|.......
00000020: cd21 ebdc c3                             .!...

```

Build and test using `xxd -r`

**Unassembled listing:**

```
        START:
B4 08       MOV  AH, 8          ; DOS API read char from STDIN (no echo)
CD 21       INT  21H            ; read char into AL
3C 20       CMP  AL, ' '        ; is any non-printable control char?
7E 1C       JL   EXIT           ; if so, end
8A D0       MOV  DL, AL         ; save original char in DL
0C 20       OR   AL, 'a'-'A'    ; lowercase the char
3C 61       CMP  AL, 'a'        ; is char less than 'a'?
7C 0E       JL   WRCHR          ; if so, do not convert
3C 7A       CMP  AL, 'z'        ; is char greater than 'z'?
7F 0A       JG   WRCHR          ; if so, do not convert
B6 0D       MOV  DH, 'n'-'a'    ; add or subtract 13
3C 6E       CMP  AL, 'n'        ; is char less than 'n'?
7C 02       JL   ADD13          ; if so, add 13
B6 F3       MOV  DH, 'a'-'n'    ; otherwise add -13
        ADD13:
02 D6       ADD  DL, DH         ; add 13 or -13
        WRCHR:
B4 02       MOV  AH, 2          ; DOS API write char to STDOUT
CD 21       INT  21H            ; write char in DL
EB DC       JMP  START          ; keep looping
        EXIT:
C3           RET                ; return to DOS

```

As a standalone PC DOS executable program. Input is via `STDIN`, output to `STDOUT`.

Re-submitting answer to conform to `STDIN` challenge requirement.

# Answer
> 3 votes
**Java 251 chars**

```
public class r{public static void main(String[] a){String s = a[0];for(int i=0;i<s.length();){char c=s.charAt(i++);if(c>='a'&&c<='m')c+=13;else if(c>='n'&&c<='z')c-= 13;else if(c>='A'&&c<='M')c+=13;else if(c>='A'&&c <='Z')c-=13;System.out.print(c);}}}

```

# Answer
> 3 votes
# Javascript (165)

```
a=prompt();y="ABCDEFGHIJKLMNOPQRSTUVWXYZ";b=y[s="substr"](13)+y[s](0,13);y+=y[l="toLowerCase"]();b+=b[l]();o='';for(i=0;a[i];i++)o+=b[y.indexOf(a[i])]||a[i];alert(o)

```

or (167) as previous Javascript solution, assuming readLine and print:

```
a=readLine();y="ABCDEFGHIJKLMNOPQRSTUVWXYZ";b=y[s="substr"](13)+y[s](0,13);y+=y[l="toLowerCase"]();b+=b[l]();o='';for(i=0;a[i];i++)o+=b[y.indexOf(a[i])]||a[i];print(o)

```

# Answer
> 3 votes
## C, 136 bytes

I have never felt like any of my solutions are good enough to post on here, but made this for fun, and figured that it will be my gateway drug into code golf.

```
#define z(x) c>=x&&c<x+13
#define q(w) c>=w&&c<w+13
main(c){for(;(c=getchar())>=0;putchar(z('A')||z('a')?c+13:q('M')||q('m')?c-13:c));}

```

# Answer
> 3 votes
# \>\<\>, 49 bytes

```
0i::"{`"@(@)*84**-::"AZ"@(@)+:}?$"4"-2d*%"A"+{?$o

```

Try it online

**Explanation**

`0i`
On each loop we initialize the stack with **0** and an input character.
The **0** will be used as a dummy to perform rot-13 operations on when the input isn't a letter.

`::"{`"@(@)*84**-`
Convert lowercase letters into uppercase for easier future operations.

`::"AZ"@(@)+:}?$`
If the character isn't an uppercase letter, use the **0** instead.

`"4"-2d*%"A"+`
ROT-13 operation. Subtract **52**, mod by **13** and add **65** to get an uppercase letter.

`{?$`
If the character wasn't an uppercase before the ROT-13 operations, use the saved character instead.

`o`
Print as a character.

# Answer
> 2 votes
## Haskell - 112 characters

```
r l=drop 13 l++take 13 l
t=['a'..'z']
s=['A'..'Z']
main=interact$map(\x->maybe x id$lookup x$zip(t++s)$r t++r s)

```

# Answer
> 2 votes
**JavaScript 1.8, 106**

`alert(prompt().replace(/\w/g,function(c)String.fromCharCode(c.charCodeAt()+(c.toLowerCase()<'n'?13:-13))))`

**JavaScript, 115**

`alert(prompt().replace(/\w/g,function(c){return String.fromCharCode(c.charCodeAt()+(c.toLowerCase()<'n'?13:-13))}))`

This solution solves the problem by adding 13 to the character code if the character in question is in the first half of the alphabet, or subtracting 13 if it's in the second half.

# Answer
> 2 votes
# Jolf, noncompeting (language postdates challenge)

Jolf, 3 bytes

Try it here!

```
,Ri
,R  rot13
  i the input

```

Or, with new implicit input, `,R`.

I'm sorry, but I'm not. I implemented this because it appears often in code-breaking puzzles, which I use Jolf a lot for, and recently used in an ARG. \o/

A longer one (try that one here):

```
ρi"[%]"γpWpud.pWp2pu+t3 iγH
ρi                           regex replace input
  "[%]"                      "[...]" following
        pWpu                 "abc...xyzABC....XYZ"
       γ                     γ = that
            d                functional replace
             .         _iγH  the index on the alphabet that the element is
                p2pu         shift uppercase alphabet
                    +t3      over thirteen
              pW             upper + lower of that

```

# Answer
> 2 votes
# Julia 1.0, 69 bytes

```
(x->(c=Char(x);print(c+isletter(c)*13*(-1)^(x&31>13)))).(read(stdin))

```

Try it online!

### Explanation

Most of the code is an anonymous function that takes an integer codepoint and prints the corresponding ROT-13'd character:

```
x->(c=Char(x);print(c+isletter(c)*13*(-1)^(x&31>13)))

x->(                                                )  # Anonymous function of x
    c=Char(x);                                         # Cast x to Char and save as c
                    c+                                 # Start with c and add to its codepoint:
                      isletter(c)*                     # If c is not a letter, the rest of this is
                                                       # multiplied by 0
                                  13*(-1)^(       )    # 13, times +/- 1 according to:
                                           x&31>13     # Low 5 bits of x are greater than 13
                                                       # I.e. x > 'M' (if x is uppercase) or x > 'm'
                                                       # (if x is lowercase)
              print(                               )   # Output the resulting character

```

We then apply this function, vectorized, to the array of (integer) codepoints returned by `read(stdin)`.

# Answer
> 2 votes
# JavaScript (Node.js), 65 bytes

```
o=>(b=Buffer)(b(o).map(c=>c%32<26&c>64?(c%32+13)%26+c-c%32:c))+''

```

Try it online!

```
o=>(                    // Define a function taking o and r
  b = Buffer            // Assign b to Buffer
)(                      // And call on...
  b(o).map(c=>          // a Buffer of the charcodes of o, mapped to...
    c%32<26&c>64        // If the character is alphabetical - charcode%32 is less than 26, charcode is >64
      ?                 // Then
    (c%32+13)%26+c-c%32 // Rot-13 the character - Mod 32, add 13, mod 26, add correct number depending on whether it's uppercase of lowercase.
    :c)                 // Else return the original string
 ) + ''                 // Coerce to string

```

# Answer
> 2 votes
# Atto-8 Machine Code, 23 bytes

Decoded as hex:

```
E8 00 E0 C0 20 A0 61 84 00 0D 85 0D 90 0D 85 F2 90 D0 80 00 E1 01 E3

```

Commented disassembly listing:

```
# Generated by Dasm

main!
  nop @dyn        # padding for alignment
  x00 lda         # read from standard input
  ld0 x20 orr     # clone and convert to lowercase
  x61 sub         # map lowercase alphabet to 0-25
  x00             # default offset is 0
  x0D su2 x0D iff # if between a-m, offset is 13
  x0D su2 xF2 iff # if between n-z, offset is -13
  st0 add         # add offset to original input
  x00 sta         # write to standard output
  x01 sti         # loop back to start

```

# Answer
> 1 votes
## K, 31

```
{x^(,/{x!(13_x),13#x}'.Q`A`a)x}

```

# Answer
> 1 votes
## Tcl, 74 chars

```
package require [set c tcl::transform::rot];$c 13 stdin;fcopy stdin stdout

```

# Answer
> 1 votes
# pyg-i \- 76 Bytes

```
P(STDI.read().t({a:a-13 if(77<a<91)or a>109 else a+13 for a in M(ord,STl)}))

```

Python Equivient:

```
import sys,string
print(sys.stdin.read().translate({a:a-13 if(77<a<91)or a>109 else a+13 for a in map(ord,string.ascii_letters)}))

```

# Answer
> 1 votes
# Haskell (103)

Reused `maybe c id $ lookup c` from jloy's answer.

```
main=interact$map(\c->maybe c id$lookup c$[['a'..'z'],['A'..'Z']]>>=zip<*>uncurry(flip(++)).splitAt 13)

```

# Answer
> 1 votes
## Python: 60 bytes

```
lambda s:''.join([chr((ord(c.lower())-84)%26+97)for c in s])

```

The only thing I don't like is having that .lower() in there. Any suggestions?

edit: I can get rid of the .lower(), and handle capitals better, but it's 94 bytes now:

```
lambda s:''.join([chr((ord(c)-(52if ord(c)<97else 84))%26+(65if ord(c)<97else 97))for c in s])

```

# Answer
> 1 votes
# C#, 94 bytes

```
s=>{var r="";foreach(var c in s)r+=(char)(Char.IsLetter(c)?(c|32)<110?c+13:c-13:c);return r;};

```

Anonymous function which returns the string of characters rotated by 13 places, based on this C answer from Fors. Works for any lower or upper letters while keeping other input the same.

Full program with ungolfed method and test cases:

```
using System;

namespace ROT13
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<string, string> f =
            s =>
            {
                var r = "";
                foreach (var c in s)
                    r += (char)(Char.IsLetter(c) ? (c | 32) < 110 ? c + 13 : c - 13 : c);
                return r;
            };

            Console.WriteLine(f("TOO MANY SECRETS!"));   // GBB ZNAL FRPERGF!
            Console.WriteLine(f("too many secrets!"));   // gbb znal frpergf!
            Console.WriteLine(f("gbb znal frpergf!"));   // too many secrets!
            Console.WriteLine(f("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890,./"));
// NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm1234567890,./
        }
    }
}

```

# Answer
> 1 votes
# Befunge-93, ~~72~~ 67 bytes

Edit: -5 bytes thanks to James Holderness

```
<,<v!:+*"a"*`"`"\`\"{":\*"G"*`"@"\`\"[":::_@#+1:~
+0|_\"N"%6-55*1+%

```

Try it online!

Kinda disappointed in the previous Befunge answers, so I wrote one with much less whitespace.

# Answer
> 1 votes
# Jelly, 12 bytes

```
ØAṙ13,µ;Œlyɠ

```

Try it online!

This takes input from STDIN

## How it works

```
ØAṙ13,µ;Œlyɠ - Main link. Takes no arguments
ØA           - "ABC...XYZ"
  ṙ13        - Rotate 13 steps to the left
     ,       - Pair with the unaltered alphabet
      µ      - Begin a new link with ['NOP...KLM', 'ABC...XYZ'] as argument
        Œl   - Lowercase; ['nop...klm', 'abc..xyz']
       ;     - Concatenate; ['NOP...KLM', 'ABC...XYZ', 'nop...klm', 'abc..xyz']
           ɠ - Read a line from STDIN
          y  - Transliterate

```

# Answer
> 1 votes
# Retina, 13 bytes

```
13+T`zlZL`l_L

```

Try it online!

The straightforward transliteration that directly applies ROT13 would be 2 bytes longer Try it online!

### Explanation

The transliteration stage here is wrapped in a loop stage making it run 13 times (or until the string is not transformed anymore, which can only happen if the input string has no alphabetic characters).

In the transliteration, characters in `zlZL` are transformed into the characters at the same positions in `l_L`. Here, `z` and `Z` are exactly what they look like, while `l` and `L` get converted into the lowercase and uppercase alphabets. The final letters of those alphabets are ignored because they already appear earlier in the string, and `_` is just a placeholder to make the uppercase alphabet line up correctly. The result is transforming each letter into the next one (a-\>b,b-\>c,...,z-\>a); doing this 13 times is ROT13.

# Answer
> 1 votes
# Powershell, 77 bytes

```
-join($args|% t*y|%{[char]((("$_"-match'[a-m]')-("$_"-match'[n-z]'))*13+$_)})

```

Test script:

```
$f = {

-join($args|% t*y|%{[char]((("$_"-match'[a-m]')-("$_"-match'[n-z]'))*13+$_)})

}

@(

,("Hello!","Uryyb!")
,("HELLO","URYYB")
,("URYYB","HELLO")
,("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz","NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm")
,("Why did the chicken cross the road?
Gb trg gb gur bgure fvqr!",
"Jul qvq gur puvpxra pebff gur ebnq?
To get to the other side!")

) | % {
    $s,$expected = $_
    $result = &$f $s
    "$($result-eq$expected): $result"
}

```

Output:

```
True: Uryyb!
True: URYYB
True: HELLO
True: NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm
True: Jul qvq gur puvpxra pebff gur ebnq?
To get to the other side!

```

# Answer
> 1 votes
# Python 3, 70 bytes

```
a=input()
for i in a:print(end=i.isalpha()*chr(65+(ord(i)-52)%26)or i)

```

# Answer
> 1 votes
# PHP - 27 Bytes

```
<?=str_rot13(fgets(STDIN));

```

# Answer
> 1 votes
# naz, 176 bytes

```
2a2x1v6a8m2x2v9a4a2x3v9a5a2x4v5a2x5v9a4a2x6v9a5a2x7v1x1f1r3x1v7e3x5v5g3x2v2g8f0x1x2f3x4v3l8f0x1x3f3x3v4g9a4a8f0x1x4f9s4s8f0x1x5f3x7v6l8f0x1x6f3x6v4g9a4a8f0x1x7f0a0x1x8f1o1f0x1f

```

The most involved naz solution I've written so far. This program subtracts 13 from every letter in standard input that's greater than M, and adds 13 to every other letter - whether lowercase or uppercase.

It does use a lot of logic to determine what's a letter or not, so I wouldn't be surprised if this could be improved upon.

Works for any input string terminated with the control character STX (U+0002).

**Explanation** (with `0x` commands removed)

```
2a2x1v                     # Set variable 1 equal to 2
6a8m2x2v                   # Set variable 2 equal to 64 ("@")
9a4a2x3v                   # Set variable 3 equal to 77 ("M")
9a5a2x4v                   # Set variable 4 equal to 91 ("[")
5a2x5v                     # Set variable 5 equal to 96 ("`")
9a4a2x6v                   # Set variable 6 equal to 109 ("m")
9a5a2x7v                   # Set variable 7 equal to 123 ("{")
1x1f                       # Function 1
    1r                     # Read a byte of input
      3x1v7e               # Jump to function 7 if it equals variable 1
            3x5v5g         # Jump to function 5 if it's greater than variable 5
                  3x2v2g   # Jump to function 2 if it's greater than variable 2
                        8f # Otherwise, jump to function 8
1x2f                       # Function 2
    3x4v3l                 # Jump to function 3 if the register is less than variable 4
          8f               # Otherwise, jump to function 8
1x3f                       # Function 3
    3x3v4g                 # Jump to function 4 if the register is greater than variable 3
          9a4a             # Otherwise, add 13 to the register,
              8f           # then jump to function 8
1x4f                       # Function 4
    9s4s8f                 # Subtract 13 from the register, then jump to function 8
1x5f                       # Function 5
    3x7v6l                 # Jump to function 6 if the register is less than variable 7
          8f               # Otherwise, jump to function 8
1x6f                       # Function 6
    3x6v4g                 # Jump to function 4 if the register is greater than variable 6
          9a4a             # Otherwise, add 13 to the register,
              8f           # then jump to function 8
1x7f                       # Function 7
    0a                     # Add 0 to the register
1x8f                       # Function 8
    1o1f                   # Output, then jump to function 1
1f                         # Call function 1

```

# Answer
> 1 votes
# Vyxal, 10 bytes

```
kB½(nn13ǓĿ

```

Try it Online!

-4 thx to lyxal

# Answer
> 1 votes
# GNU AWK, ~~147~~ 8+82 = 90 bytes

`-lordchr` argument

```
BEGIN{RS=".|";ORS=e}$0=RT~/[A-Za-z]/?chr(ord(RT)+(ord(tolower(RT))>109?-13:13)):RT

```

Try it online!

After some thought, I realized it is possible to explore GNU AWK's `ordchr` extension to return the ASCII value of a character, saving tons of bytes. The ROT13 algorithm identifies if the letter is in the first or second half of the alphabet, adding of subtracting 13 to its ASCII value, accordingly.

This code transforms every character as Record Separator, then substitutes every `$0` (formerly null) for the matching record separator (`RT`): ROT13 modified, if it's a letter; or itself, if not.

# Answer
> 1 votes
# Ly, 65 bytes

```
ir[:'@Gf(123)Lf'ZGf'aLfp*!**[p'ZGsp(13)+'Z(32)l*+G[p(26)-0]p0]po]

```

Try it online!

I'm enjoying learning Ly, so even though this is an old challenge I decided to give it a shot...

This is pretty brute force and the result isn't short compared to other entries. But it does show how to do things like `if-then` conditional blocks in Ly, so maybe someone will find it useful?

This bit reads in a line of input as codepoints, reverses the stack, then loops through each character/codepoint. At the end of the loop the character is printed, rot13'd or not.

```
ir[                                                            o]

```

The first thing to do is duplicate the character with `:` since we need to do two operations and it's easier to make a copy of the character on the stack now and then do the first one. That first test checks to see if the current character is in `"a-z"` or `"A-Z"`. It does that by stacking the results from 4 comparisons, `>=A` `>Z` `>=a` and `>z`. Then it combines those `0|1` results mathematically to figure out if we're in the right range.

```
   :'@Gf(123)Lf'ZGf'aLfp*!**

```

Then the pattern I've found works for `if-then` is used to conditionally apply the rot-13 logic only when we get an alphabetic character. That pattern is `...test...[p...then-code...0]p`. So in this case that's these bits.

```
                            [p                              0]p

```

And the code to apply the rotation starts by figuring out and remembering if the character is uppercase or not. After the `s` command, the backup cell will be `1|0` to indicated whether or not the character is uppercase.

```
                              'ZGsp

```

After that, the code adds 13 to the codepoint, then constructs what the max codepoint value is. It's either `Z` or `z` depending on the case of the original character. The `l` command pushed the backup cell (upper/lower flag) onto the stack so we use that to switch the `Z` to `z` if necessary.

```
                                   (13)+'Z(32)l*+

```

Once that max codepoint is on the stack the code conditionally subtracts `26` if the rotated number it too high.

```
                                                 G[p(26)-0]p

```

At that point, the character we want to print is on top of the stack.

# Answer
> 1 votes
# SM83/Z80, 29 bytes

Input string at `(de)`, output to `(hl)`.

* SM83 version

```
1A 13 47 CB AF D6 41 38
0E FE 1A 30 0A FE 0D 78
38 02 D6 1A C6 0D 47 78
22 B7 20 E4 C9

```
* Z80 version (changes in »German guillemets« except for second bytes of `jr` for same effective offset¹)

```
1A 13 47 CB AF D6 41 38
10 FE 1A 30 0C FE 0D 78
38 04 D6 1A C6 0D 47»70
23 04 10«E6 C9

```

Disassembly and explanation:

```
rot13:
    ld a,(de)       ; 1A        load character
    inc de          ; 13        increment
    ld b,a          ; 47        save copy
    res 5,a         ; CB AF     clear fifth bit
    sub 65          ; D6 41     subtract 'A'
    jr c,put        ; 38 0E/10  if borrowed, wasn't letter
    cp 26           ; FE 1A     is it 26 or more now?
    jr nc,put       ; 30 0A/0C  if didn't borrow, wasn't letter
    cp 13           ; FE 0D     compare against 13
    ld a,b          ; 78        load original
    jr c,notsub     ; 38 02/04  if carry, was greater than 13
    sub 26          ; D6 1A     subtract 26 if was greater
notsub:
    add 13          ; C6 0D     add 13 either way
    ld b,a          ; 47        store into b
put:                ;           b now contains rot13 version
#ifdef SM83
    ld a,b          ; 78        move into a
    ld (hl+),a      ; 22        store and increment
    or a            ; B7        test if zero
    jr nz,rot13     ; 20 E4     if not, loop
#else
    ld (hl),b       ; 70        store
    inc hl          ; 23        and increment
    inc b           ; 04        if b was 0, it's now 1
    djnz rot13      ; 10 E6     jump back if b is 1 (and decrement)
#endif
    ret             ; C9        return

```

It's a bit interesting that both CPUs have a way of saving a byte that the other doesn't. The SM83 has autoincrement addressing, while the Z80 has a way to jump if `b` is 1.

¹ Apparently Z80 relative jump instructions are measured from the start, while SM83's are from the end. (So `18 00` is an infinite loop for Z80 and a three-cycle two-byte no-op for SM83.)

# Answer
> 1 votes
# Alice, 129 bytes

```
vv2++3a-A'<
 a    > Ko= h-A'.<
 #  >@o Ko<>.'Zh-=oK
>wI.=>.'a-h=oK Ko<
 *  >^#va2++3a-a'<
 6    +*   >.'zh-=oK
 >+%'A^>6+%'a+oKo<

```

Try it online!

## Ungolfed

```
v                      >oK
                 >.'A-h=oK
    >@     >.'Zh-=oK   >'A-a3++2a*6+%'A+oK
                 >oK
>wI.=>.'a-h=oK
                 >'a-a3++2a*6+%'a+oK
    >^     >.'zh-=oK
                 >oK

```

# Answer
> 1 votes
# Python 3, 60 bytes

```
import this
print("".join(this.d.get(c,c)for c in input()))

```

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

```
`c$@[!256;c@!26;:;(c:"aA"+\:)26!-13+!26]

```

Try it online!

# Answer
> 1 votes
# JavaScript ES6 (155 bytes)

Here is a Caesar cipher that preserves case in in ES6.

```
// 155 bytes
r=s=>((f,n,m,u,l)=>[...s].map(c=>(x=>x>=u&&x<=u+n?f((x-u+m)%n+u):x>=l&&x<=l+n?f((x-l+m)%n+l):c)(c.charCodeAt())).join(''))(String.fromCharCode,26,13,65,97)

// Begin unit tests
mocha.setup('bdd')
const { expect } = chai
const testCases = [{
  input: "Hello, world!",
  output: "Uryyb, jbeyq!",
}, {
  input: "Code Golf and Coding Challenges is awesome.",
  output: "Pbqr Tbys naq Pbqvat Punyyratrf vf njrfbzr.",
}, {
  input: "Mod abuse!1!!1",
  output: "Zbq nohfr!1!!1",
}]
describe('Caesar cipher (ROT13)', () => {
    it('are all equal', () => {
    for (let { input, output } of testCases) {
      expect(r(input)).to.equal(output)
    }
  })
})
mocha.run()
```

```
<link href="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.3.4/mocha.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chai/3.4.1/chai.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.3.4/mocha.js"></script>
<div id="mocha"></div>
```

Here is one that is **187 bytes** (**+32 bytes**), but no code duplication:

```
r=s=>((b,f,n,m,u,l)=>[...s].map(c=>(x=>b(u,x,n)?f(u,x,n,m):b(l,x,n)?f(l,x,n,m):c)(c.charCodeAt())).join(''))((v,x,n)=>x>=v&&x<=v+n,(v,x,n,m)=>String.fromCharCode((x-v+m)%n+v),26,13,65,97)

```

At **192 bytes** (**+37 bytes**), this one is a bit larger, but it builds a lookup and does regex replace:

```
r=s=>(l=>s.replace(/\w/g,c=>l[c]))(((f,z)=>f(z.map(c=>c.toLowerCase()),f(z,{})))((s,o)=>s.reduce((m,c,i)=>({...m,[c]:s[(i+13)%26]}),o),Array.from({length:26},(_,i)=>String.fromCharCode(i+65))))

```

# Answer
> 0 votes
## Scala 108

```
def m(a:Int,z:Int,c:Int)=if(c>=a&&c<z)a+((c-a+13)%26)else c
"Ok?".map(c=>print(m(65,91,m(97,123,c)).toChar))

```

ungolfed:

```
def m (a: Int, z:Int, c:Int) = if (c >= a && c <= z) a+((c-a+13)%26) else c
"Ok?".foreach (c => print (m ('A', 'Z', m ('a', 'z', c)).toChar))

```

result:

```
Bx?

```

# Answer
> 0 votes
**Mathematica 102**

```
StringReplace[Input[],
Join@@Table[Rule@@FromCharacterCode/@{i+c,Mod[i+13,26]+c},{c,{65,97}},{i,0,25}]]

```

# Answer
> 0 votes
# JavaScript 135

```
s=prompt(),o='',i=0
while((c=s.charCodeAt(i++)))c+=c>64&&c<91?c<52?13:-13:c>96&&c<123?c<109?13:-13:0,o+=String.fromCharCode(c)
alert(o)

```

# Answer
> 0 votes
# Scala (96 chars)

```
def r(s:String)=s.map{c⇒val m = if(c<91)65 else 97
if(c.isLetter)
((c+13-m)%26+m).toChar
else c}

```

# Answer
> 0 votes
# , ~~32~~ 29 bytes

```
a.{~3&u:+13*2|&.>:'@MZ`mz'&I.

```

Try it online!

# Answer
> 0 votes
# Japt, 28 bytes

```
c_d)è"%l")?Z|H)<#n?Z+D:Z-D:Z

```

Try it!

```
c_d)è"%l")?Z|H)<#n?Z+D:Z-D:Z
c_                                # map input string through a function
  d)è"%l")?                       # regex check if current character is a letter
           Z|H)<#n?               # is it less than the letter n?
                   Z+D:           # if yes, then add 13
                       Z-D:       # otherwise, subtract 13
                           Z      # not a letter, do not transform

```

# Answer
> 0 votes
# T-SQL, 80 bytes

The TRANSLATE function was introduced in SQL Server 2017.

Input is taken from the column `I` of the table `T`.

```
SELECT TRANSLATE(I,A+B,B+A)FROM(VALUES('ABCDEFGHIJKLM','NOPQRSTUVWXYZ'))V(A,B),T

```

SQL Fiddle

# Answer
> 0 votes
# Zsh, 79 bytes

Builtins only. Try it Online!

```
for k (${(s::)1})printf ${k/[A-Za-z]/${(#)$((z=#k<91?0:32,65+z+(#k-52-z)%26))}}

```

**Explanation**

```
for k (${(s::)1})  # for each letter $k of the argument $1, loop
&&printf ${..}     # and print the value of expression ${..}, per `man zshexpn`
${k/[A-Za-z]/      # if $k is a letter, replace it with the following stuff,
                   #    otherwise leave it (implicit)
${(#)..}           # convert decimal (in the following expression) to ascii char
$((..))            # math expression
                   #    n.b.: #k is the ascii value (ord) of $k
#k<91?             # ternary: if #k<91, i.e $k is uppercase
65+(#k-52)%26      #    rotate uppercase
:97+(#k-84)%26     #    otherwise, rotate lowercase

```

<sub>Previous solutions: ~~126~~, ~~112~~, ~~106~~, ~~99~~, ~~88~~, ~~82~~
Initial (wrong) solutions: ~~56~~, ~~83b~~</sub>

# Answer
> 0 votes
# Google Sheets, 144

* Input: A1 (Given named range "A", +1 score)
* Column B: `=ArrayFormula(CODE(MID(A,SEQUENCE(LEN(A)),1`, given named range "B", +1 score
* Final output: `=ArrayFormula(JOIN(,IF(B=0,,CHAR(IF((B>64)*(B<91),B+13*-1^(B>77),IF((B<97)+(B>122),B,B+13*-1^(B>109`

# Answer
> 0 votes
# Haskell, 77 bytes

```
r(a:b:c)=[a..b]++r c
main=interact$map$(r"\0@NZAM[`nzam{\1114111"!!).fromEnum

```

Try it online!

# Answer
> 0 votes
# Stax, 2 bytes

```
:3

```

Run and debug it

:3

# Answer
> 0 votes
# Assembly (MIPS, SPIM), 122 bytes

```
main:li$2 12
syscall
abs$4 $2
and$2 95
sub$2'A'
bgtu$2 25p
sub$4 13
bge$2 13p
add$4 26
p:li$2 11
syscall
bne$4 10main
j$ra

```

Try it online!

Input is a single line from stdin, output is printed to stdout.

Pretty similar to the other ASM versions as that is the best way on baremetal.

```
main:
.Lloop:
    li    $v0, 12            # READ CHARACTER
    syscall                  # v0 = getchar() or '\n'
    abs    $a0, $v0          # Save copy to a0 (abs is shorter than move for positive)
    and    $v0, 0x5F         # Clear bit 6 to convert lowercase to uppercase
    sub    $v0, 'A'          # Try to convert to number.
    bgtu   $v0, 25, .Lprint  # Non-letters will be < 0 or > 25, test with unsigned > 25
    sub    $a0, 13           # Subtract 13 to rotate left
    bge    $v0, 13, .Lprint  # If the letter-to-number was < 13...
    add    $a0, 26           # Add 26 to revert the left rotation and rotate right
.Lprint:
    li     $v0, 11           # 11 = PRINT CHARACTER
    syscall                  # putchar(a0)
    bne    $a0, '\n', .Lloop # Loop if not end of line
    j      $ra               # Return from main

```

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

```
ZY

```

Attempt This Online!

Builtins FTW!

# Answer
> 0 votes
# Thunno 2, 1 byte

```
V

```

Attempt This Online!

Built-in solution.

# Thunno 2, 12 bytes

```
kĠD½13ȷẒJsdṆ

```

Attempt This Online!

## Thunno 2 `J`, 20 bytes

```
ıÐA?Ä12+26%97+Csfh?R

```

Attempt This Online!

Non built-in solutions.

#### Explanations

```
kĠD½13ȷẒJsdṆ  # Implicit input
kĠD           # Push the string [A-Za-z] and duplicate
   ½          # Halve it to yield [[A-Z], [a-z]]
      ȷ       # To each string in the pair:
    13 Ẓ      #  Rotate it 13 places to the right
              # (We now have [[N-ZA-M], [n-za-m]])
        J     # Join it into [N-ZA-Mn-za-m]
         sd   # Swap and cast to a list of characters
           Ṇ  # Transliterate the input string
              # Implicit output

```

```
ıÐA?Ä12+26%97+Csfh?R  # Implicit input
ı                     # Map over the input string:
 Ð                    #  Triplicate the current character
  A                   #  Pop one copy and check if it's alphabetic
   ?                  #  If it is:
    Ä                 #   Pop another copy and push its 1-based index in the alphabet
     12+              #   Add 12 to this number
        26%           #   Mod this number by 26
           97+        #   Add 97 to this number
              C       #   And convert it to a character
               s      #   Swap so the loop character is back on top
                fh    #   Pop it and check if it's uppercase
                  ?   #   If it is:
                   R  #    Uppercase the character on the top of the stack
                      #   Otherwise, the lowercase character stays on top
                      #  Otherwise, the loop character stays on top
                      # Implicit output, joined

```

# Answer
> 0 votes
# Python + `Rot13`, 23 Bytes

```
from Rot13 import*
func

```

There is a package dedicated to this, but looking at the source code of the package, it is not well written...

---
Tags: code-golf, cryptography
---


title: Geohash Generator

text:
# Question
Title: Geohash Generator
# XKCD Comic:

---

# Goal:

Given a date, the current Dow Opening, and your current coordinates as a rounded integer, produce a "geohash."

# Input:

Input through any reasonable means (STDIN, function argument, flag, etc.) the following:

* The current date. This does necessarily have to be the date of the system's clock, so assume that the input is correct.
* The most recent Dow Opening (must support at least 2 decimal places)
* The floor of your current latitude and longitude.

To make input easier, you can input through any reasonable structured format. Here are some examples (you may create your own):

```
["2005","05","26","10458.68","37",-122"]
2005-05-26,10458.68,37,-122
05-26-05 10458.68 37 -122

```

# Algorithm:

Given your arguments, you must perform the "geohash" algorithm illustrated in the comic. The algorithm is as follows.

1. Format the date and Dow Opening in this structure: `YYYY-MM-DD-DOW`. For example, it might look like `2005-05-26-10458.68`.
2. Perform an md5 hash on the above. Remove any spacing or parsing characters, and split it in to two parts. For example, you might have these strings: `db9318c2259923d0` and `8b672cb305440f97`.
3. Append each string to `0.` and convert to decimal. Using the above strings, we get the following: `0.db9318c2259923d0` and `0.8b672cb305440f97`, which is converted to decimal as aproximately `0.8577132677070023444` and `0.5445430695592821056`. You must truncate it down the the first 8 characters, producing `0.857713` and `0.544543`.
4. Combine the coordinates given through input and the decimals we just produced: `37` \+ `0.857713` = `37.857713` and `-122` \+ `0.544543` = `-122.544543`

# Notes:

* To prevent the code from being unbearably long, you may use a built-in for the md5 hash.
* Standard loopholes (hardcoding, calling external resource) are forbidden.

# Answer
# Bash + Coreutils + md5, 98 bytes:

```
C=`md5 -q -s $1-$2`;C=${C^^};for i in 3 4;{ dc -e 16i[${!i}]n`cut -c1-7<<<.${C:$[16*(i>3)]:16}`p;}

```

Try It Online!

Uses the built-in `md5` command on OSX to generate the MD5 hash. Takes 4 space separated command line arguments in the following format:

```
YYYY-MM-DD DOW LAT LONG

```

with *negative numbers* input and output with a leading *underscore* (i.e. `_122` instead of `-122`).

**Note:** Depending on your system, you may need to substitute in `echo -n $1-$2|md5sum` for `md5 -q -s $1-$2` in order for this to work. Doing so brings the byte count up to 103, and is indeed the case in the TIO link.
> 0 votes

# Answer
# Python 2, 129 bytes

```
import md5
d,q,c=input()
h=md5.new(d+'-'+q).hexdigest()
print map(lambda p,o:o+'.'+`float.fromhex('.'+p)`[2:8],(h[:16],h[16:]),c)

```

Input is given in the form `'2005-05-26','10458.68',('37','-122')` (using the example).

Computes the MD5 hash with `md5.new().hexdigest()`, then performs the necessary transforms. I *could* save five bytes by using `h` instead of `h[:16]`, but I'm not sure if that would affect the six most significant digits in the decimal conversion.

Ideone it! (substituting an `eval()` call for the `input()`)
> 5 votes

# Answer
# Groovy, ~~198~~ 161 bytes

```
{d,o,l,L->m=""+MessageDigest.getInstance("MD5").digest((d+"-"+o).bytes).encodeHex()
h={(Double.valueOf("0x0."+it+"p0")+"")[1..7]}
[l+h(m[0..15]),L+h(m[16..31])]}

```

This is an unnamed closure.

```
Input
f("2005-05-26","10458.68","37","-122")

Output
[37.857713, -122.544543]

```

Try it here!

**Ungolfed** -

```
import java.security.*
{
    date,open,lat,lon ->
    md = "" + MessageDigest.getInstance("MD5").digest((date+"-"+open).bytes).encodeHex()
    decimal = {(Double.valueOf("0x0."+it+"p0")+"")[1..7]}
    [lat+decimal(md[0..15]),lon+decimal(md[16..31])]  //Implicity returns
}

```
> 0 votes

# Answer
## Javascript (Node, using built-in Crypto), 165 characters

```
(d,o,l)=>l.map((p,i)=>p+Math.sign(p)*[...require('crypto').createHash('md5').update(d+-o).digest`hex`.slice(z=i*16,z+16)]
.reduce((a,d,i)=>a+parseInt(d,16)*16**~i,0))

```

Such a verbose API!

## JavaScript (using `md5` library), 125 characters

```
(d,o,l)=>l.map((p,i)=>p+Math.sign(p)*[...require('md5')(d+-o).slice(z=i*16,z+16)]
.reduce((a,d,i)=>a+parseInt(d,16)*16**~i,0))

```

Nothing very golfy here.

In both cases:

f('2005-05-26', 10458.68, [144,-37])

=> [ 144.857713267707, -37.54454306955928 ]
```
</code></pre>
> 0 votes

# Answer
# Python, 185 bytes

```
import hashlib as h
x,y,a,n=input().split(',')
b=h.md5((x+'-'+y).encode()).hexdigest()
q=list(map(str,map(float.fromhex,['0x.'+b[:15],'0x.'+b[16:]])))
print(a+q[0][1:8]+','+n+q[1][1:8])

```

Attempt This Online!

Hashlib stole my bytes, :P.
> 0 votes

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