title: Shantae Dance Matching

text:
# Question
Title: Shantae Dance Matching
In the original Shantae game, there are transformation dances that you have to input in time using the D-Pad, A, and B. If you complete a predefined sequence while dancing, you will transform into the corresponding form (or teleport or heal). Your task is to output the corresponding effect when given an input. The catch is that you may get extraneous dance moves in the input, both before and after, and there may not even be a dance in the input.

# The Dances

Using `UDLRAB` for dance moves:

* Monkey: `DR`
* Elephant: `DL`
* Spider: `DA`
* Harpy: `DB`
* Tinkerbat: `DUU`
* Heal: `DUA`
* Scuttle Town: `DULR`
* Water Town: `DURLAB`
* Oasis Town: `DURRBA`
* Zombie Caravan: `DULLBA`
* Bandit Town: `DUBLBR`

# Coding

Input: a sequence of dance moves. This can contain Up, Down, Left, Right, B, A, and Wait values. Use any convenient encoding.

Output: a value corresponding to the first matching dance in the sequence or a distinct value if there is no match. You can encode this in any convenient way.

# Examples

Using `.` for waiting:

* `DR` → Monkey
* `UUU.DLUAB` → Elephant
* `L.DDBALL` → Harpy
* `LRLRDURURLAB`*No match*
* `DUBLBR` → Bandit Town
* `DURLBA`*No match*
* `DDUDR` → Monkey
* `RLAB`*No match*
* `.DUUBBB` → Tinkerbat
* `DADRDL` → Spider
* `.DURRBADR` → Oasis Town
* `DURR.BA`*No match*

# Other Rules/Notes

* Standard rules on loopholes and IO methods apply
* Describe your encoding for dance moves and matching dances.
* There may be more than one dance in the input. If that is the case, match only the first one that appears in the input.
* Waiting interrupts dances.

# Answer
# JavaScript (ES6),  ~~92 88 61~~  59 bytes

*Saved 2 bytes thanks to a suggestion from @tsh*

Expects `UdLRAB` for the dance moves and `.` for waiting. Outputs either *undefined* if there's no match, or the sequence of the matching dance (e.g. `dR` for Monkey or `dURLAB` for Water Town).

```
s=>(/d([A-R]|U(U|A|LR|RLAB|RRBA|LLBA|BLBR))/.exec(s)||0)[0]

```

Try it online!

or Try it with enhanced output
> 3 votes

# Answer
# JavaScript (Node.js), ~~179~~ ~~164~~ ~~153~~ ~~148~~ ~~137~~ 115 bytes

```
d=>{for(;d;d=d.slice(1))for(z of "R.L.A.B.UU.UA.ULR.URLAB.URRBA.ULLBA.UBLBR".split`.`)if(!d.search('D'+z))return z}

```

Try it online!

*-11 bytes thanks to Arnauld's answer making me realize output can be simplified*
*-8 bytes thanks to flawr in chat helping me golf array empty checks*
*-12 bytes thanks to Shaggy*

Takes input as a string in same formatting as OP test cases.

Outputs the matched dance string minus the leading `D` for a match, or `undefined` for no match.

The integer corresponds to the match's index in this array (0-indexed):

```
0  - Monkey: DR
1  - Elephant: DL
2  - Spider: DA
3  - Harpy: DB
4  - Tinkerbat: DUU
5  - Heal: DUA
6  - Scuttle Town: DULR
7  - Water Town: DURLAB
8  - Oasis Town: DURRBA
9  - Zombie Caravan: DULLBA
10 - Bandit Town: DUBLBR

```

Probably room for golfing, especially in compressing the dance move set.

## Explanation

### General approach

Iterate through the input string, removing the first character each time and checking if the resulting string starts with a valid dance string.

The whole thing is just a for loop inside a for loop, I'll break it down into 3 parts:
\- Condition
\- Inner Loop
\- Outer Post

### Condition

This is the termination condition for the outer loop, IE while this is true, keep looping.
Quite simple:

```
d

```

`d` is a string, in JS empty strings are falsey "`d` is not empty".

### Inner Loop

This is the stuff that happens each loop:

```
for(z of "R.L.A.B.UU.UA.ULR.URLAB.URRBA.ULLBA.UBLBR".split`.`)

```

So first we define an array with:

```
"R.L.A.B.UU.UA.ULR.URLAB.URRBA.ULLBA.UBLBR".split`.`

```

This creates an array of all dance move strings, missing the `D` at the start of each of them (They all begin with `D`). We'll call this array `x`
There's probably significant golfing potential here.

We then iterate through each item in `x` (stored in `z`), and run the following:

```
if(!d.search('D'+z))return z

```

This uses `d.search` to return the index in the string of `'D'+z`. If and only if `d` *begins* with `'D'+z`, this will return `0`, which is a falsey value in JS.
As such, `!d.search` will *only* be true when the string starts with `'D'+z`.

*Note: This is why we omit the `D`s in `x`, as it saves us 10 bytes (1 per dance), and only costs us a single byte in this search*

Then, if the search matches, we return `z`. This is the dance we've found, without the leading `D`.

If not, we keep looping.

### Outer Post

This is stuff that happens at the *end* of each iteration of the outer loop:

```
d=d.slice(1)

```

Just remove the first character from `d`

### No Match

If `d` becomes empty and no match has been found, the end of the function is reached. This implicitly returns `undefined` as per standard JavaScript behavior
> 2 votes

# Answer
# Retina, ~~53~~ ~~43~~ ~~42~~ 37 bytes

```
0L`;\w|;:(:|A|LR|RLAB|RRBA|LLBA|BLBR)

```

Try it online!

Slightly deviates from the standard input and output to make use of `;:` as `DU` respectively. Inspiration from tsh, saving 5 bytes.

Matches the first dance and outputs it, after seeing Arnauld's answer. Saved 10 bytes thanks to Neil suggesting using the list stage `L` and limiting the output to the first match. Saved one byte thanks to tsh shortening the regex.

The header and footer just allow for multiple inputs and making the output readable, respectively.
> 2 votes

# Answer
# Perl 5 `-p`, 47 bytes

```
/D([RLAB]|U(U|A|LR|LLBA|RLAB|RRBA|BLBR))/;$_=$&

```

Try it online!

Returns the dance's code (allowed as per @Arnauld's comment) or blank if no match.
> 1 votes

# Answer
# Charcoal, 48 bytes

```
≔⌊Ｅ⁺D⪪”{➙∧⪫⁻Ｙ⟧¹⊟AOＰ9GＫπ⁸Ｐa↷VＢ”D⟦⌕⁺θιιＬι⟧η✂θ§η⁰Ση

```

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

```
⁺D⪪”{➙∧⪫⁻Ｙ⟧¹⊟AOＰ9GＫπ⁸Ｐa↷VＢ”D

```

Split the compressed string `RDLDADBDUUDUADULRDURLABDURRBADULLBADUBLBR` (which contains all of the dances except for the leading `D`) on `D`, and then prefix the `D` back to each entry.

```
Ｅ...⟦⌕⁺θιιＬι⟧

```

For each dance, concatenate it to the input and find the first position of the dance in the concatenation, plus also take the length of the dance. For dances that weren't found this means that the result will be the length of the input string instead of `-1`.

```
≔⌊...η

```

Take the minimum of those results, i.e. the position and length of the dance that appeared first.

```
✂θ§η⁰Ση

```

Extract that dance from the original string.
> 1 votes

# Answer
# Jelly, ~~33~~ 28 bytes

```
“¡ịḟ½NỵC\HỤĊȷṗ~’b6ṣ0;€0ɓUwⱮM

```

Try it online!

Takes as input a list of integers representing the moves:

```
0 D
1 U
2 R
3 B
4 L
5 A
6 .

```

Returns a wrapped integer for the answer, or a list of all these integers for no match:

```
1 Monkey
2 Harpy
3 Elephant
4 Spider
5 Tinkerbat
6 Heal
7 ScuttleTown
8 OasisTown
9 WaterTown
10 BanditTown
11 ZombieCaravan
1,2,3,4,5,6,7,8,9,10,11 NoMatch

```

TIO link includes code in the footer to translate these back to the strings in the question, but is not needed for the program to function using the integers specified here.
> 1 votes

# Answer
# 05AB1E, 104 bytes

```
'dð.•—Áå•«•¼L?D/8¢Am.Z¼ž•6BSèJ#«å.•g³ç¼…¬ÿ¬Õ‚YÙ•“ÆÚàæÉ¾ ÿ“#.•664Îè¡HĆ∍•¸«“scuttle„©Ê´ bandit“#ð“‰à“«««sÏ

```

Try it online!

---

I wrote this monstrosity without realizing I could use numbers for name moves...
> 0 votes

# Answer
# sfk, ~~119~~ 91 bytes

```
xex -i -firsthit
_DR_
_DL_
_DA_
_DB_
_DUU_
_DUA_
_DULR_
_DURLAB_
_DURRBA_
_DULLBA_
_DUBLBR_

```

Try it online!

Gives the first dance present as a sequence of moves.

(`xex` is just a stream editor, and in this case `_<pattern>_` is search text)
> 0 votes

# Answer
# 05AB1E, ~~28~~ 27 bytes

Saved 1 byte thanks to *Grimy*

```
Œ.Δ•1Λ*#$ß‘«∍@…9\÷•6B1¡1ìQZ

```

Try it online!

Outputs either the match (i.e. `10` for Monkey) or `-1` for no match

```
1 = D
0 = R
2 = L
3 = A
4 = B
5 = U
6 = .

```

**Explanation**

```
Œ.Δ                           # Find the first substring of the input
                         Q    # that is equal to
                          Z   # any element in
   •1Λ*#$ß‘«∍@…9\÷•           # 29058694378496950170872579685936
                   6B         # converted to base-6
                     1¡       # split on 1's
                       1ì     # with a 1 prepended to each

```
> 0 votes

---
Tags: code-golf, sequence, classification
---


title: Intercommunication between threads

text:
# Question
Title: Intercommunication between threads
So glad I found this cool site. Wanted to try sharing a coding challenge a friend gave me, an interview question. Usually it is written in java, but you can use whatever language you want, just have fun!

**Challenge:** write efficiently and securely a program that creates an array of n threads that communicate with each other, where each thread, for simplicity, represents a number between 1,...,100. Oh, and it has to be randomly initialized.

Here comes the fun part: each thread looks at its neighbours(i-1,i+1) and:

* If its number is smaller than the number of both of his neighbours(i-1,i+1), it increments itself.
* If its number is larger than the numbers of both of his neighbours, it decrements itself.
* If its number is equal or between the numbers of its neighbours, it keeps the number the same.

So far not fun, right? So let's also make it a circular array! (the first element in the array and the last element in the array are neighbours) the tricky parts are: each thread should not change its number before its neighbors finished checking it.

The program performs m rounds of checks.

**Input:** For program logic, you can take the input from the user, or define it, doesn't matter.

**Output:** first line should print the starting state of the array. Second line should print all of the numbers in the array after each thread did one check. Third line should print the numbers in all of the array after each thread did a second test(second round) and so on.

Might be quite tricky in the beginning, but have fun with it! The winner will be the one who can write the shortest code, and in case of a tie, cool algorithmic tricks or functional utilization of the java language will be awarded extra points!

---

First post here, will try to post more cool stuff for you to enjoy! Really like this site.

I posted it a while ago, but forgot my credentials while being abroad so I couldn't log in to the site and fix the previous post. Hoping that this one is according to the standards of the site and more than that, I really hope you'll enjoy this cool coding gamexercise.

Good luck to all and most importantly - enjoy!

As kevin well-said: Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.

# Answer
> 4 votes
# 05AB1E, 35 bytes

```
FтLΩˆ}>µ¯©=´vy®N<N>‚èy.SDPiн+ë\}ˆ}¼

```

Takes `n` as first input, and `m` as second. Doesn't use any threads, since 05AB1E has none.

Try it online.

**Explanation:**

```
F    }               # Loop the (implicit) input `n` amount of times:
 тL                  #  Push a list in the range [1,100]
   Ω                 #  Pop and push a random value from this list
    ˆ                #  Pop and add it to the global array
>                    # Increase the second (implicit) input `m` by 1
 µ                   # Loop until the counter_variable is equal to that:
  ¯                  #  Push the global array
   ©                 #  Store it in the register (without popping)
    =                #  Print it with trailing newline (without popping)
     ´               #  And clear the global array
   v                 #  Loop over each item of the array that is still on the stack:
      N<             #   Get the index-1
        N>           #   And the index+1
          ‚          #   Pair them together
     ®     è         #   Index both into the previous array we stored in the register
                     #   (NOTE: 05AB1E has automatic wrap-around when indexing)
            y.S      #   Compare both of them to the current integer `y`
                     #   (-1 if `y` is larger; 1 if `y` is smaller; 0 if equal)
               D     #   Duplicate this pair
                Pi   #   If the product is 1 (only true for [1,1] and [-1,-1]):
                  н  #    Only leave the first element of the duplicated pair
    y              + #    And add it to the current integer `y`
                 ë   #   Else:
                  \  #    Discard the duplicated pair, so `y` is at the top of the stack
                 }ˆ  #   After the if-else: add it to the global array
   }¼                #  After the inner loop: increase the counter_variable by 1

```

# Answer
> 3 votes
# Java 8, 229 bytes (lambda without threads)

```
n->m->{int a[]=new int[n],b[],i=n,t;for(;i-->0;)a[i]=(int)(Math.random()*100)+1;for(;m-->=0;a=b)for(System.out.println(java.util.Arrays.toString(a)),b=a.clone(),i=n;i-->0;)b[i]+=(t=a[(n+~i)%n]-a[i])*(a[-~i%n]-a[i])>0?t<0?-1:1:0;}

```

Try it online.

# Java 8, 299 bytes (full program without threads)

```
interface Main{static void main(String[]A){int n=new Short(A[0]),m=new Short(A[1]),a[]=new int[n],b[],i=n,t;for(;i-->0;)a[i]=(int)(Math.random()*100)+1;for(;m-->=0;a=b)for(System.out.println(java.util.Arrays.toString(a)),b=a.clone(),i=n;i-->0;)b[i]+=(t=a[(n+~i)%n]-a[i])*(a[-~i%n]-a[i])>0?t<0?-1:1:0;}}

```

Try it online.

**Explanation:**

```
n->m->{              // Method with two integer parameters and no return-type
  int a[]=new int[n],//  Create an array of size `n`
      b[],           //  Temp array, uninitialized
      i=n,           //  Index-integer, starting at `n`
      t;             //  Temp integer, uninitialized
  for(;i-->0;)       //  Loop `i` in the range (`n`, 0]:
    a[i]=(int)(Math.random()*100)+1;
                     //   Fill the `i`'th item in the array with a random integer in
                     //   the range [1, 100]
  for(;m-->=0;       //  Loop `m` times:
      a=b)           //    After every iteration: replace array `a` with `b`
    for(System.out.println(java.util.Arrays.toString(a)),
                     //   Print array `a` with trailing newline
        b=a.clone(), //   Create a copy of array `a` in `b`
        i=n;i-->0;)  //   Inner loop `i` in the range (`n`, 0]:
      b[i]+=         //    Increase the `i`'th item in array `b` by:
        (t=a[(n+~i)%n]-a[i])
                     //     Calculate a[i-1] minus a[i] (temporarily stored in `t`)
        *(a[-~i%n]-a[i])
                     //     Multiply it by a[i+1] minus a[i]
         >0?         //     If this is positive:
            t<0?     //      If `t` is negative:
             -1      //       Decrease b[i] by 1
            :        //      Else (`t` is positive):
             1       //       Increase b[i] by 1
        :            //     Else (a[i-1]-a[i] and a[i+1]-a[i] are pos/neg or neg/pos,
                     //           or one of the two is 0)
         0;}         //      Leave b[i] the same by adding 0

```

# Java 10, ~~569~~ 537 bytes (full program with threads)

```
import java.util.concurrent.*;class M{C[]c;CyclicBarrier b;int n,m,i;public static void main(String[]a){new M().t(a);}void t(String[]a){m=new Short(a[1]);c=new C[n=new Short(a[0])];for(;i<n;)c[i]=new C(i++);b=new CyclicBarrier(n,()->{System.out.println(java.util.Arrays.toString(c));});for(var x:c)new Thread(x).start();}class C implements Runnable{int v=100,i,q,L,R,t;C(int I){i=I;v*=Math.random();v++;}public void run(){try{for(;q++<=m;R=c[-~i%n].v,t=v<L&v<R?1:v>L&v>R?-1:0,b.await(),v+=t)L=c[(n+~i)%n].v;}catch(Exception ex){}}public String toString(){return""+v;}}}

```

As mentioned earlier in a comment, without threads is much shorter..

Try it online (with `class M` is replaced with `class Main`, since it won't work on TIO if the class isn't called exactly `Main`..)

**Explanation:**

```
import java.util.concurrent.*; // Required import for CyclicBarrier
class M{                       // Class:
  C[]c;                        //  Array of our Runnable cells on class-level
  CyclicBarrier b;             //  A CyclicBarrier
  int n,                       //  Size of the array
      m,                       //  Amount of cycles
      i;                       //  Index, implicitly starting at 0
  public static void main(String[]a){
                               //  Mandatory main method:
    new M()                    //   Create an instance of this class
        .t(a);}                //   And call the non-static method below:
  void t(String[]a){           //  Non-static method for the actual program:
    m=new Short(a[1]);         //   Fill the amount of cycles `m` with the second argument
    c=new C[n=new Short(a[0])  //   Fill the size `n` with the first argument
             ];                //   Create the array of that size
    for(;i<n;)                 //   Loop over all cells in the array:
      c[i]=new C(i++);         //    And create a new instance for each cell
    b=new CyclicBarrier(n,     //   Create the CyclicBarrier of size `n`
       ()->{                   //    Which will do the following before every cycle:
          var p="";            //     Create a String to print, starting empty
          for(var x:c)         //     Loop over the cells
            p+=x.v+" ";        //      Append the cell's value and a space to the String
          System.out.println(p);});
                               //     Print the String with trailing newline
    for(var x:c)               //   Loop over the cells again:
      new Thread(x)            //    Create a new thread for this Runnable cell
        .start();}             //    And start the thread
  class C                      //  Inner class for the cells
      implements Runnable{     //  which implements the Runnable interface
    int v=100,                 //   The value of this cell, starting at 100
        i,                     //   The index of this cell
        q,                     //   A counter for the cycles
        L,R,                   //   Values of the left and right neighbors
        t;                     //   Incremental integer
    C(int I){                  //  In the constructor of the cell:
      i=I;                     //   Set the index `i` on the given index
      v*=Math.random();v++;}   //   And set `v` to a random integer in the range [1,100]
    public void run(){         //  Override the Runnable run method:
      try{                     //   Mandatory try-catch for InterruptedException
        for(;q++<=m;           //    Loop `m+1` times using the cycle-counter `q`
            ;                  //      After every iteration:
             R=c[-~i%n].v,     //       Get the value in the right-neighboring cell
             t=v<L&v<R?        //       If this cell's value is smaller than both neighbors:
                1              //        Set the incremental to 1
               :v>L&v>R?       //       Else-if this cell's value is larger than both neighbors:
                -1             //        Set the incremental to -1
               :               //       Else (value is smaller than or equal to one neighboring cell
                               //             and larger than or equal to the other neighboring cell):
                0,             //        Set the incremental to 0
             b.await(),        //       Wait until all cells in this BarrierCycle are done
             v+=t)             //       And only then increase/decrease the value with the incremental
          L=c[(n+~i)%n].v;     //     Get the value in the left-neighboring cell
      }catch(Exception ex){}}}}//   Mandatory try-catch for InterruptedException

```

# Answer
> 2 votes
# Javascript, 209 bytes

```
for(a=[],l=n=prompt();n;)a[--n]=(M=Math).floor(M.random()*100+1);for(console.log(a),m=prompt();--m;)b=a.slice(),b.forEach((e,i)=>b[i]+=e<M.min(x=b[(i-1+l)%l],y=b[(i+1)%l])?1:e>M.min(x,y)?-1:0),console.log(a=b)

```

This program, upon running, will prompt the user twice. First for `n`(number of threads, but instead made with arrays), second for `m`(number of checks).

# Answer
> 2 votes
# C# (Visual C# Interactive Compiler), 198 bytes

```
n=>m=>{int[]z=new int[n],g;int i=n,a;for(var k=new Random();i>0;z[--i]=k.Next(1,101));for(;m-->0;z=g){g=z.ToArray();i=0;for(Print(z);i<n;g[i]+=(a=z[(n+~i)%n]-z[i])*(z[-~i%n]-z[i++])>0?a<0?-1:1:0);}}

```

Try it online!

---
Tags: code-golf, java, concurrency, array
---


title: English to Alien translator

text:
# Question
Title: English to Alien translator
# Briefing

Aliens have settled on earth and strangely enough, their alphabet is the exact same as ours. Their language is also very similar to ours with some very distinct and easy to compute differences.

# Challenge

Take a string and output the alien's language equivalent. The translation works as such:

Swap all the vowels in the word with the corresponding:

```
  Vowel |   With
--------+--------
   a    |   obo
   e    |   unu
   i    |   ini
   o    |   api
   u    |   iki

```

You may also write another translator to translate Alien-\>English, this is optional however.

# Examples

```
Input: Shaun
Output: Shoboikin

Input: Java
Output: Jobovobo

Input: Hello, World!
Output: Hunullapi, Wapirld!

```

If the vowel is capitalized then you capitalize the first letter..

```
Input: Alan
Output: Obolobon

Input: Australia
Output: Oboikistroboliniobo

```

# Rules

* Standard loopholes apply
* Must work for text that contains new lines
* You can either write a function, lambda, or full program

Capingrobotikilobotiniapins apin wrinitining thunu runuvunursunu trobonslobotapir!

# Answer
> 14 votes
# Haskell, ~~100~~ 91 bytes

```
(>>= \x->last$[x]:[y|(z:y)<-words"aobo eunu iini oapi uiki AObo EUnu IIni OApi UIki",z==x])

```

# Answer
> 12 votes
# TI-Basic, 173 + 59 + 148 = 380 bytes

*Hopefully the aliens use TI-83/84 calculators ;)*

**Main Program, 173 bytes**

**BONUS:** Keep second or third line depending on whether your want a normal or reverse translator.

```
"("+Ans+")→Str1
"@a~obo@A~Obo@e~unu@E~Unu@i~ini@I~Ini@o~api@O~Api@u~iki@U~Iki@→Str2    <-- English to Alien
"@obo~a@Obo~A@unu~e@Unu~E@ini~i@Ini~I@api~o@Api~O@iki~u@Iki~U@→Str2    <-- Alien to English
For(I,2,length(Ans
If "@"=sub(Str2,I-1,1
Then
Str1+"~"+sub(Str2,I,inString(Str2,"@",I)-I
prgmQ
Ans→Str1
End
End

```

**Subprogram (`prgmQ`), 59 bytes:**

```
Ans→Str9
inString(Ans,"~
sub(Str9,Ans,length(Str9)-Ans+1→Str8
Str9
prgmR
Repeat Str9=Ans+Str8
Ans+Str8→Str9
prgmR
End

```

**Subprogram (`prgmR`), 148 bytes:**

```
Ans→Str0
inString(Ans,"~→Z
inString(Str0,"~",Ans+1→Y
inString(sub(Str0,1,Z-1),sub(Str0,Z+1,Ans-Z-1→X
sub(Str0,1,-1+inString(Str0,"~
If X
sub(Str0,1,X-1)+sub(Str0,Y+1,length(Str0)-Y)+sub(Str0,X+length(sub(Str0,Z+1,Y-Z-1)),Z-X-length(sub(Str0,Z+1,Y-Z-1

```

P.S. `~` represents token `0x81` and `@` represents token `0x7F`, learn more here.

P.P.S. Part of why these programs have a high byte count is because `sub(`, `inString(`, `length(`, and all lowercase letters are two bytes each...

# Answer
> 8 votes
# Perl, 56 bytes

Includes +1 for `-p`

Give input on STDIN

`alien.pl`:

```
#!/usr/bin/perl -p
s%\w%"`"&$&|("A\x0fboE\x15nuI\x09niO\x01piU\x09ki"=~/\u$&\K.../,$&)%eg

```

Works as shown, but replace the `\xXX` escapes by the actual character to get the claimed score

# Answer
> 6 votes
# 05AB1E, ~~28~~ ~~27~~ 20 bytes

```
žÀ.•₅%~≠#ùÛãú•3ôD™«‡

```

Try it online!

**Unuxplobonobotiniapin**

```
žÀ                    # the string "aeiouAEIOU"
  .•₅%~≠#ùÛãú•        # the string "obounuiniapiiki"
              3ô      # split in pieces of 3
                D™«   # concatenate with a title-case copy
                   ‡  # transliterate

```

# Answer
> 6 votes
# Python, ~~99~~ ~~95~~ 93 bytes

```
lambda s:"".join(("ouiaiOUIAI bnnpkbnnpk ouiiiouiii"+c)["aeiouAEIOU".find(c)::11] for c in s)

```

On ideone.com...

Pretty simple. Just take the index we find each character at in the vowel list and use it to pull the three characters we need. If it's not found, `.find()` returns `-1` so just stick the current character on the end of the string. The spaces are necessary so any letter `"a"` doesn't include the added `c`. The translated vowels are grouped by letter order (the first letter of every translation, then the second, then the third).

# Answer
> 6 votes
# sed 89

```
s,a,&b\n,gi
s,i,&n\r,gi
s,o,&p\r,gi
s,u,&k\r,gi
s,e,&n\f,gi
y,aeouAEOU\n\r\f,ouaiOUAIoiu,

```

# Answer
> 5 votes
# PHP , 91 Bytes

```
<?=strtr($argv[1],[A=>Obo,E=>Unu,I=>Ini,O=>Api,U=>Iki,a=>obo,e=>unu,i=>ini,o=>api,u=>iki]);

```

# Answer
> 5 votes
# Python, 129 bytes

```
lambda s:"".join([str,str.capitalize][ord(l)<91]({"a":"obo","e":"unu","i":"ini","o":"api","u":"iki"}.get(l.lower(),l))for l in s)

```

See it running on ideone.com

Here's a more nicely formatted version:

```
lambda s: \
    "".join(
        [str, str.capitalize][ord(l) < 91](
            {"a":"obo", "e":"unu", "i":"ini", "o":"api", "u":"iki"}
            .get(l.lower(), l)
        )
    for l in s)

```

The most interesting parts are `{ ... }.get(l.lower(), l)` which tries to look up the letter stored in `l` converted to lower case in the dictionary and either returns the translated version (if found), or else the original letter,
and `[str, str.capitalize][ord(l) < 91]( ... )` which checks whether the original letter was a capital letter (ASCII code point lower than 91) and then either calls the `str()` function with the letter as argument (if it wasn't a capital letter, does nothing) or the `str.capitalize()` function (converts the first letter of the argument string to upper case).

# Answer
> 4 votes
## Batch, 215 bytes

```
@echo off
set/pt=
set s=
:l
if "%t%"=="" echo(%s%&exit/b
set c=%t:~0,1%
for %%a in (obo.a unu.e ini.i api.o iki.u Obo.A Unu.E Ini.I Api.O Iki.U)do if .%c%==%%~xa set c=%%~na
set s=%s%%c%
set t=%t:~1%
goto l

```

Takes input on STDIN. Processing character-by-character has the convenience of being case-sensitive.

# Answer
> 4 votes
# Pyth, 42 bytes

```
#sXw"aeiouAEIOU"+Jc"obounuiniapiiki"3mrd3J

```

A program that takes input on STDIN and prints the output.

Try it online

**How it works**

```
#sXw"aeiouAEIOU"+Jc"obounuiniapiiki"3mrd3J  Program.
#                                           Loop until error statement:
   w                                         Get w, the next line of the input
                   "obounuiniapiiki"         Yield string literal "obounuiniapiiki"
                  c                 3        Split that into groups of three characters
                 J                           Assign that to J and yield J
                                     mrd3J   Map title case over J
                +                            Merge the lower and title groups
    "aeiouAEIOU"                             Yield string literal "aeiouAEIOU"
  X                                          Translate w from that to the three-character
                                             groups
 s                                           Concatenate that
                                             Implicitly print

```

# Answer
> 4 votes
# C, 167 bytes

I really didn't want to break my habit of always doing main functions when coding C, but this is substantially shorter than the version with a main and this way I got another letter to spell what I wanted!

## Golfed

```
a;l;i;e(char*n){for(;i=*n++;l=i>90,i-=32*l,a=!(i-65)+2*!(i-69)+3*!(i-73)+4*!(i-79)+5*!(i-85),printf(a?"%c%c%c":"%c",(a?"HOUIAI"[a]:i)+l*32,"ibnnpk"[a],"!ouiii"[a]));}

```

## Commented

```
a;l;i;
e(char*n)
{
    for(;
        i = *n++;  /* Get char and advance */
        l = i>90,  /* Is lowercase? */
        i -= 32*l, /* Make uppercase */

        /* Is 1,2,3,4,5 depeding on the vowel and 0 for no vowel */
        a = !(i-65) + 2*!(i-69) + 3*!(i-73) + 4*!(i-79) + 5*!(i-85),

        printf(a?"%c%c%c":"%c",        /* Print 1 or 3 chars? */
               (a?"HOUIAI"[a]:i)+l*32, /* Print appropriate char+case */
                  "ibnnpk"[a],            /* Print appropriate char */
                  "!ouiii"[a]));          /* Print appropriate char */
}

```

There is something special about C and how horrible you can be with pointers and such.

# Answer
> 4 votes
# C (gcc), ~~150 141 136~~ 134 bytes

```
a;i;e(char*n){for(char*v=" AEIOUIAI",*t;i=*n++;printf(&a))t=index(v,i-i/96*32),a=t?t-v:0,a=a?v[a+3]|L" 潢畮楮楰楫"[a]<<8|i&32:i;}

```

Try it online!

Based on the answer by @algmyr and -8 thanks to @ASCII-only

Less golfed version

```
a;i;
e(char*n){
  for(char*v=" AEIOUIAI",*t;i=*n++;printf(&a))
    t=index(v,i-i/96*32),
    a=t?t-v:0,
    a=a?v[a+3]|L" 潢畮楮楰楫"[a]<<8|i&32:i;
}

```

# Answer
> 3 votes
## Retina, 60 bytes

Byte count assumes ISO 8859-1 encoding.

```
[A-Z]
»$&
T`L`l
i
ini
u
iki
e
unu
a
·b·
o
api
·
o
T`»l`_L`».

```

Try it online!

# Answer
> 3 votes
## Javascript (ES6), ~~94~~ ~~93~~ 92 bytes

```
s=>s.replace(/[aeiou]/gi,c=>"OUIAIouiai"[n="AEIOUaeiou".search(c)]+"bnnpk"[n%=5]+"ouiii"[n])

```

*Saved 1 byte thanks to edc65*
*Saved 1 byte thanks to Neil*

### Demo

```
let f =
s=>s.replace(/[aeiou]/gi,c=>"OUIAIouiai"[n="AEIOUaeiou".search(c)]+"bnnpk"[n%=5]+"ouiii"[n])

function translate() {
  document.getElementById("o").value = f(document.getElementById("i").value);
}
translate();
```

```
<input id="i" size=80 oninput="translate()" value="Hello, World!"><br><input id="o" size=80 disabled>
```

# Answer
> 2 votes
# C#, 133 121 bytes

```
s=>{int i;return string.Concat(s.Select(c=>(i ="AIUEOaiueo".IndexOf(c))>-1?"OboIniIkiUnuApioboiniikiunuapi".Substring(i*3,3):c+""));}

```

# Edit (thanks to `milk`)

thank you :) I actually know this overload but somehow completely forgot it when writing this..

```
s=>string.Concat(s.Select((c,i)=>(i="AIUEOaiueo".IndexOf(c))>-1?"OboIniIkiUnuApioboiniikiunuapi".Substring(i*3,3):c+""));

```

# Answer
> 2 votes
## Java 8, 172 bytes

```
String f(String s){String v="AEIOUaeiou",r="OboUnuIniApiIkiobounuiniapiiki",o="";for(char c:s.toCharArray()){int n=v.indexOf(c);o+=n>-1?r.substring(n*3,n*3+3):c;}return o;}

```

ungolfed:

```
String f(String s){
    String v="AEIOUaeiou",r="OboUnuIniApiIkiobounuiniapiiki",o="";
    for(char c:s.toCharArray()){
        int n=v.indexOf(c);
        o+=n>-1?r.substring(n*3,n*3+3):c;
    }
    return o;
}

```

And Alien back to English (171 bytes):

```
String g(String s){String[] v="AEIOUaeiou".split(""),r="Obo Unu Ini Api Iki obo unu ini api iki".split(" ");for(int i=0;i<v.length;i++)s=s.replaceAll(r[i],v[i]);return s;}

```

Ungolfed:

```
String g(String s){
    String[] v="AEIOUaeiou".split(""),r="Obo Unu Ini Api Iki obo unu ini api iki".split(" ");
    for(int i=0;i<v.length;i++)s=s.replaceAll(r[i],v[i]);
    return s;
}

```

# Answer
> 2 votes
## Tcl, 75 bytes

String to be translated is in the variable `s`.

```
string map {A Obo a obo E Unu e unu I Ini i ini O Api o api U Iki u iki} $s

```

# Answer
> 2 votes
# Mathematica, 128 bytes

```
#~StringReplace~{"a"->"obo","A"->"Obo","e"->"unu","E"->"Unu","i"->"ini","I"->"Ini","o"->"api","O"->"Api","u"->"iki","U"->"Iki"}&

```

Not sure whether a shorter program can be obtained by using `IgnoreCase->True` together with a case check.

# Answer
> 2 votes
**C, ~~207~~ 202 bytes** (thanks to Cyoce)

```
#include <stdio.h>
#define r(c,t) case c:printf(t);continue;
int main(){int c;while(~(c=getchar())){switch(c){r('a',"obo")r('e',"unu")r('i',"ini")r('o',"api")r('u',"iki")default:putchar(c);}}return 0;}

```

1) I hate to omit type before any kind of declarations

2) I don't really like to put unusable code (without main() function)

**Usage:**

```
c89 cg.c -o cg; echo "Testing" | ./cg

```

# Answer
> 2 votes
**C 178 bytes**

```
char*p[256],*a="obo\0unu\0ini\0api\0iki\0Obo\0Unu\0Ini\0Api\0Iki",*b="aeiouAEIOU";main(c){for(c=0;b[c];++c)p[b[c]]=a+4*c;for(;(c=getchar())>0;)p[c]?printf("%s",p[c]):putchar(c);}

```

# Answer
> 2 votes
# C, ~~163~~ ~~162~~ 159 bytes

```
char*t="aeiou";n,k;q(char*x){for(;*x;n<0||(*x=t[n>1?n%2?0:2:n+3])&&k>90||(*x-=32),printf("%c%.2s",*x++,n<0?"":&"bonunipiki"[2*n]))n=strchr(t,tolower(k=*x))-t;}

```

# Answer
> 1 votes
# Swift 2.2 196 bytes

¯\\\_(ツ)\_/¯

### Golfed

```
var r = ["a":"obo","e":"unu","i":"ini","o":"api","u":"iki"];var q={(s:String) in var o = "";for var i in s.lowercaseString.characters{o += r[String(i)] != nil ? r[String(i)]!:String(i)};print(o);}

```

### unGolfed

```
var r = ["a":"obo","e":"unu","i":"ini","o":"api","u":"iki"]
var q={(s:String) in
    var o = ""
    for var i in s.lowercaseString.characters {
        o += r[String(i)] != nil ? r[String(i)]!:String(i)
    }
    print(o)
}

```

# Answer
> 0 votes
# Perl 6,  ~~84~~  82 bytes

```
{my%o=<a obo e unu i ini o api u iki>;S:i:g[<{%o.keys}>]=%o{$/.lc}.samecase($/~'a')}

```

```
{my%o=<a obo e unu i ini o api u iki>;S:i:g[<[aeiou]>]=%o{$/.lc}.samecase($/~'a')}

```

## Expanded:

```
# bare block lambda with implicit parameter ｢$_｣
{
  # create the mapping
  my %v = <a obo e unu i ini o api u iki>;

  # replace vowels in ｢$_｣
  S
    :ignorecase
    :global
  [
    <[aeiou]>
  ]

  = # replace them with:

  %v{ $/.lc }
  # change it to be the same case as what was matched, and a lowercase letter
  .samecase( $/ ~ 'a' )
}

```

## Usage:

```
my &english-to-alien = {my%o=<a obo e unu i ini o api u iki>;S:i:g[<[aeiou]>]=%o{$/.lc}.samecase($/~'a')}

say english-to-alien 'Australia'; # Oboikistroboliniobo

```

# Answer
> 0 votes
# Ruby, 102 93 91 88 78 bytes

```
gsub(/[#{b='aeiouAEIOU'}]/){'obounuiniapiikiOboUnuIniApiIki'[b.index($&)*3,3]}

```

*Explanation:*

Execute the line like `ruby -pe "gsub(/[#{b='aeiouAEIOU'}]/){'obounuiniapiikiOboUnuIniApiIki'[b.index($&)*3,3]}"`, next up type, for example, `Australia` it should output: `Oboikistroboliniobo`.

It's pretty straightforward, replace all vowels with a substring based on the index of the to-be replaced vowel in (b), times 3 and the next 3 characters in the translation string.

# Answer
> 0 votes
## C - 192 bytes

(newlines added for clarity)

```
int c,j,b;main(){
char*f[]={"bo","nu","ni","pi","ki",""},
s[]={14,16,0,-14,-12};
while(c=getchar()){for(b=j=0;j<10;++j)
{if(c=="aeiouAEIOU"[j]){c+=s[j%=5];b=1;break;}}
printf("%c%s",c,f[b?j:5]);}}

```

Just lookup tables and a boolean switch.

Lookup each letter in table (string) of vowels; if found, then modify it according to the rule in table `s`. Print each character followed by a string: if a vowel was found, print the character modified by the value in `s` followed by the rest of the syllable stored in table `f`; if a vowel was not found, print the original character and an empty string.

# Answer
> 0 votes
# TI-BASIC, ~~201~~ ~~197~~ 195 bytes

```
Ans+" →Str1:"AEIOUaeiou→Str2:"OUIAIouiai→Str3:"bonunipiki→Str4:1→X:While X<length(Str1:inString(Str2,sub(Str1,X,1→A:5fPart(.2A→B:If A:sub(Str1,1,X-1)+sub(Str3,A,1)+sub(Str4,2B-1,2)+sub(Str1,X+1,length(Str1)-X→Str1:X+1+2(A>0→X:End:sub(Str1,1,length(Str1)-1

```

To think that I'd find another TI-BASIC answer here!

Anyway, the input is an English string in `Ans`.
The output is the translated string.

**Examples:**

```
"HE
HE
prgmCDGF1A
HUnu
"Hello
Hello
prgmCDGF1A
Hunullapi

```

**Explanation:**
(Newlines added for readability. Multiple lines from the same line will be denoted with a `:` in the following code block.)

```
Ans+" →Str1                     ;append a space to the input string and store the result
                                ; in "Str1"
"AEIOUaeiou→Str2                ;store the upper- and lowercase vowels in "Str2"
"OUIAIouiai→Str3                ;store the beginning letter of each corresponding translated
                                ; vowel in "Str3"
"bonunipiki→Str4                ;store the remaining letters of each translated vowel
                                ; in "Str4"
1→X                             ;store 1 in "X"
While X<length(Str1             ;loop until all English letters have been checked
inString(Str2,sub(Str1,X,1→A    ;get the current letter and store its index in "Str2"
                                ; into "A"
5fPart(.2A→B                    ;get which translated vowel end should be used
                                ; B ranges from 1 to 5
If A                            ;if the current letter is a vowel
sub(Str1,1,X-1)                 ;extract the substring of the input before the
                                ; current letter
: +sub(Str3,A,1)                ;append the translated vowel start
: +sub(Str4,2B-1,2)             ;append the translated vowel end
: +sub(Str1,X+1,length(Str1)-X  ;append the remaining substring of the input
: →Str1                         ;store the result of these concatenations into "Str1"
X+1+2(A>0→X                     ;check if A>0 (if the current letter was a vowel)
                                ; if true, increment "X" by three
                                ; if false, increment "X" by one
End
sub(Str1,1,length(Str1)-1       ;remove the trailing space and store the result in "Ans"
                                ;implicit print of "Ans"

```

---

**Notes:**

* TI-BASIC is a tokenized language. Character count does ***not*** equal byte count.
* Lowercase letters in TI-BASIC are two bytes each.

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


# Question
Title: Upside-Down Pyramid Addition...REVERSED!
Upside-Down Pyramid Addition is the process of taking a list of numbers and consecutively adding them together until you reach one number.

When given the numbers `2, 1, 1` the following process occurs:

```
 2   1   1
   3   2
     5

```

This ends in the number `5`.

---

### YOUR TASK

Given the right side of an Upside-Down Pyramid (Ascending), write a program or function that will return the original list.

**New Extra Challenge**: Try doing this in less than O(n^2)

### EXAMPLE

```
f([5, 2, 1]) => [2, 1, 1]
f([84,42,21,10,2]) => [4,7,3,8,2]

```

NOTE: The Upside-Down Pyramid will never be empty and will always consist of positive integers ONLY.

# Answer
# JavaScript (ES6),  ~~62 58 49~~  46 bytes

*Saved 3 bytes thanks to @Oliver*

Returns the list as a comma-separated string.

```
f=a=>+a||f(a.map(n=>a-(a=n),a=a.shift()))+[,a]

```

Try it online!

### Commented

```
f = a =>              // f = recursive function taking the input list a[]
  +a                  // if a[] consists of a single positive integer:
                      //   stop recursion and return this integer
  ||                  // else:
    f(                //   do a recursive call to f:
      a.map(n =>      //     for each value n in a[]:
        a - (a = n),  //       yield the difference between the previous value and n
                      //       and update a to n
        a = a.shift() //       start by removing the first element and saving it in a
                      //       (because of the recursion, it's important here to reuse
                      //       a variable which is defined in the scope of f)
      )               //     end of map()
    )                 //   end of recursive call
    + [, a]           //   append the last entry from a[]

```
> 17 votes

# Answer
# Haskell, 22 bytes

```
foldl(flip$scanr(-))[]

```

Try it online!
> 8 votes

# Answer
## Haskell, 42 bytes

```
f[]=[]
f a=f(zipWith(-)a$tail a)++[last a]

```

Try it online!
> 7 votes

# Answer
# TI-BASIC, 54 bytes

```
Ans→L₁:dim(L₁→dim(L₂:While 1-Ans:L₁(Ans→L₂(Ans:-ΔList(L₁→L₁:dim(Ans:End:L₁(Ans→L₂(Ans:L₂

```

Input is the list of the right side of the triangle in `Ans`, as is described in the challenge.
Output is the top row of said triangle.

**Examples:**

```
{5,2,1
         {5 2 1}
prgmCDGF19
         {2 1 1}
{84,42,21,10,2
 {84 42 21 10 2}
prgmCDGF19
     {4 7 3 8 2}

```

**Explanation:**
This solution abuses the fact that the triangle formed using the right side of the triangle as the start ends up being the change in each element.

In other words,

```
2 1 1
 3 2
  5

```

becomes:

```
5 2 1
 3 1
  2

```

Thus, the resulting list is the right side of this new triangle, which can be formed by setting the last element to the index of its parent list's length in the resulting list.

```
Ans→L₁          ;store the input list in L₁
dim(L₁→dim(L₂   ;set the length of L₂ to the length of L₁
While 1-Ans     ;while the L₁'s length is not 1
L₁(Ans→L₂(Ans   ;set the last element of L₁ to the corresponding index in L₂
-ΔList(L₁→L₁    ;get the change in each element, then negate
                ; (elements are in descending order so the change in each
                ;  element will be negative)
                ; and store the resulting list in L₁
dim(Ans         ;leave the length of L₁ in "Ans"
End
L₁(Ans→L₂(Ans   ;set the element again
                ; (needed for final step)
L₂              ;leave L₂ in "Ans"
                ;implicit print of "Ans"

```

---

**Note:** TI-BASIC is a tokenized language. Character count does ***not*** equal byte count.
> 6 votes

# Answer
# MathGolf, ~~14~~ 11 bytes

```
xÆ‼├│?;∟;]x

```

Try it online!

## Explanation

```
x             reverse int/array/string
 Æ     ∟      do while true without popping using 5 operators
  ‼           apply next 2 operators to TOS
   ├          pop from left of list
    │         get differences of list
     ?        rot3
      ;       discard TOS (removes rest from ├ command)
              loop ends here
        ;     discard TOS (removes empty array from stack)
         ]    wrap stack in array
          x   reverse array

```
> 4 votes

# Answer
# Jelly, 6 bytes

```
ṚIƬZḢṚ

```

A monadic Link accepting a list of integers which yields a list of integers.

**Try it online!**

### How?

Builds the whole triangle then extracts the required elements.

```
ṚIƬZḢṚ - Link: list of integers          e.g.  [84,42,21,10,2]
Ṛ      - reverse                               [2,10,21,42,84]
  Ƭ    - collect & apply until a fixed point:
 I     -   incremental differences            [[2,10,21,42,84],[8,11,21,42],[3,10,21],[7,11],[4],[]]
   Z   - transpose                            [[2,8,3,7,4],[10,11,10,11],[21,21,21],[42,42],[84]]
    Ḣ  - head                                  [2,8,3,7,4]
     Ṛ - reverse                               [4,7,3,8,2]

```
> 4 votes

# Answer
# Python 2, 56 bytes

```
f=lambda a:a and f([l-r for l,r in zip(a,a[1:])])+a[-1:]

```

A recursive function accepting a list of positive integers which returns a list of non-negative integers.

**Try it online!**
> 3 votes

# Answer
# Jelly, 5 bytes

```
_ƝƬa/

```

Try it online!

We can assume the whole pyramid is positive, so we can use a && operation instead of a "right" operation.
> 3 votes

# Answer
# Pari/GP, 36 bytes

Based on @Lynn's comment:

> Free insight that I can't find a language it's shorter in: $$f(\[a,b,c,d,e\]) = \begin{bmatrix} 1&-4&6&-4&1 \\ 0&1&-3&3&-1 \\ 0&0&1&-2&1 \\ 0&0&0&1&-1 \\ 0&0&0&0&1 \end{bmatrix} \cdot \begin{bmatrix}a\\b\\c\\d\\e\end{bmatrix}$$

Pari/GP has a built-in for the Pascal matrix, and its inverse is exactly the matrix we need:

$$\begin{bmatrix} 1&0&0&0&0 \\ 1&1&0&0&0 \\ 1&2&1&0&0 \\ 1&3&3&1&0 \\ 1&4&6&4&1 \end{bmatrix}^{-1} = \begin{bmatrix} 1&0&0&0&0 \\ -1&1&0&0&0 \\ 1&-2&1&0&0 \\ -1&3&-3&1&0 \\ 1&-4&6&-4&1 \end{bmatrix}$$

```
a->r=Vecrev;r(r(a)/matpascal(#a-1)~)

```

Try it online!
> 3 votes

# Answer
# , ~~69~~ 67 bytes

```
function(n,x=sum(n|1):1-1,`[`=outer)(x[x,choose]*(-1)^x[x,"+"])%*%n

```

Try it online!

Returns a column vector.

-2 bytes thanks to Kirill L.

Also based on Lynn's comment:

> Free insight that I can't find a language it's shorter in: $$f(\[a,b,c,d,e\]) = \begin{bmatrix} 1&-4&6&-4&1 \\ 0&1&-3&3&-1 \\ 0&0&1&-2&1 \\ 0&0&0&1&-1 \\ 0&0&0&0&1 \end{bmatrix} \cdot \begin{bmatrix}a\\b\\c\\d\\e\end{bmatrix}$$

It's longer than the other R answer, but it was an interesting approach to take and try to golf.
> 3 votes

# Answer
# , ~~55~~ ~~63~~ ~~55~~ 53 bytes

```
x=scan();for(i in sum(1|x):1){F[i]=x[i];x=-diff(x)};F

```

Try it online!

-2 bytes thanks to Giuseppe.
> 2 votes

# Answer
# Javascript (ES6), 127 bytes

```
f=a=>{for(e=[a],a=[a[l=a.length-1]],i=0;i<l;i++){for(e.push(g=[]),j=-1;j<l;)g.push(e[i][j]-e[i][++j]);r.unshift(g[j])}return r}

```

Original code

```
function f(a){
  var e=[a];
  var r=[a[a.length-1]];
  for (var i=1;i<a.length;i++){
    var g=[];
    for (var j=0;j<a.length;j++){
      g.push(e[i-1][j-1]-e[i-1][j]);
    }
    e.push(g);
    r.unshift(g[j-1]);
  }
  return r;
}

```

Oh, I lost like... a lot... to the previous answer...
> 2 votes

# Answer
# Perl 6, 37 bytes

```
{[R,]($_,{@(.[]Z-.skip)}...1)[*;*-1]}

```

Try it online!

Repeatedly reduces by elementwise subtraction, and then returns the last number of each list in reverse.

### Explanation:

```
{                                  }  # Anonymous code block
      $_,               ...   # Create a sequence starting from the input
         {             }      # Where each element is
            .[]Z-.skip          # Each element minus the next element
          @(          )         # Arrayified
                           1  # Until the list has one element left
 [R,]                                # Reverse the sequence
     (                     )[*;   ]  # For every list
                               *-1   # Take the last element

```
> 2 votes

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

```
R.¥.Γ¥}¨ζнR

```

Port of *@JonathanAllan*'s Jelly answer, although I'm *jelly* about Jelly's more convenient builtins in this case. ;)
-1 byte thanks to *@Emigna*.

Try it online or verify all test cases.

**Explanation:**

```
R            # Reverse the (implicit) input-list
             #  i.e. [16,7,4,3] → [3,4,7,16]
 .¥          # Undelta it (with leading 0)
             #  → [0,3,7,14,30]
   .Γ }      # Continue until the result no longer changes, and collect all steps:
     ¥       #  Get the deltas / forward differences of the current list
             #  → [[3,4,7,16],[1,3,9],[2,6],[4],[]]
       ¨     # Remove the trailing empty list
             #  → [[3,4,7,16],[1,3,9],[2,6],[4]]
        ζ    # Zip/transpose; swapping rows/column (with space as default filler)
             #  → [[3,1,2,4],[4,3,6," "],[7,9," "," "],[16," "," "," "]]
         н   # Only leave the first inner list
             #  → [3,1,2,4]
          R  # Revert it back
             #  → [4,2,1,3]
             # (after which it's output implicitly as result)

```
> 2 votes

# Answer
# Wolfram Language (Mathematica), 57 bytes

```
(r=Reverse)[#&@@@Most@NestList[Differences,r@#,Tr[1^#]]]&

```

Try it online!
> 2 votes

# Answer
# Python 2, 78 bytes

```
lambda n,*a:R(lambda r,v:R(lambda x,w:x+[w-x[-1]],r,[v]),a,[n])[::-1]
R=reduce

```

Try it online!
> 1 votes

# Answer
# Japt, ~~11~~ 9 bytes

```
Nc¡=äa
yÌ

```

Try it

2 bytes saved thanks to Oliver.

## ~~12~~ 11 bytes

```
_äa}hUÊN yÌ

```

Try it

1 byte saved thanks to Oliver.
> 1 votes

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

```
a=>{int x=a.Length;var l=new int[x][];for(int i=0;i<x;i++){l[i]=new int[x];l[i][0]=a[i];for(int j=0;j<i;j++)l[i][j+1]=l[i-1][j]-l[i][j];}return l.Last().Reverse();}

```

Try it online!
> 1 votes

# Answer
# APL+WIN, 34 or 28 bytes

```
v←⊂⌽⎕⋄1↓⌽↑¨⍎∊'v',(∊⍴¨v)⍴⊂',-2-/¨v'

```

Try it online! Courtesy of Dyalog Classic

Prompts for right side vector.

or implementing @Lynn's approach:

```
0⍕⌽(⌹⍉n∘.!n←0,⍳¯1+⍴n)+.×⌽n←⎕

```

Try it online!Courtesy of Dyalog Classic

Prompts for right side vector.
> 1 votes

# Answer
# Charcoal, 19 bytes

```
Ｆθ«ＰＩ§θ±¹↑ＵＭθ⁻§θ⊖λκ

```

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

```
Ｆθ«

```

Loop once for each term in the original list.

```
ＰＩ§θ±¹↑

```

Print the last term in the list, but move the cursor to the beginning of the previous line, so that the terms are output in reverse order.

```
ＵＭθ⁻§θ⊖λκ

```

Compute the deltas, inserting a dummy value at the beginning so that we can use an operation that doesn't change the length of the list.
> 1 votes

# Answer
# Attache, 29 bytes

```
{y.=Delta@-_If[_,$@y'_@-1,y]}

```

Try it online!

Simply iterates the `Delta` function until its empty. Much shorter than the very verbose `PeriodicSteps` solution...
> 1 votes

# Answer
# C, 76 bytes

```
i=0;int*f(int*a,int n){for(;i<n;a[i++]=a[i]-a[i+1]);if(!n)return a;f(a,n-1);}

```

**input** : `(*a = pointer to array, n = last element's index of that array)`
**output** : `return int* = output`

**Explanation**
going from right side to up, as the last elements are same in both input and output the loop inside function simply finds next higher numbers in the triangle gradually reaching to the top leaving the answer intact in the end.

**ungolfed(from C++)**

```
#include <iostream>
#define SIZE_F 5

int*recFind(int*a, int n) {
    int i = 0;
    while (i < n)
        a[i++] = a[i] - a[i+1];
    if (!n) return a;
        recFind(a, n - 1);
}
int main()
{
    int first[SIZE_F],*n;
    for (int i = 0; i < SIZE_F; i++)
        std::cin >> first[i];

    n = recFind(first, SIZE_F - 1);//size - 1
    for (int i = 0; i < SIZE_F; i++)
        std::cout << n[i];
}

```
> 1 votes

# Answer
# Julia 0.6, 44 bytes

```
x->reverse([(j=x[end];x=-diff(x);j)for i=x])

```

Try it online!

Same iterative principle as my R answer.

# Julia 0.6, 55 bytes

```
x->inv([binomial(i,j)for i=(l=length(x)-1:-1:0),j=l])*x

```

Try it online!

@Lynn's algorithm (inverse of Pascal matrix multiplied by input).
> 1 votes

---
Tags: code-golf, math, fastest-algorithm, algorithm
---


title: A Note on N!

text:
# Question
Title: A Note on N!
J. E. Maxfield proved following theorem (see DOI: 10.2307/2688966):

> If \\$A\\$ is any positive integer having \\$m\\$ digits, there exists a positive integer \\$N\\$ such that the first \\$m\\$ digits of \\$N!\\$ constitute the integer \\$A\\$.

### Challenge

Your challenge is given some \\$A \geqslant 1\\$ find a corresponding \\$N \geqslant 1\\$.

### Details

* \\$N!\\$ represents the factorial \\$N! = 1\cdot 2 \cdot 3\cdot \ldots \cdot N\\$ of \\$N\\$.
* The digits of \\$A\\$ in our case are understood to be in base \\$10\\$.
* Your submission should work for arbitrary \\$A\geqslant 1\\$ given enough time and memory. Just using e.g. 32-bit types to represent integers is not sufficient.
* You don't necessarily need to output the *least* possible \\$N\\$.

### Examples

```
A            N
1            1
2            2
3            9
4            8
5            7
6            3
7            6
9           96
12           5
16          89
17          69
18          76
19          63
24           4
72           6
841      12745
206591378  314

```

The least possible \\$N\\$ for each \\$A\\$ can be found in https://oeis.org/A076219

# Answer
> 14 votes
# Python 2, 50 bytes

```
f=lambda a,n=2,p=1:(`p`.find(a)and f(a,n+1,p*n))+1

```

Try it online!

This is a variation of the 47-byte solution explained below, adjusted to return `1` for input `'1'`. (Namely, we add `1` to the full expression rather than the recursive call, and start counting from `n==2` to remove one layer of depth, balancing the result out for all non-`'1'` inputs.)

## Python 2, 45 bytes (maps 1 to `True`)

```
f=lambda a,n=2,p=1:`-a`in`-p`or-~f(a,n+1,p*n)

```

This is another variation, by @Jo King and @xnor, which takes input as a number and returns `True` for input `1`. Some people think this is fair game, but I personally find it a little weird.

But it costs only 3 bytes to wrap the icky Boolean result in `+()`, giving us a shorter "nice" solution:

## Python 2, 48 bytes

```
f=lambda a,n=2,p=1:+(`-a`in`-p`)or-~f(a,n+1,p*n)

```

> This is my previous solution, which returns `0` for input `'1'`. It would have been valid if the question concerned a *non-negative `N`*.
>
> ## Python 2, 47 bytes (invalid)
>
> ```
> f=lambda a,n=1,p=1:`p`.find(a)and-~f(a,n+1,p*n)
>
> ```
>
> Try it online!
>
> Takes a string as input, like `f('18')`.
>
> The trick here is that `x.find(y) == 0` precisely when `x.startswith(y)`.
>
> The `and`-expression will short circuit at ``p`.find(a)` with result `0` as soon as ``p`` starts with `a`; otherwise, it will evaluate to `-~f(a,n+1,p*n)`, id est `1 + f(a,n+1,p*n)`.
>
> The end result is `1 + (1 + (1 + (... + 0)))`, `n` layers deep, so `n`.

# Answer
> 9 votes
# Brachylog, ~~3~~ 5 bytes

```
ℕ₁ḟa₀

```

Try it online!

Takes input through its output variable, and outputs through its input variable. (The other way around, it just finds arbitrary prefixes of the input's factorial, which isn't quite as interesting.) Times out on the second-to-last test case on TIO, but does fine on the last one. I've been running it on 841 on my laptop for several minutes at the time of writing this, and it hasn't actually spit out an answer yet, but I have faith in it.

```
         The (implicit) output variable
   a₀    is a prefix of
  ḟ      the factorial of
         the (implicit) input variable
ℕ₁       which is a positive integer.

```

Since the only input `ḟa₀` doesn't work for is 1, and 1 is a positive prefix of 1! = 1, `1|ḟa₀` works just as well.

Also, as of this edit, 841 has been running for nearly three hours and it still hasn't produced an output. I guess computing the factorial of every integer from 1 to 12745 isn't exactly fast.

# Answer
> 7 votes
# C++ (gcc), ~~107~~ 95 bytes, using `-lgmp` and `-lgmpxx`

Thanks to the people in the comments for pointing out some silly mishaps.

```
#import<gmpxx.h>
auto f(auto A){mpz_class n,x=1,z;for(;z!=A;)for(z=x*=++n;z>A;z/=10);return n;}

```

Try it online!

Computes \\$n!\\$ by multiplying \\$(n-1)!\\$ by \\$n\\$, then repeatedly divides it by \\$10\\$ until it is no longer greater than the passed integer. At this point, the loop terminates if the factorial equals the passed integer, or proceeds to the next \\$n\\$ otherwise.

# Answer
> 6 votes
# Jelly, 8 bytes

```
1!w⁼1ʋ1#

```

Try it online!

Takes an integer and returns a singleton.

# Answer
> 6 votes
# 05AB1E, 7 bytes

```
∞.Δ!IÅ?

```

Try it online or verify -almost- all test cases (`841` times out, so is excluded).

**Explanation:**

```
∞.Δ      # Find the first positive integer which is truthy for:
   !     #  Get the factorial of the current integer
    IÅ?  #  And check if it starts with the input
         # (after which the result is output implicitly)

```

# Answer
> 2 votes
# JavaScript, ~~47~~ 43 bytes

Output as a BigInt.

```
n=>(g=x=>`${x}`.search(n)?g(x*++i):i)(i=1n)

```

Try It Online!

Saved a few bytes by taking Lynn's approach of "building" the factorial rather than calculating it on each iteration so please upvote her solution as well if you're upvoting this one.

# Answer
> 2 votes
# Pyth - 8 bytes

```
f!x`.!Tz

f              filter. With no second arg, it searches 1.. for first truthy
 !             logical not, here it checks for zero
  x    z       indexof. z is input as string
   `           string repr
    .!T        Factorial of lambda var

```

Try it online.

# Answer
> 2 votes
# C# (.NET Core), 69 + 22 = 91 bytes

```
a=>{var n=a/a;for(var b=n;!(b+"").StartsWith(a+"");b*=++n);return n;}

```

Try it online!

Uses `System.Numerics.BigInteger` which requires a `using` statement.

-1 byte thanks to @ExpiredData!

# Answer
> 1 votes
# Python 3, 63 bytes

```
f=lambda x,a=2,b=1:str(b).find(str(x))==0and a-1or f(x,a+1,b*a)

```

Try it online!

-24 bytes thanks to Jo King

-3 bytes thanks to Chas Brown

# Answer
> 1 votes
# Jelly, 16 bytes

```
‘ɼ!³;D®ß⁼Lḣ@¥¥/?

```

Try it online!

### Explanation

```
‘ɼ                | Increment the register (initially 0)
  !               | Factorial
   ³;             | Prepend the input
     D            | Convert to decimal digits
        ⁼   ¥¥/?  | If the input diguts are equal to...
         Lḣ@      | The same number of diguts from the head of the factorial
      ®           | Return the register
       ß          | Otherwise run the link again

```

# Answer
> 1 votes
# Perl 6, 23 bytes

```
{+([\*](1..*).../^$_/)}

```

Try it online!

### Explanation

```
{                     }  # Anonymous code block
   [\*](1..*)            # From the infinite list of factorials
             ...         # Take up to the first element
                /^$_/    # That starts with the input
 +(                  )   # And return the length of the sequence

```

# Answer
> 1 votes
# Charcoal, 16 bytes

```
⊞υ¹Ｗ⌕ＩΠυθ⊞υＬυＩ⊟υ

```

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

```
⊞υ¹

```

Push `1` to the empty list so that it starts off with a defined product.

```
Ｗ⌕ＩΠυθ

```

Repeat while the input cannot be found at the beginning of the product of the list...

```
⊞υＬυ

```

... push the length of the list to itself.

```
Ｉ⊟υ

```

Print the last value pushed to the list.

# Answer
> 1 votes
# Perl 5 `-Mbigint -p`, 25 bytes

```
1while($.*=++$\)!~/^$_/}{

```

Try it online!

# Answer
> 1 votes
# , <sup>~~28~~</sup> 22 bytes

*-6 bytes thanks to FrownyFrog*

```
(]+1-0{(E.&":!))^:_&1x

```

Try it online!

# original answer , 28 bytes

```
>:@]^:(-.@{.@E.&":!)^:_ x:@1

```

Try it online!

* `>:@] ... x:@1` starting with an extended precision `1`, keep incrementing it while...
* `-.@` its not the case that...
* `{.@` the first elm is a starting match of...
* `E.&":` all the substring matches (after stringfying both arguments `&":`) of searching for the original input in...
* `!` the factorial of the number we're incrementing

# Answer
> 1 votes
# C (gcc) -lgmp, 161 bytes

```
#include"gmp.h"
f(a,n,_,b)char*a,*b;mpz_t n,_;{for(mpz_init_set_si(n,1),mpz_init_set(_,n);b=mpz_get_str(0,10,_),strstr(b,a)-b;mpz_add_ui(n,n,1),mpz_mul(_,_,n));}

```

Try it online!

# Answer
> 0 votes
# Jelly, 11 bytes

```
‘ɼµ®!Dw³’µ¿

```

Try it online!

# Answer
> 0 votes
# Clean, 88 bytes

```
import StdEnv,Data.Integer,Text
$a=hd[n\\n<-[a/a..]|startsWith(""<+a)(""<+prod[one..n])]

```

Try it online!

Defines `$ :: Integer -> Integer`.

Uses `Data.Integer`'s arbitrary size integers for IO.

# Answer
> 0 votes
# Wolfram Language (Mathematica), 62 bytes

```
(b=1;While[⌊b!/10^((i=IntegerLength)[b!]-i@#)⌋!=#,b++];b)&

```

Try it online!

# Answer
> 0 votes
# Ruby, 40 bytes

```
->n{a=b=1;a*=b+=1until"%d"%a=~/^#{n}/;b}

```

Try it online!

# Answer
> 0 votes
# Icon, ~~65~~ 63 bytes

```
procedure f(a);p:=1;every n:=seq()&1=find(a,p*:=n)&return n;end

```

Try it online!

# Answer
> 0 votes
# Haskell, 89 bytes

```
import Data.List
a x=head$filter(isPrefixOf$show x)$((show.product.(\x->[1..x]))<$>[1..])

```

If anyone knows how to bypass the required import, let me know.

---
Tags: code-golf, math, number, integer, factorial
---


title: Maximizing by swapping

text:
# Question
Title: Maximizing by swapping
# Input

An integer n in the range 100 to 10^18 and an integer k in the range 1 to 18, inclusive.

# The swap operation

A swap chooses two digits at different positions and exchanges their positions, as long as the swap does not result in a leading zero. For example if we start with the integer `12345` we can perform one swap to make it `12543`.

# Task

Output the largest number you can get after exactly k swaps.

# Examples

```
n = 1283, k = 2. Output: 8312
n = 510, k = 1. Output: 501
n = 501, k = 2. Output: 501
n = 999, k = 3. Output: 999
n = 12345678987654321, k = 1. Output: 92345678187654321

```

# Answer
> 5 votes
# Python 3, ~~194~~ ~~190~~ ~~196~~ ~~193~~ ~~175~~ ~~164~~ 162 bytes

```
def f(n,k):
 for i in range(len(n)-1):
  y=max(n[i:]);j=n[::-1].index(y)
  if(y>n[i])*k:n[i],n[~j]=y,n[i];k-=1
 if len(n)-len({*n})<k%2:n[-2:]=n[:-3:-1]
 return n

```

Try it online!

Pretty tough to golf this challenge in a real world language - I like it :)

After golfing down to 190 bytes (and below..), I found some cases where the algorithm would not find the maximum possible value. Bugfixing forced me back up to ~~196~~ 193 bytes :/

... then I found some ways to better handle branching on `k` and went down below 180 :)

After the comment from Chas Brown, switching from integer to list I/O saved 28 bytes! (And more golfing another 2..)

Then, another bug: the algorithm incorrectly handles remaining swaps, if there are equal digits present. The fix cost 19 bytes.

### Algorithm:

1. For each digit, starting from the leftmost one, swap it with the rightmost maximum digit, if that one is bigger. First line of the `for`-loop finds the maximum and its index. Second line does the swap.
2. If there are `k'` swaps left, swap two equal digits, or the two rightmost `k'` times. I.e. if there are two equal digits present, or if `k'` is even, no more swaps have to be done. Else, just swap the last two digits once.

# Answer
> 3 votes
# Jelly, 16 bytes

```
JŒ!nJ$S⁼ɗƇ2ị⁸Ṁµ¡

```

**Try it online!**

A dyadic Link accepting a list of digits (as non-negative integers) on the left and a non-negative integer on the right which yields a list of digits.

### How?

```
JŒ!nJ$S⁼ɗƇ2ị⁸Ṁµ¡ - Link: L, n
              µ¡ - repeat the monad to the left n times -- i.e. f(f(f(...(L)...))):
J                -   range of length
 Œ!              -   all permutations
         Ƈ       -   filter keep if:
        ɗ 2      -     last three links as a dyad with right argument 2
     $           -       last two links as a monad:
    J            -         range of length
   n             -         not equal? (vectorises)
      S          -       sum
       ⁼         -       equal?
           ị     -   index into (vectorises):
            ⁸    -     chain's left argument, L
             Ṁ   -   maximum

```

---

**20 byte version** which is fine within the previous time-constraint since \\$\binom{18}2=\frac{18\times 17}2=153\\$

```
JŒcœṖḢ;Ḣ€ṚżƊƊFɗ€⁸Ṁµ¡

```

Try it online!

### How?

```
JŒcœṖḢ;Ḣ€ṚżƊƊFɗ€⁸Ṁµ¡ - Link: L, n
                  µ¡ - repeat the monad to the left n times -- i.e. f(f(f(...(L)...))):
J                    -   range of length
 Œc                  -   all (length(L)-choose-2) pairs: [[1,2],[1,3],[1,4],...,[2,3],[2,4],...]
               €     -   for each (such pair, P):
              ɗ ⁸    -     last three links as a dyad, with right argument L:
   œṖ                -       partition (L) at indexes (P) - call this X
            Ɗ        -       last three links as a monad - i.e. f(X):
     Ḣ               -         head (of X) (the items up to but not including the first to swap)
           Ɗ         -         last three links as a monad - i.e. f(X):
       Ḣ€            -           head each (actually removes them too) (the items to swap)
         Ṛ           -           reverse
          ż          -           zip with (the altered X)
      ;              -         concatenate
             F       -       flatten
                 Ṁ   -   maximum

```

# Answer
> 3 votes
# Python 2, ~~185~~ ~~177~~ ~~173~~ ~~166~~ ~~164~~ ~~161~~ 152 bytes

```
def f(a,k):exec"i=0;j=L=len(a)-1\nwhile i<L>0<a[i]==max(a[i:]):i+=1\nwhile a[j]<max(a[i:]):j-=1\nj-=i==j<=L<len(set(a));a[i],a[j]=a[j],a[i];"*k;return a

```

Try it online!

Takes a list of digits and an integer k; returns a list of digits.

```
j-=i==j<=L<len(set(a))

```

uses a bunch of shortcuts, and is the same as:

```
if i==j:                     # if i==j, then the list is already sorted
    if len(a)-1<len(set(a)): # since len(a)>=len(set(a)) is *always* True,
                             # this means len(a)==len(set(a), i.e,
                             # a has no duplicated digits,
        j = i-1              # so do a swap with the rightmost digits

```

# Answer
> 2 votes
# Python 2, 113 bytes

```
f=lambda l,k,E=enumerate:l*0**k or f(max(l[:i]+[y]+l[i+1:j]+[x]+l[j+1:]for(i,x)in E(l)for j,y in E(l)if i<j),k-1)

```

Try it online!

Greedily does the best swap at each step, found by testing all possible swaps and taking the maximum.

# Answer
> 1 votes
# PowerShell, 162 bytes

```
$f={param($s,$k)if($k--){$s=if($s.length-le2){&$f($s[1]+$s[0])$k}else{($m=($s|% t*y|sort)[-1])+(&$f(($s-replace"(?<!$m.*)$m",$s[0])|% s*g 1)($k+=$s[0]-eq$m))}}$s}

```

Try it online!

The Recursive Function. Less golfed:

```
$f={
    param($s,$k)
    if($k--){
        $s=if($s.length-le2){
            &$f ($s[1]+$s[0]) $k
        }
        else{
            $max=($s|% t*y|sort)[-1]
            $k+=$s[0]-eq$max
            $s=$s-replace"(?<!$max.*)$max",$s[0]
            $s=$s|% subString 1
            $max+(&$f $s $k)
        }
    }
    $s
}

```

---

## Alternative, 169 bytes

```
param($s,$k)1..$k|%{do{if($s.length-le2){$s=-join$s[1,0]
$r=0}else{$m+=($c=($s|% t*y|sort)[-1])
$r=$s[0]-eq$c
$s=($s-replace"(?<!$c.*)$c",$s[0])|% s*g 1}}while($r)}$m+$s

```

---
Tags: code-golf
---


title: What date is that again?

text:
# Question
Title: What date is that again?
On my website, users enter their date of birth in the style `xx.xx.xx` \- three two-digit numbers separated by dots. Unfortunately, I forgot to tell the users exactly which format to use. All I know is that one section is used for the month, one for the date, and one for the year. The year is definitely in the 20th century (1900-1999), so the format `31.05.75` means `31 May 1975`. Also, I'm assuming everyone uses either the Gregorian or the Julian calendar.

Now, I want to go through my database to clear up the mess. I'd like to start by dealing with the users with the most ambiguous dates, that is, those where the range of possible dates is the biggest.

For example, the date `08.27.53` means `27 August 1953` in either the Gregorian or Julian calendar. The date in the Julian calendar is 13 days later, so the range is just `13 days`.

In contrast, the notation `01.05.12` can refer to many possible dates. The earliest is `12 May 1901 (Gregorian)`, and the latest is `1 May 1912 (Julian)`. The range is `4020 days`.

## Rules

* Input is a string in the format `xx.xx.xx`, where each field is two digits and zero-padded.
* Output is the number of days in the range.
* You can assume that the input will always be a valid date.
* You may not use any built-in date or calendar functions.
* Shortest code (in bytes) wins.

## Testcases

* `01.00.31` =\> `12`
* `29.00.02` =\> `0` (The only possibility is `29 February 1900 (Julian)`)
* `04.30.00` =\> `13`
* `06.12.15` =\> `3291`

# Answer
> 6 votes
# Pyth, 118 bytes

```
M++28@j15973358 4G&qG2!%H4FN.pmv>dqhd\0cz\.I&&&hN<hN13eN<eNhgFPNaYK+++*365JhtN/+3J4smghdJthNeNInK60aY-K+12>K60;-eSYhSY

```

Try it online: Demonstration or Test Suite.

### Necessary knowledge of Julian and Gregorian Calendars

Julian and Gregorian Calendar are quite similar. Each calendar divides a year into 12 months, each containing of 28-31 days. The exact days in a month are `[31, 28/29 (depends on leap year), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]`. The only difference between the calendars are their definition of a leap year. In the Julian Calendar any year divisible by 4 is a leap year. The Gregorian Calendar is a bit more specific. Any year divisible by 4 is a leap year, except the year divisible by 100 and not divisible by 400.

So in the 20th century only one year is different. The year 1900, which is a leap year in the Julian Calendar, but not a leap year in the Gregorian Calendar. So the only date, that exists in the one calendar but not in the other calendar is the day `29.02.1900`.

Because of the different leap year definition, there's a difference between a date in the Julian Calendar and the Gregorian Calendar. 12 days difference for a date before the `29.02.1900`, and 13 days difference for dates after the `29.02.1900`.

### Simplified Pseudo-Code

```
Y = []  # empty list
for each permutation N of the input date:
   if N is valid in the Julian Calendar:
      K = number of days since 0.01.1900
      append K to Y
      if K != 60:  # 60 would be the 29.02.1900
         L = K - (12 if K < 60 else 13)
         append L to Y
print the difference between the largest and smallest value in Y

```

### Detailed Code Explanation

The first part `M++28@j15973358 4G&qG2!%H4` defines a function `g(G,H)`, which calculates the number of days in month `G` of a year `H` in the Julian Calendar.

```
M                            def g(G,H): return
      j15973358 4               convert 15973358 into base 4
     @           G              take the Gth element
  +28                           + 28
 +                &qG2!%H4      + (G == 2 and not H % 4)

```

And the next part is just the for loop, and the ifs. Notice that I interpret `N` in the format `(month, year, day)`. Just because it saves some bytes.

```
FN.pmv>dqhd\0cz\.
             cz\.        split input by "."
    mv>dqhd\0            map each d of ^ to: eval(d[d[0]=="0":])
FN.p                     for N in permutations(^):

I&&&hN<hN13eN<eNhgFPN
I                          if
    hN                        month != 0
   &                          and
      <hN13                   month < 13
  &                           and
           eN                 day != 0
 &                            and
             <eNhgFPN         day < 1 + g(month,year):

aYK+++*365JhtN/+3J4smghdJthNeN
          JhtN                    J = year
     +*365J   /+3J4               J*365 + (3 + J)/4
    +              smghdJthN      + sum(g(1+d,year) for d in [0, 1, ... month-2])
   +                        eN    + day
  K                               K = ^
aYK                               append K to Y

InK60aY-K+12>K60
InK60                             if K != 60:
     aY-K+12>K60                    append K - (12 + (K > 60)) to Y

;-eSYhSY
;          end for loop
 -eSYhSY   print end(sorted(Y)) - head(sorted(Y))

```

# Answer
> 0 votes
# Perl 5, 294 bytes

```
sub f{map/(\d\d)(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])/             #1
      &&$3<29+($2==2?!($1%4):2+($2/.88)%2)                        #2
      &&($j{$_}=++$j+12)                                          #3
      &&$j!#1=60?$g{$_}=++$g:0,'000101'..'991231'if!%g;           #4
      pop=~/(\d\d).(\d\d).(\d\d)/;                                #5
      @n=sort{$a<=>$b}                                            #6
         grep$_,                                                  #7
         map{($j{$_},$g{$_})}                                     #8
         ("$1$2$3","$1$3$2","$2$1$3","$2$3$1","$3$1$2","$3$2$1"); #9
      $n[-1]-$n[0]}                                               #10

```

Try it online!

298 bytes when spaces, newlines and comments are removed.

Lines 1-4 initializes (if not done) the `%g` and `%j` hashes where the values are the Gregorian and Julian day numbers accordingly counting from Jaunary 1st 1900 up to December 31st 1999.

Line 5 puts input date into $1, $2 and $3.

Line 9 lists all six permutations of those three input numbers.

Line 8 converts those six into two numbers each, the Gregorian and the Julian day numbers, but only those who are valid dates.

Line 7 makes sure of that, it filters out non existant day numbers.

Line 6 sorts the list of valid date numbers from the smallest to the largest.

Line 10 returns then difference between the last and first (max and min), which was the wanted range.

---
Tags: code-golf, date
---