title: Swap the Alphabet

text:
# Question
Title: Swap the Alphabet
In this challenge, you will be "reversing" the alphabet or swapping `a-z` with `z-a`. This is commonly known as the Atbash cypher.

Because this transformation makes the output look like some foreign language, your code will need to be as short as possible.

---

## Examples

```
abcdefghijklmnopqrstuvwxyz
zyxwvutsrqponmlkjihgfedcba

Programming Puzzles & Code Golf
Kiltiznnrmt Kfaaovh & Xlwv Tlou

Hello, World!
Svool, Dliow!

```

## Specification

* The input may contain multiple lines, and will be ASCII-only
* **No** *additional* whitespace should be added to the output
* Case *must* be preserved

## Leaderboard

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

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

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

---

This is so shortest code in bytes wins

# Answer
## Pyth, 8 bytes

```
XXzG)rG1

```

@xnor suggested this simpler approach on @FryAmTheEggman's Pyth answer, then I translated it to Pyth.

This uses the handy behavior of `X` (translate) when given only two arguments: it translates from the second argument to the reversed second argument. We do this first with the lowercase alphabet (`G`), and then with uppercased `G`.
> 12 votes

# Answer
# C, 59 bytes

Sorry for bringing up C again, but I was a bit disappointed to see only C *functions* here. I was under the impression OP was looking for a usable product.

```
main(c){while(~(c=getchar()))putchar(isalpha(c)?c+4^31:c);}

```

Compiled on Ubuntu 14.04 with a simple:

```
cc swalpha.c

```

The resulting executable reads any number of lines from stdin, and writes the result to stdout.

Thanks to so many of the other posters for the XOR trick.
> 17 votes

# Answer
# JavaScript (ES6), ~~69~~ 67 bytes

```
x=>x.replace(/[A-Z]/gi,c=>String.fromCharCode(c.charCodeAt()+4^31))

```

Uses the same strategy as my Japt answer:

```
x=>x.replace(/[A-Z]/gi,C=>   // Replace each letter C with
 String.fromCharCode(        //  the character with char code
  C.charCodeAt()+4^31))      //   the char code of C, plus 4, with the last 5 bits flipped.

```

Curse your incredibly long property names, JS...
> 11 votes

# Answer
## CJam, 17 bytes

I wanted to help GamrCorps golf his CJam solution, but the result ended up so different that I decided to make a separate answer.

```
q'[,_el^_W%32f^er

```

Try it online.

### Explanation

```
q     e# Read all input.
'[,   e# Get a character range from the null byte up to and including "Z".
_el   e# Duplicate and convert to lowercase.
^     e# Symmetric set difference. Due to the lowercase operation only letters will not
      e# appear in both sets, and so we get a string with all uppercase letters followed
      e# by all lowercase letters, i.e "ABC...XYZabc...xyz".
_W%   e# Duplicate and reverse. Gives: "zyx...cbaZYX...CBA".
32f^  e# Take each character XOR 32 which swaps the case, so now we have:
      e#                               "ZYX...CBAzyx...cba"
er    e# Transliterate: substitute each character in the first string with the correspoding
      e# character in the second string.

```
> 11 votes

# Answer
# Retina, ~~17~~ ~~14~~ 13 bytes

Code:

```
\T`w`_dZ-Az-a

```

Explanation:

```
\             # This suppresses the trailing linefeed
 T            # Switches to transliterate mode
  `w          # w is short for _0-9A-Za-z
    `_d       # d is short for 0-9
       Z-Az-a # Z-Az-a

```

This does some magic stuff and completes the task.

Try it here.
> 10 votes

# Answer
## Pyth, ~~10~~ 9

```
uXGr;H)2z

```

Thanks to Jakube for saving a byte with the new feature of `;`!

Test Suite

A quick explanation: reduce starting with the input over the numbers 0 and 1. The operation to be performed is translate the lower case alphabet with either `r...0` or `r...1` which are the lower and upper functions from python, respectively, applied to it, and then reversed.
> 9 votes

# Answer
# Julia, ~~74~~ ~~61~~ 47 bytes

```
s->replace(s,r"[a-z]"i,t->Char(31$Int(t[1])-4))

```

This is a lambda function that accepts a string and returns a string. To call it, assign it to a variable.

We match each letter using a regular expression and replace each letter with the ASCII character corresponding to 31 XOR the ASCII code for the letter, minus 4.
> 7 votes

# Answer
# Japt, ~~23~~ 22 bytes

```
Ur"[A-Za-z]"_c +4^31 d

```

Try it online!

### How it works

```
Ur"[A-Za-z]"_  // Take the input and replace each letter with:
 c +4          //  Take its char code and add 4. This results in
               //  the string      "ABC...XYZabc...xyz"
               //  becoming        "EFG...\]^efg...|}~".
 ^31           //  XOR the result by 31. This flips its last five 5 bits.
               //  We now have     "ZYX...CBAzyx...cba".
 d             //  Convert back from a char code.
               // Implicit: output last expression

```
> 5 votes

# Answer
## C, ~~150~~ 129 Bytes

```
void rev(char*s){int i,t;for(i=0;i<strlen(s);i++){t=s[i]+25;t=t<116?180-t:244-t;isalpha(s[i])?printf("%c",t):printf("%c",s[i]);}}

```

This function just converts char to int and adds the appropriate offset to the int before printing. I know it's not the shortest but I didn't see a C implementation.

Example usage

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

void rev(char*s){int i,temp;for(i=0;i<strlen(s);i++){temp=s[i]+25;temp=temp<116?180-temp:244-temp;isalpha(s[i])?printf("%c",temp):printf("%c",s[i]);}}

int main(){
   char *s = "hello, there";
   rev(s);
   return 0;
}

```

UPDATE: shortened a variable name.
> 5 votes

# Answer
# R, ~~69~~ 61 bytes

Thanks to @Giuseppe for shaving off some extra bytes:

```
function(s)cat(chartr("a-zA-Z",intToUtf8(c(122:97,90:65)),s))

```

**Previous version:**

```
function(s)cat(chartr("a-zA-Z",rawToChar(as.raw(c(122:97,90:65))),s))

```

This is an anonymous function. Usage:

```
> f=function(s)cat(chartr("a-zA-Z",rawToChar(as.raw(c(122:97,90:65))),s))
> f("Hello, World!")
Svool, Dliow!
> f("Programming Puzzles & Code Golf")
Kiltiznnrmt Kfaaovh & Xlwv Tlou
> f("This is
+ a multiline
+ example.")
Gsrh rh
z nfogrormv
vcznkov.

```
> 5 votes

# Answer
# C, 64

A void function that modify the string in place.

```
t(char*p){for(int c;c=*p;)*p++=c>64&c<91|c>96&c<123?(c^31)-4:c;}

```

Test: ideone
> 5 votes

# Answer
## Python, 61 bytes

```
lambda x:''.join([c,chr(ord(c)+4^31)][c.isalpha()]for c in x)

```

An anonymous function. On letters, does the reversing operation on the bit representation by adding 4, then flipping the last five bits, similar to ETHproductions' Javascript answer.
> 5 votes

# Answer
# Ruby, 40 bytes

New solution: Stole that bit flipping magic from some of the other posts here:

```
->s{s.gsub(/[a-z]/i){($&.ord+4^31).chr}}

```

---

# Ruby, ~~55~~ 46 bytes

```
->s{s.tr'a-zA-Z',[*?A..?Z,*?a..?z].reverse*''}

```

9 bytes off thanks to @manatwork

---

test run:

```
->s{s.gsub(/[a-z]/i){($&.ord+4^31).chr}}["Kiltiznnrmt Kfaaovh & Xlwv Tlou"]
=> "Programming Puzzles & Code Golf"

```
> 4 votes

# Answer
## CJam, 21 bytes

```
q'[,65>__el_@+W%@@+er

```

Not an optimal solution... yet... Try it online

Its hard to explain without grouping things, so here is a general explanation: gets input, pushes uppercase alphabet twice and lowercase twice, rotates things around, combines uppercase and lowercase strings, reverses one, and uses transliteration (similar to the Retina answer).
> 3 votes

# Answer
# Jolf, 15 bytes

```
~Ai+plpu+_pl_pu
~A              I don't know what to call this, besides "dictionary replace"
  i              the input
   +plpu         previous dictionary: lower + upper alphabet
        +_p1_pu  new dictionary: reversed lower + reversed upper

```

Test suite, or try it with your own input
> 3 votes

# Answer
## Seriously, 31 bytes

```
úúû+╗úRúûR+╝,`;╜íuWD╛E(X0WX`Mεj

```

Hex Dump:

```
a3a3962bbba352a396522bbc2c603bbda1755744be452858305758604dee6a

```

Try It Online

Expl:

```
úúû+╗                             Put UPPERCASElowercase in reg0
     úRúûR+╝                      Put ESACREPPUesacrewol in reg1
            ,                     Fetch input.
             `             `Mεj   Map over the characters in string as list, joining result
              ;╜íu                Find 1-index of character in UPPERCASElowercase
                  W     0WX       If it is positive (present):
                   D              Convert back to 0-index
                    ╛E            Look it up in ESACREPPUesacrewol
                      (X          Delete the original character.
                                  (Else just leave the original character unchanged.)

```

I just realized the spec say no additional whitespace, but there is no way to suppress trailing newlines in Seriously output, so there is no Seriously solution.
> 3 votes

# Answer
# 2, 12 chars / 26 bytes (non-competitive)

```
ïĪ(ᶐ+ᶛ,ᶐᴙ+ᶛᴙ

```

`Try it here (Firefox only).`

Added transliterate function after the challenge was posted.

# Explanation

```
ïĪ(ᶐ+ᶛ,ᶐᴙ+ᶛᴙ // implicit: ï=input
ïĪ(           // transliterate ï...
   ᶐ+ᶛ,       // from uppercase+lowercase alphabet...
       ᶐᴙ+ᶛᴙ  // ... to reversed uppercase+reversed lowercase alphabet
              // implicit output

```
> 3 votes

# Answer
# C (function), 50

```
f(char*s){for(;*s;s++)*s=isalpha(*s)?*s+4^31:*s;}

```

This builds on all three previous C answers, so credit to @Ruud, @Danwakeem and @edc65.

This function modifies a char array in place.

My understanding is function entries are allowed unless explicitly banned in the question.

Try it online.
> 3 votes

# Answer
# 05AB1E, 5 bytes

```
žnžo‡

```

Uses **CP-1252** character set.

Try it online!

Explanation:

```
žn    - Push [A-Za-z]
  žo  - Push [Z-Az-a]
    ‡ - Transliterate.

```
> 3 votes

# Answer
# PostgreSQL, 118 125 bytes

```
SELECT s,TRANSLATE(s,t||UPPER(t),REVERSE(t)||REVERSE(UPPER(t)))
FROM(SELECT text'Programming Puzzles & Code Golf's,text'abcdefghijklmnopqrstuvwxyz't)r

```

`**`SqlFiddleDemo`**`

Output:

```
╔══════════════════════════════════╦═════════════════════════════════╗
║                s                 ║            translate            ║
╠══════════════════════════════════╬═════════════════════════════════╣
║ Programming Puzzles & Code Golf  ║ Kiltiznnrmt Kfaaovh & Xlwv Tlou ║
╚══════════════════════════════════╩═════════════════════════════════╝

```

Input: `SELECT text'...'s`

---

**EDIT:**

Input as table:

```
SELECT s,TRANSLATE(s,t||UPPER(t),REVERSE(t)||REVERSE(UPPER(t)))
FROM i,(SELECT text'abcdefghijklmnopqrstuvwxyz't)r
GROUP BY s,t

```

`**`SqlFiddleDemo`**`

Output:

```
╔══════════════════════════════════╦═════════════════════════════════╗
║                s                 ║            translate            ║
╠══════════════════════════════════╬═════════════════════════════════╣
║ Hello, World!                    ║ Svool, Dliow!                   ║
║ Programming Puzzles & Code Golf  ║ Kiltiznnrmt Kfaaovh & Xlwv Tlou ║
║ abcdefghijklmnopqrstuvwxyz       ║ zyxwvutsrqponmlkjihgfedcba      ║
╚══════════════════════════════════╩═════════════════════════════════╝

```
> 3 votes

# Answer
# Python 3, ~~195~~ ~~169~~ ~~168~~ 166 bytes

Thanks to @TrangOul for -2 bytes!

How didn't I see that I could have golfed that down before?

```
x=__import__('string').ascii_letters;y,z=x[26:],x[:26];a,b=y[::-1],z[::-1];print(''.join(b[z.index(i)]if i in b else a[y.index(i)]if i in a else i for i in input()))

```

(sorta) ungolfed:

```
x = __import__('string').ascii_letters;
y, z = x[26: ], x[: 26];
a, b = y[::-1], z[::-1];
print(''.join(b[z.index(i)]
    if i in b
    else a[y.index(i)]
    if i in a
    else i
    for i in input()
))

```

Try it on Ideone!
> 2 votes

# Answer
## Unix shell + tr + printf, 35 bytes

```
tr A-Za-z `printf %s {Z..A} {z..a}`

```

Here you are, a canonical answer in tr. I thought how could a question to transliterate the alphabet go without a canonical answer to **tr**ansliterate the alphabet?

tr by itself does not even do a "Hello, World!" and as such isn't a programming language, so ~~I marked the answer as noncompeting~~<sup>\[1\]</sup>.

\[1\]: Edit: Actually, *Unix shell* is the language and tr is the *standard library*. Thanks to Downgoat and Digital Trauma for helping me spot this out.
> 2 votes

# Answer
# Haskell, ~~119~~ 104 bytes

Saved 15 bytes thanks to @nimi.

```
c=fromEnum;s=toEnum;f[]="";f(x:y)|64<c x&&c x<91=s(155-c x):f y|96<c x&&c x<123=s(219-c x):f y|0<1=x:f y

```

**Usage:**

```
f "abcdefghijklmnopqrstuvwxyz"
"zyxwvutsrqponmlkjihgfedcba"

f "Programming Puzzles & Code Golf"
"Kiltiznnrmt Kfaaovh & Xlwv Tlou"

f "Hello, World!"
"Svool, Dliow!"

```

**Explanation**

```
let c=fromEnum;s=toEnum;--wrap names for later use, fromEnum gets ascii code from char, toEnum gets char from ascii code
f[]=[];                 --feed empty list (of chars in this case), get empty list
f(x:y)                  --feed a list, separate the first element and...
|64<c x&&c x<91=        --if its an uppercase char (using ascii code range)...
s(c x*(-1)+155)         --  inverse its ascii code value, move it to the range of uppercase and get the new char
                        --  (like rotating half turn a ruler by the side and then sliding it to the space it previously occupied)
:f y                    --  feed the rest of the list and stick the new char in front of the result
|96<c x&&c x<123=       --if its a lowercase char (using ascii code range)...
s(c x*(-1)+219)         --  inverse its ascii code value, move it to the range of lowercase and get the new char
:f y                    --  feed the rest of the list and stick the new char in front of the result
|True=x:f y             --otherwise feed the rest of the list and stick the char in front of the result

```

I'm new to Haskell... to functional programming... and to the site, and i know there are (a lot of) better answers to this question, but bear with me.
> 2 votes

# Answer
# Perl 6, 28 bytes

```
{S:g/\w/{chr $/.ord+4+^31}/}

```

### Usage:

```
# give it a lexical name
my &swap = { … }

say swap 'Programming Puzzles & Code Golf';
# Kiltiznnrmt Kfaaovh & Xlwv Tlou

say swap ('a'..'z').join
# zyxwvutsrqponmlkjihgfedcba

```
> 2 votes

# Answer
## Java, 136 bytes

```
void x(String i){for(char c:i.toCharArray()){if(Character.isLetter(c))c=c<91?(char)(90-(c-65)):(char)(122-(c-97));System.out.print(c);}}

```

Example usage:

```
class Test {
  static void x(String i){for(char c:i.toCharArray()){if(Character.isLetter(c))c=c<91?(char)(90-(c-65)):(char)(122-(c-97));System.out.print(c);}}
  public static void main(String[] args) {
    x("Programming Puzzles & Code Golf");
    // produces "Kiltiznnrmt Kfaaovh & Xlwv Tlou"
  }
}

```

Probably the worst commonly-used language in terms of byte size.
> 2 votes

# Answer
## Python 3, ~~164~~ 159 bytes

```
def f(t,a="abcdefghijklmnopqrstuvwxyz",b=""):
 for c in t:u=64<ord(c)<91;c=c.lower();c=a[::-1][a.index(c)] if c in a else c;b+=c.upper() if u else c
 return b

```
> 2 votes

# Answer
# PHP, 73 bytes

```
<?=strtr($argv[1],($b=strtolower($a=join(range(A,Z)))).$a,strrev($a.$b));

```

do this need any comments?
> 2 votes

# Answer
# Perl 5, ~~28~~ 25 bytes

24 bytes of code + 1 for `-p`

```
s/\pL/chr(4+ord$&^31)/ge

```

Try it online!
> 2 votes

# Answer
# PowerShell, 65 bytes

```
-join($args|% t*y|%{[char]($_,(($_-bxor31)-4))[$_-match'[a-z]']})

```

Try it online!
> 2 votes

# Answer
# Husk, 22 bytes

```
σ…'A'Z…'Z'Aσ…'a'z…'z'a

```

Try it online!
> 2 votes

# Answer
# C, ~~112~~ 98 bytes

```
i;main(){char x[99];gets(x);for(;x[i];i++)if(isalpha(x[i]))x[i]=(x[i]>90?219:155)-x[i];puts(x);}

```

I know that `gets()` is deprecated and unsafe, but `scanf()` doesn't accept whitespace and I need to include `stdio.h` if I want to `fgets` (since `stdin` is defined in `stdio.h`). I assume this program wouldn't work if the user tried to enter a string more than `99` characters.

EDIT: Changing `printf("%s",x)` to `puts(x)` saves `7` bytes and changing `i<strlen(x)` to `x[i]` saves another `7` bytes.
> 2 votes

# Answer
# Vyxal, 5 bytes

```
kBklĿ

```

Try it Online!

Explanation:

```
kB     # Constant 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
  kl   # Constant 'ZYXWVUTSRQPONMLKJIHGFEDCBAzyxwvutsrqponmlkjihgfedcba'
    Ŀ  # Transliterate a(b -> c)
       # Implicit output

```
> 2 votes

# Answer
# MATL, 21 ~~28~~ bytes

Uses version 6.0.0, which is earlier than this challenge. The code runs in Octave.

```
jttk2Y2mXK)o31Z~4-cK(

```

### Example

```
>> matl
 > jttk2Y2mXK)o31Z~4-cK(
 >
> Hello, World!
Svool, Dliow!

```

### Explanation

```
j             % input string
t             % duplicate
tk            % duplicate and convert to lowercase
2Y2           % string 'abc...xyz'
m             % "ismember" function: produces logical index of letter positions
XK            % copy to clipboard K
)             % index into string to get its letters
o31Z~4-       % bitwise XOR with 31 and subtract 4
c             % convert to char
K             % paste logical index from clipboard K
(             % put back modified letters into original string

```

### Old approach, 28 bytes

```
j1Y2!tkh"t@2#m@0v27b-)wXK)K(

```
> 1 votes

# Answer
# Brachylog, 66 bytes

```
_|hH(:64>:91<,77-H+78=X;H:96>:123<,109-H+110=X;HX),[X]:"~c"w,?b:0&

```

The lack of built-ins really hurts here, so we have to resort to good old ASCII codes computations.

The predicate `brachylog_main` expects a character codes string as input and no output, e.g. `brachylog_main(`Hello, World!`,_).`

### Explanation

```
_                                                                  § If the input is empty,
                                                                   § return true
                                                                   §
 |                                                                 § Else
                                                                   §
  hH(                                            ),[X]:"~c"w       § Print variable X which
                                                                   § depends on the head of
                                                                   § the input as a char code
                                                                   §
                                                            ,?b:0& § Recursive call on the
                                                                   § tail of the input
                                                                   §
     :64>:91<,77-H+78=X                                            § If H is capital, X =
                                                                   § 77 - H + 78
                       ;                                           § Else if H is non-cap, X=
                        H:96>:123<,109-H+110=X                     § 109 - H + 110
                                              ;                    § Else (not a letter)
                                               HX                  § H = X

```
> 1 votes

# Answer
# MATLAB, 61 bytes

```
@(x)[abs(-x+ismember(x,65:90)*155+ismember(x,97:122)*219),'']

```

I tried `f=@ismember`, and making the range `a=65:90` a variable and do `32+a` in the second `ismember`-call. All this shortened the code, but would result in a program and thus require both `disp` and `input`.

This gives:

```
ans('Hello, World!')
ans =
Svool, Dliow!

ans('Programming Puzzles & Code Golf')
ans =
Kiltiznnrmt Kfaaovh & Xlwv Tlou

```
> 1 votes

# Answer
# Python 2, 104 bytes

Pretty simple using `str.translate` and `string.maketrans`.

```
from string import*
u=ascii_uppercase
l=u.lower()
f=lambda x:x.translate(maketrans(u+l,u[::-1]+l[::-1]))

```

**Try it online**

This last line would also work, since `string` is imported:

```
f=lambda x:translate(x,maketrans(u+l,u[::-1]+l[::-1]))

```
> 1 votes

# Answer
# Perl 6, ~~40~~ 39 bytes

Since everyone else is doing anonymous functions:

```
my &f=*.trans(/\w/=>{chr $/.ord+4+^31})

```

(Thanks @b2gills for the tip)

Uses the same bit flipping voodoo as some of the other posts. I wasn't sure whether to include the variable/function declaration in the byte count, so I did just in case. Without it this solution is only 34 bytes.

Usage:

```
> f "zyxwvutsrqponmlkjihgfedcba"
abcdefghijklmnopqrstuvwxyz
> f "Kiltiznnrmt Kfaaovh & Xlwv Tlou"
Programming Puzzles & Code Golf
> f "Svool, Dliow!"
Hello, World!

```
> 1 votes

# Answer
# Oracle SQL 11.2, 105 bytes

```
SELECT TRANSLATE(:1,a||UPPER(a),REVERSE(UPPER(a)||a))FROM(SELECT'abcdefghijklmnopqrstuvwxyz'a FROM DUAL);

```
> 1 votes

# Answer
# Factor, 92 bytes

```
[ [ 65 90 [a,b] dup >lower 2dup [ reverse ] bi@ append -rot append zip >hashtable at ] map ]

```

An anonymous function. Making it case insensitive is... expensive.
> 1 votes

# Answer
# PHP, 69 bytes

```
while(""<$c=$argv[1][$i++])echo ctype_alpha($c)?chr(ord($c)+4^31):$c;

```

mapping stolen from ETHproductions
> 1 votes

# Answer
# 05AB1E, 5 bytes

```
žižk‡

```

Try it online!

```
       # Push input.
 ži    # Push [a-zA-Z]
   žk  # Push [z-aZ-A]
     ‡ # Transliterate a#(b -> c)

```
> 1 votes

# Answer
## Racket 332 bytes

```
(let p((l(map char->integer(string->list s)))(ol'())(g(λ(n a b)(and(> n a)(< n b))))(t first)(c cons))
(cond[(empty? l)(list->string(map integer->char(reverse ol)))][(and(not(g(t l)96 123))(not(g(t l)64 91)))(p(rest l)(c(t l)ol)g t c)]
[(>(t l)95)(p(rest l)(c(- 122(-(t l)97))ol)g t c)][else(p(rest l)(c(- 90(-(t l)65))ol)g t c)]))

```

Ungolfed:

```
(define(f s)
  (let p ((l (map char->integer (string->list s)))
             (ol '())
             (g (λ (n a b) (and (> n a) (< n b))))
             (t first)
             (c cons))
    (cond
      [(empty? l)
       (list->string (map integer->char (reverse ol)))]
      [(and(not (g (t l) 96 123)) (not(g(t l) 64 91)))
       (p (rest l) (c (t l) ol) g t c)]
      [(> (t l) 95)
       (p (rest l) (c (- 122 (- (t l) 97)) ol) g t c)]
      [else
       (p (rest l) (c (- 90 (- (t l) 65)) ol) g t c)]
      )))

```

Testing:

```
(f "abcdefghijklmnopqrstuvwxyz")
(f "Programming Puzzles & Code Golf")
(f "Hello, World!")

```

Output:

```
"zyxwvutsrqponmlkjihgfedcba"
"Kiltiznnrmt Kfaaovh & Xlwv Tlou"
"Svool, Dliow!"

```
> 1 votes

# Answer
# C#, 234 Bytes

Golfed:

```
string A(string s){string a="abcdefghijklmnopqrstuvwxyz",z=string.Concat(a.Reverse()),o="";s.ToList().ForEach(c=>o+=!z.Contains(char.ToLower(c))?c:char.IsLower(c)?z[a.IndexOf(c)]:char.ToUpper(z[a.IndexOf(char.ToLower(c))]));return o;}

```

Ungolfed:

```
public string A(string s)
{
  string a = "abcdefghijklmnopqrstuvwxyz",
    z = string.Concat(a.Reverse()), o = "";
  s.ToList().ForEach(c => o += !z.Contains(char.ToLower(c)) ? c :
  char.IsLower(c) ? z[a.IndexOf(c)] :
  char.ToUpper(z[a.IndexOf(char.ToLower(c))]));
  return o;
}

```

Testing:

```
Console.WriteLine(new Atbash().A("Programming Puzzles & Code Golf"));
Kiltiznnrmt Kfaaovh & Xlwv Tlou

Console.WriteLine(new Atbash().A("Hello, World!"));
Svool, Dliow!

```
> 1 votes

# Answer
# Jelly, 11 bytes

```
ØAµ,Uµ;Œsðy

```

Try it online!
> 1 votes

# Answer
# Common Lisp, 110 bytes

```
(lambda(s)(map-into s(lambda(x)(if(alpha-char-p x)(code-char(-(if(upper-case-p x)155 219)(char-code x)))x))s))

```

Try it online!

Very straightforward solution.
> 1 votes

# Answer
# Wolfram Language (Mathematica), 114 bytes

```
(a=Alphabet[];b=Capitalize/@a;r:=Reverse;u=AssociationThread[a~Join~b->r@a~Join~r@b];StringJoin[Characters@#/.u])&

```

Try it online!
> 1 votes

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

```
{x^'![t,_t;(|t),|_t:`c$65+!26]x}

```

Try it online!

Builds a dictionary mapping the letters to their "reverses", filling any non-letter character with what was in the input.

* `t:`c$65+!26` build a list of the letters from `"A"` through `"Z"`, storing in `t`
* `![t,_t;(|t),|_t:...]` build a dictionary mapping the letters to their reverses
* `x^'![...]x` index into that dictionary with the input. non-letter characters in the input get replaced with `" "`'s, so replace those spaces with whatever was in the input

# k4, 24 bytes

```
{x^![|,/|l;,/l:.Q`a`A]x}

```

Similar to the above, but benefits from using the built-in lists of characters; `.Q.A` for uppercase letters, and `.Q.a` for the lower case ones.
> 1 votes

# Answer
## CJam, 33 bytes

```
q['a{_)}25*]_eu+['z{_(}25*]_eu+er

```

Explanation:

```
q                   e# Read all input an put string to the stack
[                   e# Start array (char)
    'a              e# Put 'a' char to the stack
    {               e# Begin of code block
        _           e# Duplicate top element on the stack
        )           e# Increment the duplicate
    }               e# End of code block
    25*             e# Repeat code block 25 times
]                   e# End array
_                   e# Duplicate array
eu                  e# Uppercase the duplicate
+                   e# And join arrays
['z{_(}25*]_eu+     e# Repeat the same thing back from Z
er                  e# Replace A-z with z-A in the input

```
> 0 votes

# Answer
# Python 3, 141 bytes

Similar to @cat, but uses a `dict` to map letters and uses a simpler comprehension for the print:

```
a=__import__('string').ascii_letters;l,u=a[:26],a[26:];m=dict(zip(a,l[::-1]+u[::-1]));print(''.join(m[c] if c in a else c for c in input()))

```

Ungolfed:

```
a = __import__('string').ascii_letters; # import alphabet
l, u = a[:26],a[26:];                   # separate lower/uppercase
m = dict(zip(a, l[::-1] + u[::-1]));    # create map a-z+A-Z -> z-a+Z-A
print(''.join(m[c] if c in a else c     # if input char in map, map it
                   for c in input()))   # otherwise leave it alone

```
> 0 votes

# Answer
# JavaScript ES6, 96 bytes

```
var R=i=>i.replace(/[A-z]/g,s=>String.fromCharCode(155-s.charCodeAt(0)+(/[a-z]/.test(s)?64:0)))

```

Not as good as the other JavaScript answer, but I thought I'd try myself.
> 0 votes

# Answer
## REXX, 88 bytes

```
b=xrange(a,z)
a=lower(b)
do forever
  parse pull n
  say translate(n,reverse(b||a),a||b)
end

```
> 0 votes

# Answer
# JavaScript, 57 bytes

```
s=>{var k;for(var a=s.length-1;a>0;a--){k+=s[a]}return k}

```
> 0 votes

# Answer
## Mathematica 89 Bytes

```
StringReplace[#,Thread[#~Join~#3@#->#2@#~Join~#2@#3@#]&[Alphabet[],Reverse,ToUpperCase]]&

```

48 Bytes of this is just long function names
> 0 votes

# Answer
# Lua, 116 bytes

```
t={}for i=65,90 do a=('').char(i)b=a.char(155-i)t[a],t[a:lower()]=b,b:lower()end print((io.read"*all"):gsub("%a",t))`

```
> 0 votes

# Answer
# Python3

This is my first post on Code Golf; but I think I understood your question successfully;

This python3 code replaces abc -\> xyz (as you specified above)

```
def ASUB(m,A,B):o = m.maketrans(A,B);r = m.translate(o);return(r);
ASUB(m="Programming Puzzles & Code Golf",
     A="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
     B="zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA")
#'Svool, Dliow!'
#'Kiltiznnrmt Kfaaovh & Xlwv Tlou'

```

the output of the both messages (Hello, World! and the other one) is in # comments

**EDIT: Thanks for clarifying caird coinheringaahing!**

Improved:

```
def A(m):o=m.maketrans("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ","zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA");return m.translate(o);

```
> 0 votes

# Answer
# Jelly, 8 bytes

```
ØẠŒsU,Ɗy

```

Try it online!

## How it works

```
ØẠŒsU,Ɗy - Main link. Takes S on the left
ØẠ       - Yield "ABC...XYZabc...xyz"
      Ɗ  - Last three links as a monad f("ABC...XYZabc...xyz"):
  Œs     -   Swapcase
    U    -   Reverse
     ,   -   Pair
       y - Translate S by this mapping

```
> 0 votes

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


title: Plz Halp, Need Investors ASAP

text:
# Question
Title: Plz Halp, Need Investors ASAP
Bob has a startup that is developing a product that uses “advanced AI” and “black magic” to automatically code-golf computer programs. Unfortunately, Bob is running out of cash and desperately needs money from investors to keep his company running. Each investor that Bob has contacted wishes to schedule a meeting with a certain start and end time. However, some of meeting times conflict with each other. Bob wishes to meet with as many investors as possible so he can raise the largest amount of money. How many investors can Bob meet with, given that Bob can only meet with one investor at a time?

## Input Format

Input is given as an array of pairs (or the equivalent in your chosen language). Each pair p represents one investor, where `p[0]` is the start time of the investor’s meeting and `p[1]` is the end time.

For example, in the test case `[(0,10),(5,10),(12,13)]`, there are three investors: one who wants to meet from time 0 to time 10, one who wants to meet from time 5 to time 10, and one who wants to meet from time 12 to time 13. Meetings will always have a positive duration, and a meeting that ends at time `k` does not conflict with a meeting that starts at time `k`.

You may use any reasonable I/O method for input.

## Test Cases

```
[(0,10),(5,10),(12,13)] => 2 (investors 1 and 3)

[(10,20),(10,20),(20,30),(15,25)] => 2 (investors 1 and 3)

[(0,3),(1,5),(1,5),(1,5),(4,9),(6,12),(10,15),(13,18),(13,18),(13,18),(17,19)] => 4 (investors 1,5,7 and 11)

[(1,1000),(1,2),(2,3),(3,4),(4,5),(5,6),(6,7)] => 6 (every investor except the first)

[(1,2),(101,132),(102,165),(3,9),(10,20),(21,23),(84,87)] => 6 (investors 1,2,4,5,6,7)

```

## Output

Your program should output an integer, the maximum number of investors that Bob can meet with.

Standard loopholes are prohibited. This is , so the shortest solution in each language wins.

# Answer
# Python 2, ~~53~~ 52 bytes

Based on xnor's answer.
-1 byte thanks to dingledooper!

```
f=lambda l,t=0:-min([a<t or~f(l,b)for a,b in l]+[0])

```

Try it online!

This is a recursive function which takes 2 arguments:

* `l`: a list of all offered meetings
* `t`: the time our last meeting ended (initially 0)

The list comprehension iterates over all offered meetings `(a, b)`.
If the meeting starts before our last meeting ended (`a<t`), `a<t or ...` evaluates to `True`, which is basically the same as `1` in Python.
Otherwise `f(l,b)` is called to see how much more meetings we can fit in if we take the current meeting. The bitwise inverted value of this gets into the list.

If `a<t` was false for any meeting `(a, b)` in the comprehension, `min` returns the smallest of all possible `~f(l,b)` values. Then `-min(...)` returns `-~f(l,b)==1+f(l,b)` for some meeting.
Otherwise `-min(...)` is equal to `0`.

---

47 bytes if we can assume that the input is not empty:

```
f=lambda l,t=0:1-min(a<t or-f(l,b)for a,b in l)

```

Try it online!
> 16 votes

# Answer
# Wolfram Language (Mathematica), 49 bytes

```
If[#==0m,1,1+#0[#.m]]&[m=Boole[#>=#2&~Outer~##]]&

```

Try it online!

Input `[{starting times}, {ending times}]`.

Finds the least power `n` such that \\$M^n=\mathbf{0}\\$, where `M` is an adjacency matrix representing possible next meetings.
> 14 votes

# Answer
# Python 2, 54 bytes

```
f=lambda l,t=0:max([1+f(l,b)for a,b in l if a>=t]+[0])

```

Try it online!
> 10 votes

# Answer
# , 43 36 35 bytes

```
1#@}.(#~0{]>://&.|:@/:{:"1) ::]^:a:

```

Try it online!

Uses greedy algorithm. Probably more to golf....

## orig brute force, 43 bytes

```
[:>./(2#:@i.@^#)(#*;-:~.@;)@#<@([+i.@-~)/"1

```

Try it online!
> 7 votes

# Answer
# Jelly, 8 bytes

```
<þ¬æ×Ƭ`L

```

```
<þ¬æ×Ƭ`L
<þ        outer product less than
  ¬       negate (outer product greater than or equal to)
   æ×     matrix multiply
     Ƭ`   apply until converged using itself as the left argument
       L  length

```

Uses the method from the mathematica answer https://codegolf.stackexchange.com/a/224523/95516 go upvote that!

Try it online!
> 6 votes

# Answer
# Ruby, 42 bytes

```
f=->a,b=0{a.map{|c,d|c<b ?0:-~f[a,d]}.max}

```

Try it online!

This answer is heavily inspired by xnor's python answer.
> 5 votes

# Answer
# Charcoal, 22 bytes

```
Ｗ⌊ΦＥθ⮌κ¬‹⊟κ∨⌈υ⁰⊞υ⊟ιＩＬυ

```

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

```
Ｅθ⮌κ

```

Reverse each investor meeting, so that the end time comes first and the start time second.

```
Φ...¬‹⊟κ∨⌈υ⁰

```

Destructively compare the start times with the latest end time so far, returning just the possible end times of the next meeting.

```
Ｗ⌊

```

Take the earliest such time, if any. While it exists:

```
⊞υ⊟ι

```

Push that earliest ending time to the predefined empty list.

```
ＩＬυ

```

Output the number of meetings in the list.
> 4 votes

# Answer
# Pari/GP, 164 bytes

Exponential time. Am I proud of myself? No.

```
c(v)=if(#v>1,(sum(i=2,#v,(v[1][1]<v[i][2])&&(v[1][2]>v[i][1]))+c(v[^1])),0)
p(v)=vector(2^#v-1,i,vecextract(v,i))
m(v)=vecmax(vector(2^#v-1,i,#p(v)[i]*!c(p(v)[i])))

```

Try it online!
> 4 votes

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

```
g=(a,e,m)=>a.map(([S,E])=>m=S<e|E>m?m:E)|m&&g(a,m)+1

```

Try it online!

Greedy join meetings that ends earliest.
> 3 votes

# Answer
# Retina 0.8.2, 56 bytes

```
\d+
$*
O^$`1*,(1+)
$1
^
¶
+m`^(1*)(¶.*\1,(1+))
¶$3$2
\G¶

```

Try it online! Link includes test cases. Takes `;`-delimited meetings. Explanation:

```
\d+
$*

```

Convert to unary.

```
O^$`1*,(1+)
$1

```

Sort by descending meeting end.

```
^
¶

```

Insert a marker for the latest meeting end so far.

```
+m`^(1*)(¶.*\1,(1*))
¶$3$2

```

Repeatedly match the meeting with the earliest end whose start is not before the latest meeting end so far, update the latest meeting end, and keep track of the number of meetings.

```
\G¶

```

Convert the number of meetings to decimal.
> 3 votes

# Answer
# Python 2, ~~145~~, ~~143~~, 142 bytes

Saved **2 bytes** thanks to Wasif pointing out that I didn't need to assign the `lambda` function to a variable.

```
lambda t:max(all(min(e,y)<=max(s,x)for(x,y),(s,e)in k(p,2))*len(p)for r in range(len(t))for p in k(t,r))
from itertools import*
k=combinations

```

Try it online!

Brute force approach. The program uses list comprehension to iterate through the powerset of the meetings.
> 2 votes

# Answer
# , 85 bytes

```
f=function(m)`if`((s=sum(m|1))<3,s|1,max(1+f(m[,m[1,]>=m[2]|m[2,]<=m[1]]),f(m[,-1])))

```

Try it online!

Input is matrix with start times in row 1 and end times in row 2.

**How?**

```
how_many_meetings=
f=function(m){                          # f = recursive function, m = input matrix
 if((s=sum(m|1))<3)return(s|1)          # if there's only one or zero investors in the matrix, return that number,
 else{                                  # otherwise
   return(max(                          # return the max of
     1+f(m[,m[1,]>=m[2]|m[2,]<=m[1]]),  # 1 (the first investor in the matrix) + recursive call with
                                        # all investors in the matrix that don't overlap with him/her,
     f(m[,-1]))                         # or just a recursive call without the first investor in the matrix
   )
 }
}

```
> 2 votes

---
Tags: code-golf
---


# Question
Title: An Array of Challenges #3: Moving Averages
*Note: This is #3 in a series of challenges. For the previous challenge, click here.*

# Moving Average of a List

> The **moving average** of a list is a calculation resulting in a new, smoothed out list, created by averaging small overlapping sublists of the original.

When creating a moving average, we first generate the list of overlapping sublists using a certain 'window size', shifting this window to the right once each time.

For example, given the list `[8, 4, 6, 2, 2, 4]` and the window size `3`, the sublists would be:

```
[8,  4,  6,  2,  2,  4]          Sublists:
(         )                  <-  [8, 4, 6]
    (         )              <-  [4, 6, 2]
        (         )          <-  [6, 2, 2]
            (         )      <-  [2, 2, 4]

```

We then calculate the **mean average** of each sublist to obtain the result: `[6.0, 4.0, 3.3, 2.7]` (each value rounded to one decimal place).

---

# The Challenge

Your task is to write a program or function which, given a list **L**, and an integer **1 ≤ n ≤ length(L)**, calculate the moving average for **L** using the window size **n**.

**Rules:**

* Your program may use integer division *or* float division. In the case of float division, small inaccuracies due to the data type's limitations are permitted, as long as the value is otherwise correct.
* You may submit a full program, or a function (but not a snippet).
* You may assume that the list will only contain **positive integers**.
* Standard loopholes are forbidden.
* **This is , so the shortest answer (in bytes) wins!**

---

# Test Cases

Note that, for ease of readability, all values are rounded to one decimal place.

```
n=5, [1, 2, 3, 4, 5, 6, 7, 8]      ->      [3, 4, 5, 6]
n=3, [100, 502, 350, 223, 195]     ->      [317.3, 358.3, 256]
n=1, [10, 10, 10]                  ->      [10, 10, 10]
n=3, [10, 20, 30]                  ->      [20]
n=2, [90, 40, 45, 100, 101]        ->      [65, 42.5, 72.5, 100.5]

```

# Answer
# Dyalog APL, 4 bytes

*1 byte saved thanks to @Graham*

*2 bytes saved thanks to @jimmy23013*

Did I mention APL is **not** a golfing language?

```
⊢+/÷

```

with `n` on the right, or

```
+/÷⊣

```

with `L` on the right.

Try it online!

**How?**

`÷` \- divide `L` by `n`

`⊢+/` \- reduce `+` on windows of `n`
> 8 votes

# Answer
# Jelly, 3 bytes

```
ṡÆm

```

Try it online!

Pretty simple thanks to

## How it works

```
ṡÆm - Main dyadic link. Arguments: l (list) and n (integer)
ṡ   - Split l into sublists of length n
 Æm - Mean of each

```
> 7 votes

# Answer
# Wolfram Language (Mathematica), 13 bytes

Mathematica has a built-in for everything

```
MovingAverage

```

Try it online!

Takes a list and then a radius...
> 7 votes

# Answer
# Haskell, 47 bytes

```
n!a|length a<n=[]|_:t<-a=div(sum$take n a)n:n!t

```

Try it online!

Saved two bytes thanks to xnor!
> 7 votes

# Answer
# Python, 48 bytes

```
f=lambda n,l:l[n-1:]and[sum(l[:n])/n]+f(n,l[1:])

```

Try it online!

A recursive function. Shorter than the program (50 bytes)

```
n,l=input()
while l[-n]:print sum(l[:n])/n;l=l[1:]

```

Try it online!

This saves 2 bytes by terminating with error on the `while` condition.
> 6 votes

# Answer
# Enlist, 3 bytes

```
ṡÆm

```

Try it online!
> 4 votes

# Answer
# Perl 6, 33 bytes

```
{@^a.rotor($^b=>1-$b)».sum X/$b}

```

Test it

## Expanded:

```
{  # bare block with placeholder parameters ｢@a｣, ｢$b｣

  @^a                # declare and use first param

  .rotor(            # split it into chunks
    $^b              # declare and use second param
    =>               # pair it with
    1 - $b           # one less than that, negated

  )».sum             # sum each of the sub lists

  X/                 # cross that using &infix:«/»

  $b                 # with the second param
}

```
> 4 votes

# Answer
# C,  ~~86~~   ~~84~~  83 bytes

```
i,j,s;f(a,l,n)int*a;{for(i=-1;i+++n<l;s=!printf("%d ",s/n))for(j=n;j--;)s+=a[i+j];}

```

Try it online!

**Unrolled:**

```
i, j, s;
f(a, l, n)int*a;
{
    for(i=-1; i+++n<l; s=!printf("%d ", s/n))
        for(j=n; j--;)
            s += a[i+j];
}

```
> 4 votes

# Answer
# Ohm v2, 3 bytes

```
ÇÆm

```

Try it online!

Explanation:

```
ÇÆm  Main wire, arguments l (list) and n (integer)

Ç    All consecutive sublists of l with length n
 Æm  Arithmetic mean of each sublist

```
> 4 votes

# Answer
# J, ~~7~~ 5 bytes

```
]+/\%

```

Try it online!

Takes `n` as the right argument and the list as the left. Credit to Uriel's solution for the idea of doing only the summation in the infix.

### Explanation

```
]+/\%
    %  Divide list by n
]+/\   Sum on overlapping intervals of size n

```

### Previous solution (7 bytes)

```
(+/%#)\
      \  Apply to overlapping intervals of size n
(+/%#)   Mean
 +/        Sum
   %       Divided by
    #      Length

```
> 4 votes

# Answer
# Pyth, 5 bytes

```
.O.:F

```

**Try it here!**

## How this works

```
.O.:F  - Full program.

    F  - Reduce the input (nested list) with...
  .:   - ... Sublists.
.O     - Average of each.

```
> 3 votes

# Answer
# Octave, ~~33~~ 31 bytes

```
@(x,n)conv(x,~~(1:n)/n,'valid')

```

**Try it online!**

### Explanation

Convolution (`conv`) is essentially a moving weighted sum. If the weights are chosen as `[1/n, ..., 1/n]` (obtained as `~~(1:n)/n`) the result is a moving average, of which only the `'valid'` part is kept.
> 3 votes

# Answer
# Python 3, 55 bytes

```
lambda n,A:[sum(A[j:n+j])/n for j in range(-n-~len(A))]

```

Try it online!
> 2 votes

# Answer
# 05AB1E, 5 bytes

```
ŒsùÅA

```

Explanation:

```
Œ     All substrings
 sù   Keep those only where the length is equal to <the second input>
   ÅA Arithmetic mean of each element in the resulting array.

```

Try it online!
> 2 votes

# Answer
# Japt v2.0a0, 7 bytes

```
ãV ®x÷V

```

Try it

---

## Explanation

Implicit input of array `U` and integer `V`.

```
ãV

```

Get subsections of `U` with length `V`

```
®

```

Map over the subsections.

```
÷V

```

Divide each element by `V`.

```
x

```

Sum all elements.
> 2 votes

# Answer
# , 72 bytes

```
function(l,n)(k=sapply(0:sum(l|1),function(x)mean(l[x+1:n])))[!is.na(k)]

```

Try it online!

Computes the `mean` of all the size `n` windows; when the window goes past the edge of `l`, the results are `NA` so we filter them out.

# R + zoo package, 13 bytes

```
zoo::rollmean

```

The `zoo` package (S3 infrastructure for Regular and Irregular Time Series) has a lot of handy functions. You may try it here (R-fiddle).
> 2 votes

# Answer
# Factor \+ `math.extras`, 14 bytes

```
moving-average

```

Try it online!

Built-in.

---

# Factor, 22 bytes

```
[ clump [ mean ] map ]

```

Try it online!

## Explanation:

A non-trivial answer. It's a quotation (anonymous function) that takes a sequence and an integer from the data stack as input and leaves a sequence on the data stack as output.

* `clump` Split a sequence into groups of `n` with overlapping. This creates the moving window.
* `[ mean ] map` Map each window to its mean.
> 2 votes

# Answer
# Python 3, 61 bytes

```
lambda l,n:[sum(e)/n for e in zip(*[l[i:]for i in range(n)])]

```

Try it online!
> 1 votes

# Answer
# Mathematica, 21 bytes

```
Mean/@##~Partition~1&

```

Try it online!

-3 bytes JungHwan Min
> 1 votes

# Answer
# Proton, 46 bytes

```
n=>l=>[sum(l[h to h+n])/n for h:0..len(l)-n+1]

```

Try it online!

Note that this takes input via currying functions syntax, and returns a list of fractions.
> 1 votes

# Answer
# Jq 1.5, 61 bytes

```
def f(N;L):[L|range(0;1+length-N)as$i|.[$i:$i+N]|add/length];

```

Expanded

```
def f(N;L):
  [   L
    | range(0;1+length-N) as $i        # generate
    | .[$i:$i+N]                       # sublists
    | add/length                       # compute mean
  ];

```

Try it online!
> 1 votes

# Answer
# CJam, ~~14~~ 12 bytes

 -2 bytes thanks to @aditsu

```
{_@ew::+\f/}

```
> 1 votes

# Answer
# x86 Machine Code, 20 bytes

```
86 89 D9 31 C0 03 44 8F FC E2 FA 31 D2 F7 F3 AB 39 F7 72 ED C3

```

The above bytes define a function that calculates the moving average of a list, modifying the elements of the list in-place. It assumes that the list is a contiguous array of integer elements. The function takes the following inputs in registers

* `edi`: the address of the first element in the list (*i.e.*, a pointer to the beginning of the array)
* `esi`: the address of the element following the last element in the list (*i.e.*, a pointer to one past the end of the array)
* `ebx`: the size of the window (*i.e.*, number of elements to consider in each window)

This is a custom calling convention, which is common when writing machine/assembly language functions. All averaging operations are done internally in integer mode, as provided for by the challenge.

The input array, bounded by the addresses specified as `edi` and `esi`, is modified in-place by the function: the first *n* elements are replaced with the corresponding moving average. Thus, the caller just discards all but the first *n* elements.

**Try it online!**

Here are the ungolfed assembly mnemonics:

```
MovingAverage:
; Inputs:
;    edi = &array[0]
;    esi = &array[N]
;    ebx = cWindow
; Outputs:
;    array is modified in-place, starting from the beginning
; Clobbers:
;    eax, ecx, edx, edi, flags
              OuterLoop:
89 D9            mov    ecx, ebx
31 C0            xor    eax, eax
              InnerLoop:
03 44 8F FC      add    eax, DWORD PTR [edi + ecx * 4 - 4]
E2 FA            loop   InnerLoop
31 D2            xor    edx, edx
F7 F3            div    ebx
AB               stos ; DWORD PTR [edi], eax; sub edi, 4
39 F7            cmp    edi, esi
72 ED            jb     OuterLoop
C3               ret

```

The assembly code should be pretty self-explanatory, although I hope sufficiently clever! The code basically just runs two loops. The outer loop iterates through the entire array, one element at a time. The inner loop starts at the current element, iterates through the length of the window, and computes the sum. After the inner loop, the sum is used to compute the average (simple division by the window size), and then the resulting moving average for that "sublist" is written back into the original array at the current index.

Very few notable "tricks" here. Of mention:

* Cleverly choosing the calling convention allows significant savings with the elision of unnecessary `MOV` instructions. (Of course, that burden is transferred onto the caller, but they're not playing code golf!)
* The string instruction, `STOSD`, is used to save a large number of bytes; encoded with only 1 byte, it writes the contents of the `eax` register back to the memory location contained in `edi`, while simultaneously incrementing `edi` by 4 bytes to contain the location of the next element.
* The `LOOP` instruction (which does a combined decrement of `ecx` and loop if its new value is not equal to 0) is used to save a couple of bytes.
> 1 votes

# Answer
## JavaScript (ES6), 53 bytes

```
(l,n)=>l.map(e=>(s+=e-=a[i-n]||0)/n,s=i=0).slice(n-1)

```
> 0 votes

# Answer
# PHP, 94 bytes

```
function f($l,$n){while($i<=count($l)-$n)$r[]=array_sum(array_slice($l,$i++,$n))/$n;return$r;}

```

Try it online!
> 0 votes

# Answer
# K (oK), ~~13~~ 11 bytes

**Solution:**

```
{+/+x':y%x}

```

Try it online!

**Examples:**

```
{+/+x':y%x}[3;8 4 6 2 2 4]
6 4 3.3333 2.6667
{+/+x':y%x}[5;1 2 3 4 5 6 7 8]
3 4 5 6

```

**Explanation:**

`oK` has a built-in for creating a sliding window, then sum up resulting arrays and divide by sliding window size to get mean:

```
{+/+x':y%x} / the solution
{         } / lambda function taking x and y as implicit parameters
       y%x  / y (list) by x (sliding array size)
    x':     / sliding window of size x over list y
   +        / flip array (rotate by 90 degrees)
 +/         / sum up array

```
> 0 votes

# Answer
# Clojure, 48 bytes

```
(fn[n a](map #(/(apply + %)n)(partition n 1 a)))

```

Try it online!
> 0 votes

# Answer
# DataWeave, 50 bytes

```
fun s(l,w)=0 to(sizeOf(l)-w)map avg(l[$ to $+w-1])

```

```
%dw 2.0
output application/json

fun sma(list: Array<Number>, window: Number) =
  0 to (sizeOf(list) - window)  // generate starting indices of sublists
  map list[$ to $ + window - 1] // generate sublists
  map avg($)                    // calculate averages

---
sma([90, 40, 45, 100, 101], 2)

```
> 0 votes

# Answer
# Stacked, 22 bytes

```
[infixes[:sum\#'/]map]

```

Try it online!

## Explanation

`infixes` generates all the windows of the given length. Then, we map our own average function over each infix.
> 0 votes

# Answer
# Common Lisp, 77 bytes

```
(defun f(x y)(if(>=(length x)y)(cons(/(apply'+(subseq x 0 y))y)(f(cdr x)y))))

```

Try it online!
> 0 votes

# Answer
# Funky, ~~67~~ 66 bytes

*Saved a byte with curry syntax.*

```
n=>t=>{k={}fori=0i<=(#t)-n i++k[i]=(forj=c=0c<n c++j+=t[i+c])/n k}

```

Try it online!
> 0 votes

# Answer
# Java 8, 111 bytes

```
a->n->{int l=a.length-n+1,i=0,j;float[]r=new float[l];for(;i<l;r[i++]/=n)for(j=i;j<i+n;r[i]+=a[j++]);return r;}

```

**Explanation:**

Try it here.

```
a->n->{                 // Method with array and int parameters and float-array return-type
  int l=a.length-n+1,   //  New length of the return-array
      i=0,j;            //  Index-integers
  float[]r=new float[l];//  Return-array
  for(;i<l;             //  Loop (1) from 0 to `l` (exclusive)
      r[i++]/=n)        //    After every iteration, divide the current item by input `n`
    for(j=i;j<i+n;      //   Inner loop (2) from `i` to `i+n` (exclusive)
      r[i]+=a[j++]      //    Sum the result at index `i` with the items of the input-array
    );                  //   End of inner loop (2)
                        //  End of loop (1) (implicit / single-line body)
  return r;             //  Return the resulting float-array
}                       // End of method

```
> 0 votes

# Answer
# Ruby, 35 bytes

```
->l,n{l.each_cons(n){|x|p x.sum/n}}

```

Try it online!
> 0 votes

# Answer
## Python 57 bytes:

```
lambda L,n:[sum(L[i:(i+n)])/n for i in range(len(L)-n+1)]

```
> 0 votes

# Answer
# Husk, 3 bytes

```
mAX

```

Try it online!

Output as a list of rationals.
> 0 votes

# Answer
# Perl 5 `-MList::Util=sum -a`, 44 bytes

```
say sum(@F[$_..$_+$,-1])/$,for 0..@F-($,=<>)

```

Try it online!
> 0 votes

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


title: Bacterial expansion

text:
# Question
Title: Bacterial expansion
Colonies of bacteria labelled `1` through `9` live on a segment of equally-spaced cells, with empty cells indicated by `0`

```
0 0 2 0 0 0 1 2 0 0 3 3 0 0

```

Every second, each colony spreads to adjacent empty cells. If two colonies reach an empty cell at the same time, the larger-labeled colony takes it.

```
t=0:  0 0 2 0 0 0 1 2 0 0 3 3 0 0
t=1:  0 2 2 2 0 1 1 2 2 3 3 3 3 0
t=2:  2 2 2 2 2 1 1 2 2 3 3 3 3 3

```

The colonies cannot spread beyond the boundaries. A colony is never displaced by another colony, so once all empty cells are filled, nothing further changes.

Given the initial state, output or print the final state. Use any reasonable list or string format. You should not output any intermediate states. The input will contain at least one bacterial colony.

**Related:** Cover up zeroes in a list. (The colonies only spread to the right.)

**Test cases:** Output below input.

```
0 0 2 0 0 0 1 2 0 0 3 3 0 0
2 2 2 2 2 1 1 2 2 3 3 3 3 3

7 0 3 0 0 0 0 0 8 0 9 1
7 7 3 3 3 8 8 8 8 9 9 1

5 0 3 0 0 0
5 5 3 3 3 3

7 7 1
7 7 1

1 0 1
1 1 1

```

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

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

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

# Answer
# JavaScript (ES6), ~~66~~ 62 bytes

```
a=>a.map(_=>a=a.map((c,i)=>c||Math.max(a[i-1]|0,a[i+1]|0)))&&a

```

## Explanation

```
a=>                 // a = input as array of numbers
  a.map(_=>         // loop for the length of a, this ensures the end is always reached
    a=a.map((c,i)=> // update a after to the result of t, for each cell c of index i
      c||           // keep the cell if it is not 0
        Math.max(   // else set the cell to the max value of:
          a[i-1]|0, //     the previous cell (or 0 if i - 1 less than 0),
          a[i+1]|0  //     or the next cell (or 0 if i + 1 greater than the length of a)
        )
    )
  )
  &&a               // return a

```

## Test

```
var solution = a=>a.map(_=>a=a.map((c,i)=>c||Math.max(a[i-1]|0,a[i+1]|0)))&&a
```

```
Cell numbers separated by spaces = <input type="text" id="input" value="7 0 3 0 0 0 0 0 8 0 9 1" />
<button onclick="result.textContent=solution(input.value.split(' ').map(n=>+n)).join(' ')">Go</button>
<pre id="result"></pre>
```
> 14 votes

# Answer
# Pyth, 18 bytes

```
um|@d1eSd.:++0G03Q

```

Test suite

Takes input as a list of integers.

Essentially, this uses a apply until convergence loop, `u`. It applies the update by forming all lists of each cell and the two cells on either side, then updating each zeroed cell to the max of its neighbors.

```
um|@d1eSd.:++0G03Q
                      Implicit: Q = eval(input())
u                Q    Apply the following until convergence, starting with G = Q.
           ++0G0      Pad G with zeros on either side.
         .:     3     Form all 3 element substrings.
                      Now, for each element of G, we have a list of the form
                      [previous, current, next]
 m                    Map over this list
  |@d1                The current element, if it's nonzero
      eSd             Else the max of the list.

```
> 10 votes

# Answer
## Mathematica, 77 bytes

Not very competitive compared with alephalpha's `//.` solution, but I figured a challenge should have a `CellularAutomaton` answer:

```
CellularAutomaton[{If[#2<1,Max@##,#2]&@@#&,{},1},{#,0},{{{l=Length@#}},l-1}]&

```

The function takes a ton of parameters... let's give them some names:

```
CellularAutomaton[{f,n,r},{i,b},{{{t}},d}]

```

Here is what they do:

* `r` is the range of the rule, that is, it determines how many neighbours are considered for the update. We want one neighbour on each side, so we use `1`.
* `n` is normally the number or list of colours (different cell types), but if we specify the rule as a custom function instead of a rule number, this should be `{}`.
* `f` is a function determining the update rule. It takes a list of 3 cells (if `r = 1`) and returns the new colour for the middle cell.
* `i` is the initial condition. That's the input.
* `b` is the background. If this isn't given, `CellularAutomaton` uses periodic boundaries, which we don't want. Instead using `0` imposes a dead boundary condition.
* `t` is the number of times to simulate. We don't need more steps than the input is wide, because after that the bacteria will have converged, so `t = Length@#`. Normally, `CellularAutomaton` returns all intermediate steps. We can avoid that by wrapping `t` in two lists.
* `d` determines which cells are presented in the output. By default, we would get all the cells that could potentially be affected by the rule (which is `t*r` additional cells on either end of the input). We give it `l-1`, because this is one of the few situations in Mathematica where a zero-based index is used.
> 8 votes

# Answer
## Haskell, ~~86~~ ~~83~~ ~~81~~ ~~79~~ ~~73~~ 71 bytes

```
(0#r)l=max r l
(o#_)_=o
p!_=zipWith3(#)p(0:p)$tail p++[0]
id>>=foldl(!)

```

Usage example: `id>>=foldl(!) $ [7,0,3,0,0,0,0,0,8,0,9,1]` -\> `[7,7,3,3,3,8,8,8,8,9,9,1]`.

Nothing much to explain: if a cell is 0, take the maximum of the neighbor elements. Repeat length-of-the-input times. For this I iterate over `x` via `foldl` but ignore the second argument in `p`.

Edit: @Mauris found 6 bytes to save and @xnor another two. Thanks!
> 6 votes

# Answer
## CJam, ~~27~~ 24 bytes

```
{_,{0\0++3ew{~@e>e|}%}*}

```

Test it here.

This pushes an unnamed block which transforms a list on the stack into a new list.

### Explanation

```
_,       e# Duplicate the input and get its length N.
{        e# Run this block N times (convergence won't take that long)...
  0\0++  e#   Wrap the list in two zeroes.
  3ew    e#   Get all sublists of length 3.
  {      e#   Map this block onto each sublist...
    ~    e#     Dump all three elements on the stack.
    @    e#     Pull up the left neighbour.
    e>   e#     Maximum of both neighbours.
    e|   e#     Logical OR between centre cell and maximum of neighbours.
  }%
}*

```
> 4 votes

# Answer
# J, ~~24~~ 23 bytes

```
(+=&0*(0,~}.)>.0,}:)^:_

```

Usage:

```
   ((+=&0*(0,~}.)>.0,}:)^:_) 0 1 5 0 0 0 6
1 1 5 5 6 6 6

```

Method is similar to Mauris' solution.

```
(                  )^:_ repeat until change
               0,}:     concat 0 and tailless input
      (0,~}.)           concat headless input and 0
             >.         elementwise maximum of the former two lists
  =&0*                  multiply by input_is_0 (zeroing out the list at nonzero input positions)
 +                       add to input

```

Try it online here.

*1 byte saved thanks to Zgarb.*
> 4 votes

# Answer
# Mathematica, ~~77~~ ~~74~~ ~~66~~ 62 bytes

Saved 12 bytes thanks to Martin Büttner.

```
#//.i_:>BlockMap[If[#2<1,Max@##,#2]&@@#&,Join[{0},i,{0}],3,1]&

```
> 3 votes

# Answer
## Python 3.5, 83 bytes

This function takes a Python list of integers. Not sure there's much left to golf, but I'd love to get it competitive with another language at least!

```
def b(s):
 for _ in s:s=[s[n]or max((0,*s)[n:n+3])for n in range(len(s))]
 return s

```

From Python 3.5, PEP 448 lets us unpack `s` into `0,*s`. Earlier releases require one byte extra, like so:

```
def b(s):
 for _ in s:s=[s[n]or max(([0]+s)[n:n+3])for n in range(len(s))]
 return s

```

Credit to user81655's solution and explanation for helping me realise that I don't need to test whether the list has stopped changing; I just need to iterate enough times to be sure all zeroes must have been covered. (The maximum number of iterations needed is one less than the length of the list; this does one iteration more than that, because that takes less code.)
> 3 votes

# Answer
# J, 33 bytes

```
3 :'y+(y=0)*>./(_1,:1)|.!.0 y'^:_

```

A bit longer than I would've liked.

```
3 :'                         '^:_   Repeat a "lambda" until a fixed point:
                            y         The input to this lambda.
               (_1,:1)|.!.0           Shift left and right, fill with 0.
            >./                       Maximum of both shifts.
      (y=0)*                          Don't grow into filled cells.
    y+                                Add growth to input.

```
> 3 votes

# Answer
# Matlab, 90 bytes

How about some convolutions?

```
x=input('');for n=x;x=x+max(conv(x,[0 0 1],'same'),conv(x,[1 0 0],'same')).*~x;end;disp(x)

```

### Example

```
>> x=input('');for n=x;x=x+max(conv(x,[0 0 1],'same'),conv(x,[1 0 0],'same')).*~x;end;disp(x)
[7 0 3 0 0 0 0 0 8 0 9 1]
     7     7     3     3     3     8     8     8     8     9     9     1

```
> 3 votes

# Answer
## Haskell, ~~66~~ 65 bytes

```
f x=[maximum[[-j*j,a]|(j,a)<-zip[-i..]x,a>0]!!1|(i,_)<-zip[0..]x]

```

This defines a function called `f`.

## Explanation

Instead of iterating the cellular automaton, I compute the final values directly. The definition is a single list comprehension. The value `i` ranges from `0` to `length x - 1`, since we zip `x` with the natural numbers. For each index `i`, we produce the list of 2-element lists

```
[-(-i)^2, x0], [-(-i+1)^2, x1], [-(-i+2)^2, x2], ..., [-(-i+n)^2, xn]

```

From this list, we compute the maximal element whose second coordinate is nonzero and take that second element with `!!1`. This gives the closest nonzero value to index `i`, breaking ties by taking the larger value.
> 3 votes

# Answer
# Lua, 133 bytes

Two loops, nested ternaries... If I want to golf it further, I will have to find an other way to do it, but I don't see one.

```
function f(a)for i=1,#a do b={}for j=1,#a do c,d=a[j+1]or 0,a[j-1]b[j]=0<a[j]and a[j]or(d or 0)>c and d or c end a=b end return a end

```

### Explanations

```
function f(a)
  for i=1,#a                       -- this loop allow us to be sure the cycle is complete
  do
    b={}                           -- set a new pointer for b
    for j=1,#a                     -- loop used to iterate over all elements in a
    do
      c,d=a[j+1]or 0,a[j-1]        -- gains some bytes by attributing these expressions
                                   -- to a variable
      b[j]=0<a[j]and a[j]or        -- explained below
            (d or 0)>c and d or c
    end
    a=b                            -- we are one cycle further, new value for a
  end                              -- which is our reference array
  return a
end

```

The part

```
b[j]=0<a[j]and a[j]or(d or 0)>c and d or c

```

will be expanded to

```
b[j]=0<a[j]and a[j]or(a[j-1] or 0)>(a[j+1] or 0) and a[j-1] or(a[j+1]or 0)

```

which can be translated in nested `if` as

```
if 0<a[j]
then
    value=a[j]          -- if the cell isn't at 0, it keeps its value
elseif (a[j-1] or 0)<(a[j+1] or 0)
--[[ x or y as the following truth table :
x | y ||x or y
------||-------
0 | 0 || false
0 | 1 ||   y
1 | 0 ||   x
1 | 1 ||   x
    -- It means that when j=1 (1-based) and we try to index a[j-1]
    -- instead of failing, we will fall in the case false or true
    -- and use the value 0
    -- the same trick is used for when we try to use an index > a:len
]]--
then
    value=a[j-1]        -- the left cell propagate to the cell j
else
    value=a[j+1] or 0   -- if j=a:len, we put 0 instead of a[j+1]
                        -- this case can only be reached when we are on the right most cell
                        -- and a[j-1]==0
end

```
> 2 votes

# Answer
# APL (Dyalog), 18 bytes

Anonymous tacit prefix function.

```
(⊢+~∘××3⌈/0,,∘0)⍣≡

```

Try it online!

`(``)⍣≡` apply the following tacit function until the result is identical to the argument:

the argument

`+` plus

`~` not
the
`×` signum

`×` times

`3⌈/` the maxima over each group of three of

`0,` zero followed by

`,` the argument followed by
a
`0` zero
> 2 votes

# Answer
# Husk, 15 bytes

```
ω(m?!2▲!2X3`:0Θ

```

Try it online!

## Explanation

```
ω(m?!2▲!2X3`:0Θ
ω(              iterate until fixed point:
           `:0Θ prepend and append 0
         X3     take overlapping segments of 3 elements
  m             map to:
   ?   !2        if second element is truthy:
    !2            leave as is
      ▲           else take maximum

```
> 2 votes

# Answer
## Pyth, 17 bytes

```
meeSe#.e,_akdbQUQ

```

Takes a Python-style list from stdin, outputs to stdout.

## Explanation

This is basically a translation of my Haskell answer. I haven't really used Pyth before, so hints are welcome.

```
                   Implicit: Q is input list
m              UQ  Map over input index d:
      .e      Q     Map over input index k and element b:
        ,_akdb       The pair [-abs(k-d), b]
    e#              Remove those where b==0
 eeS                Take the second element of the maximal pair

```
> 1 votes

# Answer
# Java 8, ~~155~~ 142 bytes

```
a->{for(int b[],i,l=a.length,p,n,f=l;f>0;)for(b=a.clone(),i=0,f=l;i<l;f-=a[i-1]>0?1:0)if(a[i++]<1)a[i-1]=(p=i>1?b[i-2]:0)>(n=i<l?b[i]:0)?p:n;}

```

Modifies the input `int[]` instead of returning a new one to save bytes.

**Explanation:**

Try it here.

```
a->{                   // Method with integer-array parameter and no return-type
  for(int b[],         //  Copy array
          i,           //  Index integer
          l=a.length,  //  Length of the array
          p,n,         //  Temp integers (for previous and next)
          f=1;         //  Flag integer, starting at 1
      f>0;)            //  Loop (1) as long as the flag is not 0 (array contains zeroes)
    for(b=a.clone(),   //   Create a copy of the current state of the array
        i=0,           //   Reset the index to 0
        f=l;           //   Reset the flag to the length of the array `l`
        i<l;           //   Inner loop (2) over the array
        f-=a[i-1]>0?   //     After every iteration, if the current item is not a zero:
            1          //      Decrease flag `f` by 1
           :           //     Else:
            0)         //      Leave flag `f` the same
      if(a[i++]<1)     //    If the current item is a 0:
        a[i-1]=        //     Change the current item to:
         (p            //      If `p` (which is:
           =i>1?       //        If the current index is not 0:
             b[i-2]    //         `p` is the previous item
            :          //        Else:
             0)        //         `p` is 0)
         >(n           //      Is larger than `n` (which is:
            =i<l?      //        If the current index is not `l-1`:
              b[i]     //         `n` is the next item
             :         //        Else:
              0)?      //         `n` is 0):
          p            //       Set the current item to `p`
         :             //      Else:
          n;           //       Set the current item to `n`
                       //   End of inner loop (2) (implicit / single-line body)
                       //  End of loop (1) (implicit / single-line body)
}                      // End of method

```
> 1 votes

# Answer
# Ruby, 81 bytes

```
->(a){a.map{|o|a=a.map.with_index{|x,i|x!=0 ? x : a[[0,i-1].max..i+1].max}}[-1]}

```

I think the inner `map` could be further golfed.
> 0 votes

# Answer
## PHP - 301 291 289 288 264 Characters

Didn't peak at other answers before attempting this. Don't blame the language, blame me. Very enjoyable and challenging non the less. All code golf advice heavily appreciated.

```
$a=explode(' ',$s);$f=1;while($s){$o=1;foreach($a as&$b){
if($b==0){$u=current($a);prev($a);$d=prev($a);if(!$o&&current($a)==0){end($a);$d=prev($a);}if(!$f){$f=1;continue;}if($u>$d)$b=$u;if($u<$d){$b=$d;$f=0;}}
$o=0;}if(!in_array(0,$a))break;}$r=join(' ',$a);echo$r;

```

Explained

```
// Input
$s = '0 0 2 0 0 0 1 2 0 0 3 3 0 0';

// Create array
$a = explode(' ', $s);
// Set skip flag
$f = 1;
while ($s)
{
    // Set first flag
    $o = 1;
    // Foreach
    foreach ($a as &$b)
    {
        // Logic only for non zero numbers
        if ($b == 0)
        {
            // Get above and below value
            $u = current($a);
            prev($a);
            $d = prev($a);

            // Fix for last element
            if (! $o && current($a) == 0)
            {
                end($a);
                $d = prev($a);
            }

            // Skip flag to prevent upwards overrun
            if (! $f)
            {
                $f = 1;
                continue;
            }

            // Change zero value logic
            if ($u > $d)
                $b = $u;
            if ($u < $d)
            {
                $b = $d;
                $f = 0;
            }
        }

        // Turn off zero flag
        $o = 0;
    }

    // if array contains 0, start over, else end loop
    if (! in_array(0, $a))
        break;
}
// Return result
$r = join(' ', $a);
echo $r;(' ', $a);
echo $r;

```
> 0 votes

# Answer
# MATL, 38 bytes

Direct translation of my Matlab answer. Uses current version of language/compiler.

```
it:"tttFFTo2X5I$X+wTFFo2X5I$X+vX>w~*+]

```

### Example

```
>> matl it:"tttFFTo2X5I$X+wTFFo2X5I$X+vX>w~*+]
> [7 0 3 0 0 0 0 0 8 0 9 1]
7 7 3 3 3 8 8 8 8 9 9 1

```

*EDIT: Try it online! with `X+` replaced by `Y+` and `v` by `&v`, owing to changes done in the language.*
> 0 votes

# Answer
## Python, 71 bytes

```
g=lambda l:l*all(l)or g([l[1]or max(l)for l in zip([0]+l,l,l[1:]+[0])])

```

The `zip` creates all length-3 sublists of an element and its neighbors, treating beyond the endpoints as `0`. The central element `l[1]` a sublist `l`, if zero, is replaced by the `max` of its neighbors with `l[1]or max(l)`. The `l*all(l)` returns the list `l` when it has no `0`'s.
> 0 votes

# Answer
# Ruby, 74 bytes

```
->a{(r=0...a.size).map{|n|a[r.min_by{|i|[(a[i]<1)?1:0,(i-n).abs,-a[i]]}]}}

```

works by finding the closest non-zero number.
> 0 votes

---
Tags: code-golf, cellular-automata
---


title: Wolstenholme numbers

text:
# Question
Title: Wolstenholme numbers
The generalised harmonic number of order \\$m\\$ of \\$n\\$ is

$$H\_{n,m} = \sum^n\_{k=1} \frac 1 {k^m}$$

In this challenge, we'll be considering the generalised harmonic numbers of order \\$2\\$:

$$H\_{n,2} = \sum^n\_{k=1} \frac 1 {k^2}$$

This sequence begins \\$1, \frac 5 4, \frac {49} {36}, \frac {205} {144}, \dots\\$ and converges to \\$\frac {\pi^2} 6\\$ as \\$n \to \infty\\$.

However, we will only be considering the *numerators* of this sequence, which forms another sequence known as the Wolstenholme numbers (A007406):

```
1, 5, 49, 205, 5269, 5369, 266681, 1077749, 9778141, ...

```

You are to take a positive integer \\$x\\$ as input. \\$x\\$ is guaranteed to be a Wolstenholme number. You should output the next term in the sequence of Wolstenholme numbers, i.e. given the numerator of \\$H\_{n,2}\\$, output the numerator of \\$H\_{n+1,2}\\$

You may input and output in any convenient format. Your program should not fail due to floating point errors, meaning that attempts that calculate via the generalised harmonic numbers will be invalid if not using rational numbers. Your program should work *theoretically* for any valid input, but it is acceptable to fail for inputs that may be outside your language's integer maximum.

You may assume that no element is repeated in the sequence. If it turns out that there are any duplicate values in the Wolstenholme numbers sequence, any and all behaviour is acceptable when passed such values as input.

This is , so the shortest code in bytes wins

## Test cases

```
        x ->       out
        1 ->         5
        5 ->        49
       49 ->       205
      205 ->      5269
     5269 ->      5369
     5369 ->    266681
   266681 ->   1077749
  1077749 ->   9778141
  9778141 ->   1968329
  1968329 -> 239437889
239437889 -> 240505109

```

# Answer
# , 39 35 30 28 bytes

```
(]{~1+i.~)1*.[:+/\_2^~1+i.,]

```

Try it online!

-5 thanks to Bubbler's observation that the numerator is the LCM of the fraction and 1.

-2 thanks to Bubbler for a transformation.

Note: The approach below relies on the assumption that every Wolstenholme number is greater than or equal its index, which was kindly proved by Greg Martin.

* `[:+/\_2^~1+i.,]` Generates the sequence up to `n+1`, where n is the input: Scan sum `+/\` of 1 over `1%` the square of `*:` one plus `1...+` the integers from 0 to the input `i.@>:`.
* `1*.` Numerators only.
* `(]{~1+i.~)` Finds index of the input in previous result, adds 1, and plucks from previous result.
> 8 votes

# Answer
# Haskell, ~~78~~ 76 bytes

* -2 bytes thanks to kops.

```
f n=snd(span(/=n)$head.words.show<$>scanl1(\i j->i+1/j^2::Rational)[1..])!!1

```

The relevant function is `f`, which takes `n` as a string of digits, and returns the next Wolstenholme number as a string of digits.

Try it online!
> 5 votes

# Answer
# JavaScript (ES6), 98 bytes

```
f=(n,i=0)=>(g=(p=!(j=k=++i),q=1)=>j?g(p,q*j*j--):k?g(x=p+q/k/k--,q):q?g(q,p%q):x/p)()-n?f(n,i):g()

```

Try it online!

### Commented

```
f = (                           // f is a recursive function taking:
  n,                            //   n = input
  i = 0                         //   i = counter, initialized to 0
) =>                            //
( g = (                         // g is a recursive function which computes the
                                // next Wolstenholme number in 3 steps
    p = !(j = k = ++i),         // increment i and start with j = k = i, p = 0
    q = 1                       // and q = 1
  ) =>                          //
  j ?                           // [step 1] while j is not equal to 0:
    g(p, q * j * j--)           //   multiply q by j² and decrement j
  :                             // then:
    k ?                         //   [step 2] while k is not equal to 0:
      g(x = p + q / k / k--, q) //     add q / k² to p, copy p to x and decrement k
    :                           //   then:
      q ?                       //     [step 3] while q is not equal to 0:
        g(q, p % q)             //       copy q to p and p % q to q
      :                         //     then:
                                //       p is now equal to the GCD of x and the final
                                //       value of q at the end of the 1st step
        x / p                   //       return x / p
)()                             // initial call to g
- n ?                           // if it's not equal to n:
  f(n, i)                       //   try again until it is
:                               // else:
  g()                           //   return the next Wolstenholme number

```
> 5 votes

# Answer
# MATL, ~~30~~ 26 bytes

```
0`@:Utptb/swyZd/ht1_)G-]0)

```

**Try it online!**

### Explanation

```
0         % Push 0. This initiallizes the array of numerators
`         % Do...while
  @:U     %   Push [1, 2, 4, ..., n^2] where n is iteration index
  tp      %   Duplicate, product. Gives denominator (not reduced)
  tb      %   Duplicate, bubble up in stack. Moves copy of [1, 2, 4, ..., n^2] to top
  /s      %   Divide element-wise and sum. Gives numerator (not reduced)
  wyZd    %   Swap, copy from below, GCD
  /       %   Divide. This gives the reduced numerator
  h       %   Concatenate to vecor of previos numerators
  t1_)    %   Duplicate, get second-to last entry
  G-      %   Subtract input
]         % End. A new iteration is run if top of the stack is non-zero
0)        % Get last entry. Implicit display

```
> 4 votes

# Answer
# Raku, 54 bytes

```
{first *>$_,map *.nude[0],[\+] map *⁻²,1.FatRat..*}

```

Try it online!

* `[\+] map *⁻², 1.FatRat .. *` is the harmonic sequence. The members are of type `FatRat`, a "fat rational" type that does not degrade to floating point. (I could skip the `.FatRat` for seven bytes and use ordinary rationals, which give the correct answer for all of the provided test cases, but the problem states that the solution should theoretically valid for any input, so...)
* `map *.nude[0]` maps that sequence into its numerators. `*.numerator` would be the more straightforward way to do this, but it's shorter to use `.nude` which returns the numerator and denominator as a pair.
* `first * > $_` finds the first element of the numerator sequence that exceeds the function argument `$_`.
> 4 votes

# Answer
# Husk, 14 bytes

```
←t↓≠⁰mois∫m□İ\

```

Try it online! or Verify all testcases

## Explanation

```
←t↓≠⁰mois∫m□İ\
            İ\ infinite list [1,1/2,1/3,...
          m□   map to squares
         ∫     cumulative sum
     mo        map to
       is      first integer in string representation
               (gets numerator)
  ↓            drop elements till
   ≠⁰          input is reached
 t             remove first item
←              take the first item

```
> 4 votes

# Answer
# , 112 bytes

```
x=scan();while({d=prod((1:T)^2);n=sum(d/(1:T)^2);i=1;while((i=i+1)<n)while(!n%%i&!d%%i)n=n/i;x!=F}){T=T+1;F=n};n

```

Try it online!

**How?**

```
x=scan();                   # get previous wolstenholme number x
while({...do this...;x!=F}) # first 'do this', then check if x is equal to F (initially zero)
 {                          # 'do this':
   d=prod((1:T)^2)          # denominator d = product of squares of 1..T
   n=sum(d/(1:T)^2)         # numerator n = sum of d/1, d/4, d/9, d/16 ... d/T^2
                            # n/d is T-th harmonic number of order 2
                            # but we need to simplify the fraction:
   i=1;while((i=i+1)<n)     # try each i from 2..(n-1):
    while(!n%%i&!d%%i)n=n/i # if i divides both n and d, divide n by i
                            # at this point, n equals the simplified numerator
                            # which is the T-th wolstenholme number
 }
){                          # if x isn't equal to F yet
   T=T+1                    # increase T
   F=n                      # and set F to the last wolstenholme number n
}
                            # if we got here, x was equal to F
                            # and we've already updated n to be the next
                            # wolstenholme number
n                           # so we output n.

```

---

A vectorized version is shorter - 98 bytes \- but quickly runs-out of memory as it tries to allocate a vector the size of the non-reduced denominator for order-2 harmonic numbers beyond the first 7...
> 4 votes

# Answer
# Python 2, 120 bytes

```
from fractions import*
x=input()
k=1
g=0
n=[]
while x not in n[:-1]:g+=Fraction(1,k*k);k+=1;n+=[g.numerator]
print n[-1]

```

Try it online!

fixed thanks to Jonathan Allan
> 3 votes

# Answer
# Stax, 15 bytes

```
┬Z°#¡Lk╢╙°m╕%ºb

```

Run and debug it

Reduced from 22 with help from recursive.

## Explanation

```
{iiGx=!w^G}Z{Ju+Fr
{      w           while result is falsy:
 ii                push iteration index twice
   G               GoTo unclosed curly brace
          }        label:
           Z       push a zero under the index
            {   F  for 1..i
             Ju+   square, invert, add
                   return to GoTo
                 r get numerator
    x=!            is it equal to the input?
        ^          if so, increment
         G         and GoTo label

```
> 3 votes

# Answer
# Ruby, 58 bytes

```
->x{r=z=1r;1until[z,z+=(r+=1)**-2]*?_=~/^#{x}.+_(\d+)/;$1}

```

Try it online!
> 3 votes

# Answer
# Wolfram Language (Mathematica), 54 bytes

```
(k=1;While[(t=Numerator[++k~HarmonicNumber~2])<=#];t)&

```

Try it online!
> 2 votes

# Answer
# Ruby, 61 bytes

Uses Ruby's *Rational* type.

```
->x{w=l=n=k=0r
(l=n;k+=1;w+=1/k/k;n=w.numerator)while l!=x
n}

```

Try it online!

73 bytes with integers:

```
->x{d=1
n=l=k=w=0
(l=n;k+=1;w*=k*k;w+=d;d*=k*k;n=w/w.gcd(d))while l!=x
n}

```

Try it online!
> 2 votes

# Answer
# Charcoal, 57 bytes

```
Ｎθ≔⁰η≔⁰ζＷ⁻θζ«≔ηζ⊞υＸ⊕Ｌυ²≔Πυε≔Σ÷ευδＷδ«≔﹪εκδ≔κε»≔÷Σ÷Πυυεη»Ｉη

```

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

```
Ｎθ

```

Input the target numerator.

```
≔⁰η≔⁰ζ

```

Initialise the next and current numerator to zero.

```
Ｗ⁻θζ«

```

Repeat until the current numerator is the target.

```
≔ηζ

```

Save the next numerator as the current numerator.

```
⊞υＸ⊕Ｌυ²

```

Add the next square to the predefined empty list.

```
≔Πυε≔Σ÷ευδ

```

Get the potential denominator and numerator of the sum by multiplying all of the fractions by the product of all the squares so far.

```
Ｗδ«≔﹪εκδ≔κε»

```

Get the GCD.

```
≔÷Σ÷Πυυεη

```

Divide the potential numerator by the GCD and save it as the next numerator.

```
»Ｉη

```

Output the next numerator.
> 2 votes

# Answer
# Jelly, (16?) 21 bytes

```
²€P©:$S:g¥®
1Ç⁼¥1#Ḣ‘Ç

```

**Try it online!**

---

I can't prove that \\$a(n) \ge n\\$, but if so this 16 byter works too:

```
‘²€P©:$S:g¥®)ḟRḢ

```

---

### How?

```
²€P©:$S:g¥® - Link 1, get a(n): integer n
²€          - square each (of [1..n])
     $      - last two links as a monad - f(squares):
  P         -   product (of the squares)
   ©        -   (copy to the register for later)
    :       -   integer divide by (each square)
      S     - sum
         ¥® - last two links as a dyad - f(sum, register)
        g   - (sum) gcd (register)
       :    - (sum) integer divided by (that)

1Ç⁼¥1#Ḣ‘Ç - Main Link: integer, a(z)
1         - set L=1
    1#    - collect the first 1 integer(s) counting up from k=L for which:
   ¥      -   last two links as a dyad - f(k,a(z))
 Ç        -     call Link 1 (k) -> a(k)
  ⁼       -     equals (a(z))?
      Ḣ   - head -> z
       ‘  - increment -> z+1
        Ç - call Link 1 (z+1) -> a(z+1)

```
> 2 votes

# Answer
# Vyxal, ~~33~~ 30 bytes

```
1:{›Ȯ?≤|:λ¡²nɾ²/M∑:n¡²ġ/;†^_}Ȯ

```

Try it Online!

Let us try to maintain a stack with 2 elements \\$n\\$ and \\$f(n)\\$ after every step, with \\$f(n)\\$ being the required numerator.

```
1:     # Pushes [1, 1] to the stack.
{      # While...
›      # Increment the first value of stack -> [n+1, f(n)]
Ȯ?≤    # While condition: Is the second value of stack less than or equal to the input?
|      # If yes, then...
:      # Duplicate the top value of stack. Now it contains [n+1, n+1, f(n)]
λ      # Lambda function
 ¡²    # Factorial of n, squared.
nɾ²    # Inclusive range [1, n], and square every number.
/M∑    # Divide every time with first argument and return the sum.
:n¡²ġ/ # Duplicate this value, then divide it with it's gcd with factorial n, squared
;      # Return value.
†      # Call the function. Now the stack contains [f(n+1), n+1, f(n)]
^      # Reverse stack -> [f(n), n+1, f(n+1)]
_      # Pop from stack -> [n+1, f(n+1)]
}      # End while
Ȯ      # Print second item of stack.

```

*-3 bytes thanks to Lyxal*
> 2 votes

# Answer
# Python 3, 126 bytes

```
from math import*
def f(n,i=1,k=1):
 k*=i*i
 q=sum(k//j**2for j in range(1,i+1))
 x=q/gcd(k,q)
 return x>n and x or f(n,i+1,k)

```

Try it online!

Let's find the numerator if the denominator is \\$1^2 + 2^2 + ... i^2\\$. The numerator of the \\$j^{th}\\$ term will be just the denominator divided by \\$j^2\\$. So we add the numerator of all these terms and then divide it with the gcd of numerator and denominator and compare it with \\$n\\$.
> 1 votes

# Answer
# Clojure, 90 bytes

```
#(loop[x 3 y 5/4](let[z(+(/ 1 x x)y)n numerator](condp = % 1 5(n y)(n z)(recur(inc x)z))))

```

Try it online!

Like many other languages, Clojure has native support for rational fractions, but with an annoying quirk: `numerator` and `denominator` functions throw exceptions on integer arguments. If that's not enough, even rational literals of the form `x/y` are auto-converted to integers wherever possible, and the only way I found to force evaluation as a rational is `clojure.lang.Numbers/toRatio`, which is a golfing nightmare.

This causes a problem with the initial term \\$1\\$ of the harmonic sequence, which necessitates a hack - we start the loop from the second term, and cover the first one with a special condition.
> 1 votes

---
Tags: code-golf, sequence, number-theory, rational-numbers
---