# Question
Title: Is this a Hardy-Ramanujan-Number-ish Harshad Number?
## Background

The number 1729 is the Hardy-Ramanujan number. An amazing property of it was discovered by S. Ramanujan (who is widely regarded as the greatest Indian mathematician1), when G.H. Hardy paid a visit to him in a hospital. In Hardy's own words:

> I remember once going to see him when he was ill at Putney. I had ridden in taxi cab number 1729 and remarked that the number seemed to me rather a dull one, and that I hoped it was not an unfavorable omen. "No," he replied, "it is a very interesting number; it is the smallest number expressible as the sum of two cubes in two different ways."

Besides that, it has many other amazing properties. One such property is that it's a Harshad Number, i.e the sum of its digits (1+7+2+9=19) is a factor of it. That too, a special one. As Masahiko Fujiwara showed, 1729 is a positive integer which, when its digits are added together, produces a sum which, when multiplied by its reversal, yields the original number:

1+7+2+9 = 19

19 × 91 = 1729

A positive integer having such property is what I define as Hardy-Ramanujan-*ish* Harshad Number, for the purpose of this post. (There might be a technical term for it, but I couldn't find it, unless it's member of A110921)

---

## The Task

Given a positive integer `n` as input, output a truthy or falsey value based on whether the input `n` is a Hardy-Ramanujan-*ish* Harshad Number. Output truthy, if it is. Otherwise, output falsey.

Note that only four Hardy-Ramanujan-*ish* Harshad Numbers exist (`1`,`81`,`1458` and `1729`), and you can write code which checks for equivalence with them. But I don't think that will be fun.

---

## Input

Your program should take a positive integer (a natural number, in other words). It may take it in any way except assuming it to be present in a variable. Reading from modal window, input box, command line, file etc. is allowed. Taking input as function argument is allowed as well.

---

## Output

Your program should output a truthy or falsey value. They need not be consistent. Your program may output in any way except writing the output to a variable. Writing to screen, command line, file etc. is allowed. Outputting with function `return` is allowed as well.

---

## Additional Rules

* You **must** not use a built-in to accomplish the task (I wonder any language will have such built-in, but then *Mathematica...*)
* Standard Loopholes apply.

---

## Test Cases

```
Input        Output
1            Truthy (because 1 × 1 (reverse of 1) = 1)
2            Falsey
3            Falsey
4            Falsey
5            Falsey
81           Truthy (because 9 (8 + 1) × 9 (reverse of 9) = 81)
1458         Truthy (because 18 (1 + 4 + 5 + 8) × 81 (reverse of 18) = 1458)
1729         Truthy (because 19 (1 + 7 + 2 + 9) × 91 (reverse of 19) = 1729)
1730         Falsey
2017         Falsey

```

---

## Winning Criterion

This is , so the shortest code in bytes wins!

---

1Every year, on 22nd December, the birthday of Srinivasa Ramanujan, National Mathematics Day is observed in India. His colleagues, those in Cambridge, compared him to Jacobi, Euler, and even Newton. Besides being so great, he had almost no formal training in *Pure Mathematics*, but still, he made important contributions to *mathematical analysis*, *number theory*, *infinite series*, and *continued fractions*. Unfortunately, he died at an early age of 32 with thousands of mathematical discoveries in his mind. A film was also made on him, which was based on his biography, *The Man Who Knew Infinity*.

# Answer
# Neim, 5 bytes

```
D

```

Explanation:

```
Example input: 1729
      Implicitly convert to digit list and um the digits [19]
 D     Duplicate [19, 19]
      everse [19, 91]
      muliply [1729]
      check for quality with input [1]
Implicit output: 1

```

Try it!
> 12 votes

# Answer
# ArnoldC, 888 Bytes

```
IT'S SHOWTIME
HEY CHRISTMAS TREE i
YOU SET US UP 0
GET YOUR ASS TO MARS i
DO IT NOW
I WANT TO ASK YOU A BUNCH OF QUESTIONS AND I WANT TO HAVE THEM ANSWERED IMMEDIATELY
HEY CHRISTMAS TREE a
YOU SET US UP 0
GET TO THE CHOPPER a
HERE IS MY INVITATION 1
YOU ARE NOT YOU YOU ARE ME i
ENOUGH TALK
HEY CHRISTMAS TREE b
YOU SET US UP 0
GET TO THE CHOPPER b
HERE IS MY INVITATION 81
YOU ARE NOT YOU YOU ARE ME i
ENOUGH TALK
HEY CHRISTMAS TREE c
YOU SET US UP 0
GET TO THE CHOPPER c
HERE IS MY INVITATION 1458
YOU ARE NOT YOU YOU ARE ME i
ENOUGH TALK
HEY CHRISTMAS TREE d
YOU SET US UP 0
GET TO THE CHOPPER d
HERE IS MY INVITATION 1729
YOU ARE NOT YOU YOU ARE ME i
ENOUGH TALK
HEY CHRISTMAS TREE res
YOU SET US UP 0
GET TO THE CHOPPER res
HERE IS MY INVITATION a
CONSIDER THAT A DIVORCE b
CONSIDER THAT A DIVORCE c
CONSIDER THAT A DIVORCE d
ENOUGH TALK
TALK TO THE HAND res
YOU HAVE BEEN TERMINATED

```

I know, I just check for equality, but that shouldn't be the fun part of the program.

Enjoy reading it. :)

Added some newlines there for easier readability:

Try it online
> 15 votes

# Answer
# x86 Assembly, ~~55~~ ~~35~~ ~~33~~ 31 bytes:

Assumes an ABI where the return value is in EAX and parameters are pushed on the stack... so almost all of them.

```
00000000: 8B 44 24 04        mov         eax,dword ptr [esp+4]
00000004: 48                 dec         eax
00000005: 74 16              je          0000001D
00000007: 83 E8 50           sub         eax,50h
0000000A: 74 11              je          0000001D
0000000C: 2D 61 05 00 00     sub         eax,561h
00000011: 74 0A              je          0000001D
00000013: 2D 0F 01 00 00     sub         eax,10Fh
00000018: 74 03              je          0000001D
0000001A: 33 C0              xor         eax,eax
0000001C: C3                 ret
0000001D: 40                 inc         eax
0000001E: C3                 ret

```
> 12 votes

# Answer
# Brachylog, 8 bytes

```
ẹ+S↔;S×?

```

Try it online!
> 4 votes

# Answer
# Haskell, ~~56~~ 55 bytes

```
f n|m<-sum$read.pure<$>show n=n==m*(read.reverse.show)m

```

Try it online!

---

**Pointfree:** (56 bytes)

```
(==)<*>((*)=<<read.reverse.show).sum.map(read.pure).show

```

Try it online!

---

**Boring:** (24 bytes)

```
(`elem`[1,81,1458,1729])

```

Try it online!
> 4 votes

# Answer
## JavaScript ES6, ~~59~~ 57 bytes

```
x=>(q=eval([...x].join`+`)+'')*[...q].reverse().join``==x

```

Try it online!

Basically splits into digit array, and joins with `+` and evals that expression to basically sum the digits. `string*string` will automatically convert strings into ints. Takes input as a string
> 4 votes

# Answer
## JavaScript (ES6), 72 bytes

This is valid ES6 submission. Add `f=` at the start and invoke like `f(arg)`.

```
n=>(y=[...`${n}`].reduce((c,p)=>+c+ +p))*[...`${y}`].reverse().join``==n

```

---

### Test Snippet:

```
let f =

n=>(y=[...`${n}`].reduce((c,p)=>+c+ +p))*[...`${y}`].reverse().join``==n

console.log(1 + " -> " + f(1))
console.log(81 + " -> " + f(81))
console.log(1458 + " -> " + f(1458))
console.log(1729 + " -> " + f(1729))
console.log((randomNum = Math.floor(Math.random() * 10000) + 1) + " -> " + f(randomNum))
```
> 2 votes

# Answer
# Mathematica, 42 bytes

```
(s=Tr@IntegerDigits@#)IntegerReverse@s==#&

```
> 2 votes

# Answer
# 05AB1E, 5 bytes

```
SOÂ*Q

```

Try it online!
> 2 votes

# Answer
# Ruby, 69 Bytes

First try, with integer as input:

```
->i{(x=i.to_s.split'').inject(0){|s,a|s+a.to_i}*(x[-1]+x[0]).to_i==i}

```

Second try, with string as input:

```
->i{(x=i.split('').map &:to_i).inject(0,&:+)*(x[-1]*10+x[0])==i.to_i}

```
> 2 votes

# Answer
## Batch, 164 bytes

```
@set/an=%1,s=0
:s
@set/as+=n%%10,n/=10
@if %n% gtr 0 goto s
@set/an=s,r=0
:r
@set/ar=r*10+n%%10,n/=10
@if %n% gtr 0 goto r
@set/an=%1-r*s
@if %n%==0 echo 1

```

Prints 1 on success, no output on failure.
> 2 votes

# Answer
## Kotlin, ~~111~~ 108 bytes

```
fun main(a:Array<String>)=print(a[0].sumBy{c->"$c".toInt()}.run{"${this*"$this".reversed().toInt()}"}==a[0])

```

Try it online!

As is typical for statically compiled JVM solutions, a lot of bytes are lost on just the main function declaration and calling print(). The meat of the function is 60ish bytes, which is not bad at all for a general purpose statically typed language like Kotlin.

# Kotlin, boring solution, 69 bytes

```
fun main(a:Array<String>)=print(a[0].toInt()in setOf(1,81,1458,1729))

```

Try it online!
> 2 votes

# Answer
# Python 2, 55 bytes

```
def f(n):x=sum(map(int,`n`));return x*int(`x`[::-1])==n

```

Try it online!

## Explanation

```
def f(n):                           # define a function f that takes an argument n
    x = sum(                        # assign to x the sum of...
            map(int, `n`))          # ...the integer conversion of all elements in stringified n
    return x * int(                 # return True if x times the integer conversion of...
                   `x`[::-1])       # ...the stringified x reversed...
                              == n  # ...equals n

```

An `eval()` solution is a ~~bit~~ 2 bytes longer...

```
def f(n):x=eval('+'.join(`n`));return x*int(`x`[::-1])==n

```

## Alternate ~~(invalid?)~~ solution, ~~42~~ 29 bytes

This solution checks for equality against all of the numbers.

```
lambda n:n in[1,81,1458,1729]

```

Try it online!
> 1 votes

# Answer
# Cheddar, 60 bytes

```
(n,g=x->x?g(x/10|0)+x%10:0)->n==g(n)*number::("%d"%g(n)).rev

```

Try it online!
> 1 votes

# Answer
# NewStack, 16 bytes

```
ḟᵢ¹f YΣ©Eᴙx| ∏=f

```

## The breakdown:

*Using 1729 as example*

```
ḟᵢ                 Define new function equal to input.               []
  ¹                Add 1 to stack.                                   [1]
   f               Multiply stack by the function.                   [1729]
     Y             Split the stack into digits.                      [1,7,2,9]
      Σ            Sum the stack.                                    [19]
       ©           Duplicate stack.                                  [19,19]
        E  |       Define new value for the first element            [19,19]
         ᴙx        Reverse first element.                            [91,19]
             ∏     Take the product.                                 [1729]
              =f   Remove from stack if not equal to the function.   [1729]

```

Prints nothing if false, and the original input if true.
> 1 votes

# Answer
# MATL, 11 bytes

```
tV!UstVPU*=

```

Try it online!

`t` \- take input and duplicate it

`V!U` \- split it into individual digits

`s` \- sum those digits

`t` \- duplicate that sum

`VP` \- turn that into a string, flip it left to right

`U` \- turn that back into a number

`*` \- multiply the last two values (the digit-sum and its left-to-right flipped version)

`=` \- check if this is equal to the original input (which is the only other value in stack)
> 1 votes

# Answer
# Japt, 8 bytes

```
¬x
*sÔ¥N

```

Run it online
> 1 votes

# Answer
# Jelly, 8 bytes

```
DS×ṚḌ$$=

```

Try it online!
> 0 votes

# Answer
# PHP, 52 bytes

```
<?=strrev($x=array_sum(str_split($argn)))*$x==$argn;

```

Try it online!

# PHP, 36 bytes

```
<?=in_array($argn,[1,81,1458,1729]);

```

Try it online!
> 0 votes

# Answer
# Perl 6, 30 bytes

```
{my \n=sum .comb;$_==n*n.flip}

```
> 0 votes

# Answer
# APL (Dyalog), 18 bytes

```
{(⍵=⍎∘⌽×⍎)⍕+/⍎¨⍕⍵}

```

Try it online!
> 0 votes

# Answer
# Pari/GP, ~~56~~ 52 bytes

```
n->n==(s=sumdigits(n))*fromdigits(Vecrev(digits(s)))

```

Try it online!
> 0 votes

# Answer
# MathGolf, 5 bytes

```
Σ_x*=

```

Try it online!

Pretty much the same as the Neim solution byte for byte.
> 0 votes

---
Tags: code-golf, math, number, decision-problem
---


title: Error-detecting Self-repairing Program

text:
# Question
Title: Error-detecting Self-repairing Program
Your task is to create a program where if any one character is deleted, it will detect which character was deleted and then re-insert the deleted character in its own source file.

For instance, if your program is `RadiationHardened` and it is modified to `RadiaionHardened`, then your program must output that the 5th byte (0-indexed) was modified and then the program source must be `RadiationHardened` immediately after execution.

## Notes and rules

* You may assume that exactly one character was deleted in the source code before execution. Behavior for the unmodified program is undefined.
* You may assume the changed byte will be deleted, not transposed, inserted, or replaced.
* In the case of a run of multiple of the same character, you may report either the first or the last index of the run, but be consistent about which you use. For example `baaad` being deleted to `baad` can report either 1 or 3 (zero indexed), but must be the same throughout the entire program.
* You do not need to write out the entire source to its own file. You need only re-insert the deleted byte.
* Unlike the typical rules for radiation-hardened quines, detecting the changed byte from reading the program's own source code is fair game.
* You can output the changed byte index through any reasonable format. Be consistent about whether it is 0-indexed or 1-indexed or any other notation. You may even output a number within a template string.

This is so the shortest program wins.

Good luck!

EDIT1: changed requirement from replacement to deletion

EDIT2: added rule for runs of duplicates

# Answer
> 11 votes
# Befunge-98 (FBBI), ~~344 296~~ 248 bytes

```
20020xxnngg33%%!!2200gg''00--3300gg33%%!!4400gg55%%!!22kk++55##rr55kk::00gg\\11pp00gg\\11++11pp22++00::pp00gg\\11++00gg--!!zz!!22**++00::gg00gg8844**--!!55++jj..''gg::00rr00::gg\\--..''220011''0011::''002211''223311''00441144kkppgg11001100::99oo@@

```

Try it online!

Verification!

Befunge-98 is the first esoteric language that I could find that was both 2D and had file output. This is a full solution (with a trailing newline) stored in a file named as a tab character. It outputs as 0-indexed, and outputs the first index in a run of characters (though there's only ever pairs).

There's a few golfs to be made, ~~especially as there are 15 no-ops in the code~~, now just one no-op! I will be working on making this shorter, with the goal of getting to or below 200 bytes.

# Answer
> 6 votes
# Unefunge-98 (PyFunge), 118 bytes

```
22xx00##rr33kk::gg\\11--pp22++00ppgg\\11++gg--!!zz!!22**--00gg::gg8844**--!!22++jj##''rr++..gg''2200pp0011--00::99oo@@

```

Try it online!

Verification!

While golfing my Befunge-98 answer, I realised I could save some bytes by porting it over to Unefunge, since I would only have to worry about the one dimension rather than the two. This also opened up a lot of possible shortcuts and golfs, which made the new solution much *much* smaller.

### Explanation (de-duplicated):

```
2x        Set the delta of the movement to 2
          This means the pointer moves 2 cells every step
          This will also initialise a counter as 2 (unless a 2 has been removed)
  0       Create the cell counter  (This will be stored at cell 0)
   #r     Enter the loop
     3k:                 Create 3 more copies of the counter
        g                Get the cell at the counter's position
         \1-p            Put it in the cell before that position
             2+0p        Add 2 to the counter and put it in cell 0
                 g       Get the cell at the counter's position
                  \1+g   Get the next cell
                      -!z!2*      If they are identical, push two, else 0
                            --    Subtract it from the total counter
                              0g:g84*-!   If the next character is a space
                                       2+j  r   Exit loop
                                         j#'    Else jump back to the start

Once the loop is over
+      Add the negative counter to the total counter
 .     And print
   '20p          Replace the 2 in cell 0 that was overwritten
             o   Write to a file named
            9    Tab
       01-       The cells from -1 to
  g              The total number of cells
              @  And exit the program

```

---
Tags: code-golf, source-layout, radiation-hardening, error-correction
---


title: Swapless distances

text:
# Question
Title: Swapless distances
Suppose you have a string \\$s\_0\\$ and someone else has a hidden string \\$s\_1\\$. You don't know what \\$s\_1\\$ is but they tell you that they can get from your string, \\$s\_0\\$, to their string by making a certain number of moves \\$d\\$. Each move can be one of the following:

* Insertion : Add a character anywhere in the string
* Deletion : Remove a character from anywhere in the string
* Replacement : Replace one character with another anywhere in the string
* Transposition : swap any two adjacent characters.

(this is Damerau-Levenshtein distance).

The question is how many moves do you need to get from \\$s\_0\\$ to \\$s\_1\\$ *without using the transposition move* (this is Levenshtein distance)?

Your task is to write a program or function that takes a string (list of positive integers is fine too) representing \\$s\_0\\$ and a positive integer representing \\$d\\$ and output the minimal number of moves required to guarantee you can get to \\$s\_1\\$ without transposition in the worst-case scenario.

This is your answer will be scored in bytes with fewer bytes being better.

# Test cases

## Using Strings

```
"Hello", 3 -> 4
"World", 2 -> 4
"aaaaa", 1 -> 1
"aaaaa", 2 -> 2
"abaaa", 3 -> 4
"Krypyp", 3 -> 5
"", 5 -> 5
"Hello", 0 -> 0

```

## Using Integer lists

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

```

# Answer
# Haskell, 186 bytes

```
-- f :: [Int] -> Int -> Int
f s k|let a=pure<$>0:s;d#(x:z)|let w(y:z)|d>0=[y:x:z];w _=[]=[c++y++z|c<-[]:a,y<-[]:[[x]]]++w z++map(x:)(d#z);_#_=a;d%i=iterate((++)<*>((d#)=<<))[s]!!i=[i|i<-[k..],all(`elem`0%i)$1%k]!!0

```

Simple brute force solution. `f` takes a list of positive integers, and the DL-distance `k`.

This generates all strings up to the DL-distance limit `k`, and searches for the smallest L-distance that contains all of those strings (also by generating those strings). This saves bytes by using the same generator code for both types of distances.

Try it online! Note that this is too slow for some of the test cases, so the TIO version uses reduced test cases.

### Pregolfed

Ungolfed version. Unlike the golfed version, this one removes duplicate strings during the generation, so it's also much faster:

```
import qualified Data.Set as S
import Data.List (sortBy)
import Data.Ord (comparing)

snub x = S.toList $ S.fromList x

f' s k =
  let -- 0 = any other symbol not in s
      alphabet = snub $ toEnum 0 : s
      -- all strings with L-distance 1 (if d, DL-distance)
      gen1 d s@(x:xs) = snub $ del ++ ins ++ sub ++ swap xs ++ map (x:) (gen1 d xs)
        where del = [xs]
              ins = map (:s) alphabet
              sub = map (:xs) alphabet
              swap (y:ys) | d = [y:x:ys]
              swap _ = []
      gen1 _ _ = map (:[]) alphabet
      -- as gen1, but distance <= i
      genAll d i = iterate (\x->snub $ x ++ (gen1 d =<< x)) [s] !! i
      -- strings with DL-distance <= k
      sDL = S.fromAscList $ genAll True k
  in head [ (i, worstStrings)
          | -- sL = genAll False i
            -- zip obtains sL' = genAll False (i-1) for calculating worstStrings
            ((_, sL'), (i, sL))
              <- zip <*> tail $ (,) <*> (S.fromAscList . genAll False) <$> [max 0(k-1)..],
            -- require that sL covers sDL
            sDL `S.isSubsetOf` sL,
            -- also show some maximal examples
            let interestingness t = length (filter (==toEnum 0) t) + abs (length t - length s)
                worstStrings =
                  take 5 $ sortBy (comparing interestingness) $
                  S.toList (sL `S.intersection` sDL `S.difference` sL')
            ]

```

Try it online! This uses the full testcases but `Krypyp` still times out on TIO (it takes a few minutes to solve). Also, it prints some of the strings that have maximal Levenshtein distance. Testcase solutions:

```
"hello", 3 -> 4 e.g. "eeeol","eehol","eeool","ehheo","ehhho"
"world", 2 -> 4 e.g. "owrdl"
"aaaaa", 1 -> 1 e.g. "_aaaa","a_aaa","aa_aa","aaa_a","aaaa"
"aaaaa", 2 -> 2 e.g. "__aaa","_a_aa","_aa_a","_aaa","_aaa_"
"abaaa", 3 -> 4 e.g. "aabbb","aab_b","aabb_","_aabab","_aabba"
"Krypyp", 3 -> 5 e.g. "rKyKppy","rKyppKy","rKyppry","rpKyppy","r_Kyppy"
"", 5 -> 5 e.g. "_____"

```
> 3 votes

# Answer
# Java 11, ~~790~~ ~~764~~ 760 bytes

```
import java.util.*;t->n->{var S=new HashSet<String>();int m=n;for(;m>0;)p(S,"",t+"x".repeat(m--));for(var s:(HashSet<String>)S.clone())for(m=s.length()-n;m-->1;)S.add(s.substring(m));S.removeIf(s->d(1,s,t)!=n);for(var s:S)m=Math.max(d(0,s,t),m);return m;}void p(Set S,String p,String s){int l=s.length(),i=0;if(l<1)S.add(p);for(;i<l;)p(S,p+s.charAt(i),s.substring(0,i)+s.substring(++i));}int d(int f,String s,String t){int l=s.length()+1,L=t.length()+1,d[][]=new int[l][L],i=l,j,c,q,A,B;for(;i-->0;)d[i][0]=i;for(j=0;++j<L;)for(d[i=0][j]=j;++i<l;B=t.charAt(j-1),c=A==B?0:1,d[i][j]=q=Math.min(Math.min(d[i-1][j]+1,d[i][j-1]+1),d[i-1][j-1]+c),d[i][j]=f>0&i>1&j>1&&A==t.charAt(j-2)&s.charAt(i-2)==B?Math.min(q,d[i-2][j-2]+c):q)A=s.charAt(i-1);return d[l-1][L-1];}

```

Will golf it down (substantially I hope) from here.

Try it online.

### Explanation:

**General approach:**

Input-String = `t` and input-integer = `n` in the explanation below.

1. Generate all permutations of `t` with up to `n` added characters, and add them to a Set
2. For each permutation, add a substring with up to `n` removed characters to the Set as well
3. Remove any String from this Set that does not have a Damerau-Levenshtein distance of `n` in comparison to `t`
4. Calculate the Levenshtein distance of each remaining String in comparison to `t`
5. Take the maximum, which is our result

**Code explanation:**

```
import java.util.*;               // Required import for the Set and HashSet

t->n->{                           // Method with String and integer parameters and integer return-type
  var S=new HashSet<String>();    //  Create a String-Set
  int m=n;for(;m>1;)              //  Loop `m` in the range [input-integer, 0):
    p(S,"",t                      //   Determine all permutations of the input-String
      +"x".repeat(m--));          //   With up to `m` additional "x" added
  for(var s:(HashSet<String>)S.clone())
                                  //  Loop over all generated permutations:
    for(m=s.length()-n;m-->1;)    //   Inner loop `m` in the range [permutation-length - input-integer, 1]:
      S.add(s.substring(m));      //    Add the permutation with the first `m` characters removed to the Set as well
                                  //  (NOTE: After these loops, `m` is 0 which we'll re-use later on)
  S.removeIf(s->                  //  Now remove any permutation from this Set which:
     d(1,s,t)!=n);                //   Does not have a DL-distance equal to the input-integer
  for(var s:S)                    //  Loop over all remaining Strings:
    m=Math.max(d(0,s,t),m);       //   Determine the maximum L-distance
  return m;}                      //  And return that maximum L-distance as result

// Separated recursive method to get all permutations from a String
void p(Set S,String p,String s){  // Method with Set and two String parameters and no return-type
int l=s.length(),                 //  Get the length of the input-String `s`
    i=0;                          //  Index-integer `i`, starting at 0
if(l<1)                           //  If the length is 0:
  S.add(p);                       //   Add the prefix-String `p` to the Set
for(;i<l;)                        //  Loop `i` in the range [0, length):
  p(S,p+s.charAt(i),              //   Append the `i`'th character to the prefix-String `p`
    s.substring(0,i)+s.substring(++i));}
                                  //   Remove the `i`'th character from the String `s`
                                  //   And do a recursive call

// Separated method to determine the DL or L distance of two Strings
int d(int f,String s,String t){   // Method with integer and two String parameters and String return-type
  int l=s.length()+1,             //  Length `l` of the source-String + 1
      L=t.length()+1,             //  Length `L` of the target-String + 1
      d[][]=new int[l][L],        //  Create an integer matrix of those dimensions
      i=l,j,                      //  Index-integers
      c,q,A,B;                    //  Temp integers
  for(;i-->0;)                    //  Loop `i` in the range (`l`, 0]:
    d[i][0]=i;                    //   Set the `i,0`'th cell to `i` in the matrix
  for(j=0;++j<L;)                 //  Loop `j` in the range [0, `L`):
    for(d[i=0][j]=j;              //   Set the `0,j`'th cell to `j` in the matrix
        ++i<l                     //   Inner loop `i` in the range [0, `l`):
        ;                         //     After every iteration:
         B=t.charAt(j-1),         //      Set `B` to the `j-1`'th character of the target-String
         c=A==B?                  //      If the characters `A` and `B` are the same:
            0                     //       Set `c` to 0
           :                      //      Else:
            1,                    //       Set `c` to 1
         d[i][j]=                 //      Set the `i,j`'th value to:
           q=Math.min(            //       The minimum of:
              Math.min(           //        The minimum of:
                d[i-1][j]+1,      //         The `i-1,j`'th value + 1
                d[i][j-1]+1),     //         And the `i,j-1`'th value + 1
              d[i-1][j-1]+c),     //        And the `i-1,j-1`'th value + `c`
         d[i][j]=                 //      Then, set the `i,j`'th value to:
                 f>0              //       If the given DL-flag is 1
                 &i>1&j>1         //       And both `i` and `j` are at least 2
                 &&A              //       And the character `A`
                   ==t.charAt(j-2)//       equals the `j-2`'th character in the target-String
                 &s.charAt(i-2)   //       And the `i-2`'th character in the source-String
                  ==B?            //       equals the character `B`:
                  Math.min(       //        Set the `i,j`'th value to the minimum of:
                   q,             //         The `i,j`'th value
                   d[i-2][j-2]+c) //         And the `i-2,j-2`'th value + `c`
                 :                //       Else (the given DL-flag is 0):
                  q)              //        Leave the `i,j`'th value the same
      A=s.charAt(i-1);            //    Set `A` to the `i-1`'th character of the source-String
  return d[l-1][L-l];}            //  Return the `l-1,L-1`'th value as result

```
> 0 votes

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


title: Next Friday the 13th

text:
# Question
Title: Next Friday the 13th
What is the shortest program that can predict the next time Friday will fall on the 13th day of the month?

* Must be an complete functioning program (not just a function/subroutine)
* Must print out date in the following format: `YYYY-MM-DD`
* Allow user to provide a start date either as a command line argument or through `STDIN`
* If user provides no start date, use today as the start date.
* If the start date is a Friday the 13th, the program should find the *next* Friday the 13th.

If I were to run the program today (Feb 16 2011) I should get the following output.

```
$ ./fr13th 2013-05-09
2013-09-13
$ ./fr13th 2007-06-29
2007-07-13
$ ./fr13th 2007-07-13
2008-06-13
$ ./fr13th
2011-05-13

```

# Answer
## Windows PowerShell, 74

```
for($d="date $args"|iex;($d+='1').day*$d.dayofweek-65){}'{0:yyy-MM-d}'-f$d

```

Fairly straightforward. One perhaps confusing bit is the use of `"Get-Date $args" | Invoke-Expression` to get either the current date (if `$args` is empty) or the date specified in `$args` without raising an error.

## 72-byte variant:

```
for($d="date $args"|iex;($d+=9).day*$d.dayofweek-65){}'{0:yyy-MM-d}'-f$d

```

Takes ages, though ... this doesn't increment the datetime by a whole day each iteration but instead only 900 nanoseconds. But two bytes shorter.

## 67-byte variant:

```
for($d="date $args"|iex;($d+='1').day*$d.dayofweek-65){}'{0:d}'-f$d

```

This is a bit locale-sensitive; if it fails on your machine, try setting your date format to ISO-8601 beforehand. :-)

Oh, and it can be made into 65 bytes just like the 72-byte version.

History:

* 2011-02-17 00:33 (92) First attempt.
* 2011-02-17 00:35 (85) Improved getting an initial date.
* 2011-02-17 00:37 (79) Compared the product instead of day and day of week individually. Admittedly stolen from Ventero.
* 2011-02-17 00:40 (76) Pulled the first line into the `for`. Comparison just as subtraction instead of `-eq` which saves another two bytes.
* 2011-02-17 00:53 (75) Unix `date` format string is a bit shorter.
* 2011-02-17 11:42 (74) Reverted to the default date pattern but `yyy-MM-d` suffices (since the year is always longer than three characters and the day is always 13. Thanks to Ty Auvil for this.
> 6 votes

# Answer
## Ruby, ~~96~~ 75 characters

```
require"date"
d=Date.parse(gets||"thu")+1
d+=1 while d.wday*d.day!=65
$><<d

```

Takes the date from stdin. To not specify a date press ctrl-d.

Thanks very much for Ventero's help.

Ungolfed:

```
require "date"
# Date.parse("thu") will return this week's thursday
date = Date.parse(gets || "thu")+1
date += 1 while d.wday * d.day != 5 * 13
$stdout << date

```

Sample IO:

```
$ ruby fr13th.rb
2013-05-09
2013-09-13
$ ruby fr13th.rb
2007-06-29
2007-07-13
$ ruby fr13th.rb
2007-07-13
2008-06-13
$ ruby fr13th.rb
2011-05-13

```
> 4 votes

# Answer
## bash, 75

```
until set `date +%F -d$1+day`
date -d$1|grep -q '^F.* 13'
do :
done
echo $1

```

This is a bit locale-sensitive; if it fails on your machine, try `export`ing `LC_ALL=C` beforehand.

```
$ bash fri13th.sh 2013-05-09
2013-09-13
$ bash fri13th.sh 2007-06-29
2007-07-13
$ bash fri13th.sh 2007-07-13
2008-06-13
$ bash fri13th.sh
2011-05-13

```
> 4 votes

# Answer
## C#, 185

Based on Andrew Koester's C# solution, but heavily modified along the way. I eventually arrived at a solution similar to my PowerShell solution:

```
using System;class
P{static void
Main(string[]a){var
n=a.Length>0?DateTime.Parse(a[0]):DateTime.Now;for(;(n=n.AddDays(1)).Day*(int)n.DayOfWeek!=65;);Console.Write("{0:yyy-MM-d}\n",n);}}

```
> 3 votes

# Answer
## Perl (and others), 114

```
for(($y,$m,$d)=(shift//`date +%F`)=~/\d+/g,$d>12&&$m++;$m
>12&&($y++,$m=1),`cal $m $y`!~/14$/m;$m++){}say"$y-$m-13"

```

Perl 5.10 or later, run with `-E 'code here'` or `-M5.010 file`. Needs `date` (from coreutils for Linux) and `cal` (from util-linux)

Sample run:

```
$ perl -M5.010 fr13.pl 2013-05-09
2013-9-13
$ perl -M5.010 fr13.pl 2007-06-29
2007-07-13
$ perl -M5.010 fr13.pl 2007-07-13
2008-6-13
$ perl -M5.010 fr13.pl
2011-5-13

```

I'm not sure when the leading zero for months before October is kept. It's obviously lost when the year rolls over; it seems to be kept when the answer is just next month. Let's call that undefined behavior--hey, this is golfing!
> 2 votes

# Answer
# PHP - 103

(brute force)

```
<?for($d=date_create(@$argv[1]);$d->modify('next fri')&&$d->format(@d)-13;);die($d->format("Y-m-d\n"));

```

Ungolfed:

```
<?
$d = new DateTime(@$argv[1]);
while ($d->modify('next fri')) {
        if ($d->format('d') == 13) {
                die($d->format("Y-m-d\n"));
        }
}

```

Test:

```
$ php 979.php 2013-05-09
2013-09-13
$ php 979.php 2007-06-29
2007-07-13
$ php 979.php 2007-07-13
2008-06-13
$ php 979.php
2011-05-13

```
> 2 votes

# Answer
**BASH**

```
#!/bin/bash
from=$1
if [ "$from" = "" ]; then
from=`date +%Y-%m-%d`
fi
i=1
while [ "$isFri" = "" ] || [ "$is13" = "" ]
do
isFri=`date -d "${from} ${i} days" | grep Fri`
is13=`date -d "${from} ${i} days" +%Y-%m-%d | grep "\-13"`
((i++))
done
((i--))
date -d "${from} ${i} days" +%Y-%m-%d

```

CONCEPT USED:

```
$ date -d "2011-02-16 2 days" +%Y-%m-%d
2011-02-18

```

SAMPLE I/O

```
:~/aman> ./fr13th.sh
2011-05-13
:~/aman> ./fr13th.sh 2013-05-09
2013-09-13
:~/aman> ./fr13th.sh 2007-06-29
2007-07-13
:~/aman> ./fr13th.sh 2007-07-13
2008-06-13

```
> 2 votes

# Answer
## Python - 166 chars

Reads from stdin, so you need to feed a blank line if you want todays date

```
from datetime import*
D=datetime
e=timedelta(1)
I=raw_input()
d=e+(I and D.strptime(I,"%Y-%m-%d")or D.now())
while(d.weekday()+1)*d.day-65:d+=e
print d.strftime("%F")

```
> 2 votes

# Answer
## C#

240 characters. C# needs a "run inside of a function only" mode!

```
using System;class P{static void Main(string[] a){var n=DateTime.Now;if(a.Length>0)DateTime.TryParse(args[0],out n);while(true){n=n.AddDays(1);if((n.Day==13)&&(n.DayOfWeek==(DayOfWeek)5))break;}Console.WriteLine(n.ToString("yyyy-MM-dd"));}}

```

Un-golfed:

```
using System;

class P
{
    static void Main(string[] a)
    {
        var n = DateTime.Now;
        if (a.Length > 0) DateTime.TryParse(args[0], out n);
        while (true)
        {
            n = n.AddDays(1);
            if ((n.Day == 13) && (n.DayOfWeek == (DayOfWeek)5)) break;
        }
        Console.WriteLine(n.ToString("yyyy-MM-dd"));
    }
}

```

Test output

```
\Debug> f13.exe 2013-05-09
2013-09-13

\Debug> f13.exe 2007-06-29
2007-07-13

\Debug> f13.exe 2007-07-13
2008-06-13

\Debug> f13.exe
2011-05-13

```
> 2 votes

# Answer
# D: 227 Characters

```
import std.datetime,std.stdio;void main(string[]a){auto d=a.length<2?cast(Date)(Clock.currTime()):Date.fromISOExtendedString(a[1]);for(;d.dayOfWeek!=DayOfWeek.fri||d.day!=13;d+=dur!"days"(1)){}writeln(d.toISOExtendedString());}

```

More Legibly:

```
import std.datetime, std.stdio;

void main(string[] a)
{
    auto d = a.length < 2 ? cast(Date)(Clock.currTime()) : Date.fromISOExtendedString(a[1]);

    for(; d.dayOfWeek != DayOfWeek.fri || d.day != 13; d += dur!"days"(1)) {}

    writeln(d.toISOExtendedString());
}

```

The fun part is that while D's std.datetime makes this sort of code very easy to write, it's also incredibly verbose - due primarily to the precise (and therefore long) function names. So, the usability and maintainability of the code is very high, but it's code golfability is rather low.
> 2 votes

# Answer
## C#, 206 194 characters

**Update**

This is a slightly different take on the problem, so I left my other attempt here in full.

```
using System:class p{static void Main(string[]a){var n=a.Length>0?DateTime.Parse(a[0]):DateTime.Now;for(;(n=n.AddDays(5-(int)n.DayOfWeek).AddDays(7)).Day!=13;);Console.Write("{0:yyy-MM-d}",n);}}

```

Here, I'm finding the "current" week's Friday and then incrementing by 7 until I find one that's a 13. I also used Joey's for loop and output formatting to shave a few characters.

Ungolfed:

```
using System;
class p
{
    static void Main(string[] a)
    {
        var n = a.Length > 0 ? DateTime.Parse(a[0]) : DateTime.Now;

        for (; (n = n.AddDays(5 - (int)n.DayOfWeek).AddDays(7)).Day != 13; ) ;

        Console.Write("{0:yyy-MM-d}", n);
    }
}

```

Original:

This is similar to Andrew's above, but there were enough differences I decided to post a separate answer rather than comment and suggest edits.

```
using System;class p{static void Main(string[]a){var n=a.Length>0?DateTime.Parse(a[0]):DateTime.Now;do n=n.AddDays(1);while(!(n.Day==13&&n.DayOfWeek+""=="Friday"));Console.Write(n.ToString("yyyy-MM-dd"));}}

```

Ungolfed:

```
using System;
class p
{
    static void Main(string[] a)
    {
        var n = a.Length > 0 ? DateTime.Parse(a[0]) : DateTime.Now;
        do
        {
            n = n.AddDays(1);
        } while (!(n.Day == 13 && n.DayOfWeek + "" == "Friday"));

        Console.Write(n.ToString("yyyy-MM-dd"));
    }
}

```
> 2 votes

# Answer
## SQLite, 374 characters

(Line breaks added here for readability; not included in the count.)

Requirement to "Allow user to provide a start date either as a command line argument or through STDIN" omitted due to technical limitations.

```
CREATE TABLE R(N UNIQUE);
INSERT INTO R VALUES(0);
INSERT INTO R VALUES(1);
REPLACE INTO R SELECT A.N*2048|B.N*1024|C.N*512|D.N*256|E.N*128|F.N*64|
G.N*32|H.N*16|I.N*8|J.N*4|K.N*2|L.N FROM
R A,R B,R C,R D,R E,R F,R G,R H,R I,R J,R K,R L;
CREATE TABLE F AS SELECT DATE('2000-01-13','+'||N||'months') AS D
FROM R WHERE STRFTIME('%w',D)='5';
SELECT MIN(D) FROM F WHERE D>DATE('now');

```

The first 4 statements create a table (R) with a single column containing all the integers from 0 to 4095.

The 5th statement builds a table (F) of all Friday the 13ths between 2000-10-13 and 2340-12-13.

The 6th statement simply returns the first Friday the 13th after the current (UTC) date.
> 2 votes

# Answer
## R, 113 characters

```
f="%Y-%m-%d";o=format;a=c(as.Date(scan(,""),f),Sys.Date())[1];repeat{a=a+1;if(o(a,"%w%d")==513)break};cat(o(a,f))

```

Example runs:

```
> f="%Y-%m-%d";o=format;a=c(as.Date(scan(,""),f),Sys.Date())[1];repeat{a=a+1;if(o(a,"%w%d")==513)break};cat(o(a,f))
1: 2007-06-29
2:
Read 1 item
2007-07-13

> f="%Y-%m-%d";o=format;a=c(as.Date(scan(,""),f),Sys.Date())[1];repeat{a=a+1;if(o(a,"%w%d")==513)break};cat(o(a,f))
1:
Read 0 items
2013-12-13

> f="%Y-%m-%d";o=format;a=c(as.Date(scan(,""),f),Sys.Date())[1];repeat{a=a+1;if(o(a,"%w%d")==513)break};cat(o(a,f))
1: 2013-12-13
2:
Read 1 item
2014-06-13

```
> 2 votes

# Answer
# Perl 6, 69 bytes

```
$_=Date.new(@*ARGS[0]//Date.today);.++while .day*.day-of-week-65;.say

```

Try it online!

Thanks to @ASCII-only for -5
> 2 votes

# Answer
Javascript

```
F13=function(x){
    z=function(x){return (''+x).replace(/^(.)$/,'0$1')}
    D=x?new Date(x):new Date(),Z=864e5,X=D.getDay()%7,X+=+D+(X?Z*(5-X):0);
    do{
        X+=Z*7;
        D=new Date(X);
    }while(D.getDate()!=13)
    return D.getFullYear()+"-"+z(D.getMonth()+1)+"-"+z(D.getDate());
}

```

ps: yeah, I know, I broke the first rule (couldn't be just a function)

Tests on javascript shell

```
F13("2013-05-09") // 2013-09-13
2013-09-13
F13("2007-06-29") // 2007-07-13
2007-07-13
F13("2007-07-13") // 2008-06-13
2008-06-13
F13() //2011-05-13
2011-05-13

```
> 1 votes

# Answer
## T-SQL ~~359~~ ~~285~~ 253 Characters

```
CREATE PROCEDURE f13(@d DateTime=null)AS
SET @d=ISNULL(@d,GETDATE())
;WITH d AS
(SELECT @d+1 d
UNION ALL SELECT d+1 FROM d
WHERE DATEPART(dw,d)<>6 OR DAY(d)<>13)SELECT CAST(d AS DATE) FROM d
WHERE DATEPART(dw,d)=6 AND DAY(d)=13
OPTION (MAXRECURSION 999)

```

I just wanted to lay the smack down on the SQLite solution with my non-clever verbose date function using T-SQL procedure.

Update: My original fear that doing a day increment would take more space than a month increment was *very* incorrect.

Test results (SSMS):

```
f13 '2013-05-09';
GO

f13 '2007-06-29';
GO

f13 '2007-07-13';
GO

f13;
GO
--

d
----------
2013-09-13

d
----------
2007-07-13

d
----------
2008-06-13

d
----------
2011-05-13

```
> 1 votes

# Answer
## Another Javascript, 153

I post another javascript answer because I can't comment the first...

```
a=new Date(process.argv[2]||Date.now());for(b=1;b;b=a.getDate()!=13||!/^F/.test(a))a.setTime(a.getTime()+864e5);console.log(a.toISOString().substr(0,10))

```

Execute with nodeJS :

```
$ node fr13th
2013-12-13

$ node fr13th 2007-06-29
2007-07-13

$ node fr13th 2013-05-09
2013-09-13

```
> 1 votes

# Answer
# Python 3.3, 166 characters

```
import datetime as d
t=input()
t=d.date(*map(int,t.split()))if t!=""else d.date.today()
while 1:
 t+=d.timedelta(1)
 if t.day==13and t.weekday()==4:
  print(t);break

```

Input is in the format `2013 1 1`,

```
>>> ================================ RESTART ================================
>>>
2013 1 1
2013-09-13

```

or just press enter to use today's date (would be 2013/12/11 for this output)

```
>>> ================================ RESTART ================================
>>>

2013-12-13

```

# (there is actually a mix of my solution and @gnibbler 's that counts 144 chars)

```
import datetime as d
t=input()
t=d.date(*map(int,t.split()))if t!=""else d.date.today()
while t.day*t.weekday()-65:
 t+=d.timedelta(1)
print(t)

```

The very nice line `while t.day*t.weekday()-65:` is from @gnibbler's solution.
> 1 votes

# Answer
# Japt, 35 bytes

```
ÐUªKs3 ¯A
@e ¶5©D¶Uf}a@f1Uf Ä
s3 ¯A

```

-8 bytes thanks to @ASCIIOnly!

Try it!
> 1 votes

# Answer
# Swift 4, 310 bytes

```
import Foundation
let (u,f)=(Calendar.current,DateFormatter())
f.dateFormat="yyyy-MM-dd"
var t={(x:Date)->Int in let c=u.dateComponents([.weekday,.day],from:x);return c.weekday!*c.day!},d=readLine().map{f.date(from:$0)!} ?? Date()
while t(d) != 65{d=u.date(byAdding:.day,value:1,to:d)!}
print(f.string(from:d))

```

Try it online!

-4 thanks to TagTaco.

Alas...:

* needs Foundation for Date/Calendar.
* Swift doesn't allow `Int`s to be used as `Bool`.
* The shorthand enum syntax is helpful, though not that much.
* Space is required around `??`.
* `!=` also needs spacing, lest it's interpreted as an unwrapping.
> 1 votes

# Answer
**VB.net (96c\*)**

**Entry**

```
Function NextFridayThe13th(d As Date) As Date
  While d.DayOfWeek<>DayOfWeek.Friday
    d=d.AddDays(1)
  End While
  While d.Day<>13
    d=d.AddDays(7)
  End While
  Return d
End Function

```
* I think the CodeGolf count for vb.net shouldn't include the **function signature**, closing **end function** and the **return**. So it just makes it about the internal implementation.

So my scoring is broken down as so

```
While d.DayOfWeek<>DayOfWeek.Friday    '35c
d=d.AddDays(1)                         '13c  48c
End While                              ' 9c  57c
While d.Day<>13                        '15c  72c
d=d.AddDays(7)                         '14c  86c
End While                              ' 9c  95c
Return d                               ' 1c  96c

```
> 0 votes

# Answer
# Rebol, 136

```
d: any[do system/script/args now]until[d: d + 1 all[d/day = 13 d/weekday = 5]]print format/pad[4"-"-2"-"-2]reduce[d/year d/month d/day]

```

Ungolfed:

```
d: any [do system/script/args  now]

until [
    d: d + 1
    all [d/day = 13 d/weekday = 5]
]

print format/pad [4 "-" -2 "-" -2] reduce [d/year d/month d/day]

```

Example usage:

```
$ rebol friday13th.reb 2013-05-09
2013-09-13
$ rebol friday13th.reb
2014-06-13

```
> 0 votes

# Answer
# Java 8, ~~200~~ 197 bytes

```
interface M{static void main(String[]a){java.time.LocalDate z=null,r=a.length<1?z.now():z.parse(a[0]);for(;(r=r.plusDays(1)).getDayOfWeek().getValue()*r.getDayOfMonth()!=65;);System.out.print(r);}}

```

**Explanation:**

Try it here (remove the argument to use the current date).

```
interface M{                        // Class
  static void main(String[]a){      //  Mandatory main-method
    java.time.LocalDate z=null,     //   LocalDate to reduce bytes when using static calls
     r=a.length<1?                  //   If no argument is given:
        z.now()                     //    Start at the current date
       :                            //   Else:
        z.parse(a[0]);              //    Start at the date of the first argument
    for(;(r=r.plusDays(1))          //   Before every iteration, go to the next day
                                    //   Loop as long as:
         .getDayOfWeek().getValue()
                                    //    the 1-indexed day of the week (Friday = 5)
         *r.getDayOfMonth()         //    multiplied by the day of the month
        !=65;                       //    is not 65
                                    //    (5 and 13 are primes, so only 5*13 results in 65)
    );                              //   End of loop
    System.out.print(r);            //   Print the result Friday the 13th
  }                                 //  End of main-method
}                                   // End of class

```

NOTE: Java's default format when printing is already `yyyy-MM-dd`.
> 0 votes

# Answer
# 05AB1E, 141 bytes

```
gĀi'-¡ëžežfžg)}V[Y`2ô0Kθ4ÖUD2Qi\28X+ë<7%É31α}‹iY¬>0ëY1¾ǝDÅsD12‹i>1ë\1Dǝ¤>2}}ǝVY`UÐ3‹12*+>13*5÷s3‹Xα©т%D4÷®т÷©4÷®·()O7%6QYн13Q*#}YRεDgi0ì]'-ý

```

05AB1E doesn't have any builtins for Date objects or calculations. The only builtin regarding dates it has is today's year/month/day/hours/minutes/seconds/microseconds.

So because of that, almost all of the code you see are manual calculations to go to the next day, and calculating the day of the week.

Mostly derived from my 05AB1E answer in *The Work Day Countdown* challenge (which is why I edited that one about an hour ago when I came across a bug..)

Input is a string in the format `dd-MM-yyyy` (but output is in the format `yyyy-MM-dd`, since it's one of the rules of the challenge).

Try it online or verify all test cases.

**Explanation:**

```
gĀi        # If an input is given:
   '-¡    '#  Split it by "-"
  ë        # Else:
   že      #  Push today's day
     žf    #  Push today's month
       žg  #  Push today's year
         ) #  Wrap them into a single list
  }V       # After the if-else statement: pop and store it in variable `Y`
[          # Start an infinite loop
 Y`2ô0Kθ4ÖUD2Qi\28X+ë<7%É31α}‹iY¬>0ëY1¾ǝDÅsD12‹i>1ë\1Dǝ¤>2}}ǝV
           #  Go to the next day
           #  (see my linked The Work Day Countdown answer for an explanation)
 Y`UÐ3‹12*+>13*5÷s3‹Xα©т%D4÷®т÷©4÷®·()O7%
           #  Calculate the day of the week (0 = Saturday, 1 = Sunday, ..., 6 = Friday)
           #  (see my linked The Work Day Countdown answer for an explanation)
 6Q        #  Check if the day of the week is a Friday
 Yн        #  Push the days of the current date
   13Q     #  Check if it's the 13th
 *         #  And if both checks are truthy:
  #        #   Stop the infinite loop
}YR        # After the infinite loop: push the resulting date-list, and reverse it
ε          # Map each value to:
 Dgi       #  If it's only a single digit:
    0ì     #   Prepend a leading "0"
]          # Close both the if-statement and map
 '-ý      '# Join the result by "-"
           # (and output the result implicitly)

```
> 0 votes

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


title: 45 degree quine

text:
# Question
Title: 45 degree quine
A very simple golf this time, but should be fun to do.

# Challenge

Output your code, but rotated 45 (or -45) degrees. E.g:

`lorem ipsum dolor sit amet`

becomes

```
                         t
                        e
                       m
                      a

                    t
                   i
                  s

                r
               o
              l
             o
            d

          m
         u
        s
       p
      i

    m
   e
  r
 o
l

```

This logic follows for newlines, too:

`lorem ipsum dolor sit amet
consectetur adipiscing`

becomes

```
                         t
                        e
                       m
                      a
                       g
                    t n
                   i i
                  s c
                   s
                r i
               o p
              l i
             o d
            d a

          m r
         u u
        s t
       p e
      i t
       c
    m e
   e s
  r n
 o o
l c

```

Of course, the difficulty is that you have to output your own code in this format.

# Scoring

Find position *b* (the amount of bytes in your code). on the X-axis of the formula \\$y=\left(\frac{b}{8}-15\right)^2-n\\$ (given *n* is the number of newlines). The lower the score, the better. Newlines are encouraged, as they made rendering it harder. Also, -15 bonus points for doing -45 degrees, as opposed to 45. My examples were -45 degrees.

# Rules

* Standard loopholes apply.
* No reading your own source.
* There must be a space between one line of code and the next, if you choose to do so
* Every line must be at least 5 characters long.
* Newlines cannot be replaced with '\n'. Tabs should be replaced with two spaces.
* Every line must do something; when removed, the program must not work
* No trailing newlines (unless for an implicit return) or no-ops.
* Blank newlines should be rendered with a space in its place (you can assume its a line of contents ' ')

# Answer
# Gol\>\<\>, 120 bytes, score 0

```
sP#|oao|o `FLFl                                                                                "

```

Adding a ton of no-ops makes my score really low, so I'm just going to go with it even though it hurts my heart to see so many no-ops doing absolutely nothing :(

Try it online!

**golfed answer**, 16 bytes, Score : 152?!

```
sP#|oao|o `FLFl"

```

Wow, that is much smaller and more correct than my previous answer!!! (my other ones were backwards!)

Try it online!
> 2 votes

# Answer
# C# (Visual C# Interactive Compiler), Score 50.765625

```
var s="var s={0}{1}{0};for(int i=0;;)WriteLine(new String(' ',i)+string.Format(s,(char)34,s)[i++]);";for(int i=0;;)WriteLine(new String(' ',i)+string.Format(s,(char)34,s)[i++]);

```

Try it online!

Also prints to STDERR, if this is invalid I will change it.
> 1 votes

# Answer
# Japt `-S`, 25 bytes, Score: 116

```
25Çî iRiZgQi"25Çî iRiZgQi

```

Run it online
> 1 votes

# Answer
# Perl 6, Score -14

```
<+map
{say(
~($_,)
.indent(
$++))
},[Z]
"<$_>[]~~
.EVAL#1234567"
.words
.map:{
.fmt(
"%-14s"
).comb
}>[]~~
.EVAL#1234567

```

Try it online!

New solution since my old one (below) might (?) be invalidated by the new rules. The output looks like:

```
< { ~ . $ } " . . . . " ) } .
 + s ( i + , < E w m f % . > E
  m a $ n + [ $ V o a m - c [ V
   a y _ d ) Z _ A r p t 1 o ] A
    p ( , e ) ] > L d : ( 4 m ~ L
         ) n     [ # s {   s b ~ #
            t     ] 1       "     1
             (     ~ 2             2
                    ~ 3             3
                       4             4
                        5             5
                         6             6
                          7             7
                           "

```

I'm not sure if this is valid output since there's no example of a normal 45 degree quine in the question itself (this one is mirrored as well as rotated).

# Perl 6, Score: -8

```
<+map {say .indent($++),' 'x($++ <5)*16},"<$_>~~.EVAL".comb#123>>~~.EVAL

```

Try it online!

Pads the code by 8 lines of 5 space characters, and then adds trailing spaces to the first 5 lines.
> 1 votes

# Answer
# Charcoal, 40 bytes, score 100

```
≔´α´↗´´´≔´Ｆ´α´↗´⁺´´´´´ι´↗´αα↗´≔Ｆα↗⁺´´ι↗α

```

Try it online!

Based off the standard Charcoal quine
> 0 votes

---
Tags: ascii-art, code-challenge, quine
---


title: Heterograms, Palindromes, oh my!

text:
# Question
Title: Heterograms, Palindromes, oh my!
(First challenge, please let me know if there are any problems with it.)

A ***heterogram*** is a word where no letter of the alphabet occurs more than once, and a ***palindrome*** is a phrase that is the same backwards and forwards.

The challenge here is to write a piece of code that takes in a word (just letters) as input, and outputs whether or not it is a heterogram (truthy/falsy). The catch is that the program must be a palindrome -- reads the same backwards and forwards. Capitalization **doesn't** matter here, so for the heterogram to be valid it can't have both q and Q, for instance. No comments are allowed, and you cannot place strings that contain your code (or a significant part of your code) to try to make the palindrome part easy :P

This is code-golf, so shortest code wins. Good luck!

EDIT: Parens, brackets or other symbols that have left and right forms must be reversed approriately for the palindrome part. So (helloolleh) is a palindrome, but (helloolleh( is not. Apparently this is called a convenient palindrome.

EDIT 2: You won't get any empty input, input with multiple words or input with characters other than letters. So don't worry about that :)

# Answer
# Pyth - 11 bytes

(Trailing and leading spaces necessary and counted).

```
 z.{ z }.z

```

Test Suite.

```
<space>        Suppress print
 z             Input (for palindromness)
.{             Unique - actually does testing
  z            Input
<space>        Suppress print
  }            In operator
   .z          Cached input list
   <space>     At end of program makes empty tuple

```
> 9 votes

# Answer
# Pyth, 17 bytes

```
 Z.{rzZ.q.Zzr}.Z

```

Try it online here.

The leading space is necessary. I have counted it and the trailing space in the byte count.

Here's the breakdown:

```
     z            z is initialized to the input
    r Z           Z is initialized to 0, and r(string)0 converts the string to lowercase
  .{              .{ is pyth's builtin uniqueness test
       .q         .q terminates the program
         .Zzr}    This is just the program mirrored
              .Z  . requires a number to immediately follow it
                  If left blank the parser would throw an error
 Z                This is just mirrored from the end
                  The leading space suppresses the automatic printing of this 0
                  The trailing space mirrors the leading space

```
> 18 votes

# Answer
# Python 3, 125

The main problem is to make the reverse of the code parsable. Then we can let it error out from undefined identifiers.

```
w=[str.lower][0]((input)())
(print)((max)((map)(w.count,w))<2)
(2>((w,tnuoc.w)(pam))(xam))(tnirp)
(()(tupni))[0][rewol.rts]=w

```
> 17 votes

# Answer
# Perl, 43 bytes

```
print+m:^(?!.*(.).*\1|1/*.(.)*.!?)^:m+tnirp

```

Usage example:

```
echo "abcde" | perl -n entry.pl

```
> 12 votes

# Answer
## \>\<\>, ~~137~~ 131 Bytes

When I saw this challenge, I thought \>\<\> might finally be a good choice of language since using it you can mostly ignore palindromes; it is simple to make sure the pointer only stays where it should. While this is true, \>\<\> unfortunately makes golfing conditionals excruciating (or just golfing in general). I hope to use some weird tricks I thought of to compensate for this, but here's a "quick" (not actually, both program-wise and creation-wise) answer. You can try it online here.

```
i:0(?v>:"Z")?vl1-:1(?v&:{:@=?v$&e0.>
  ;n1<^  -*48<   .00~<  ;n-10<01-n;  >~00.   >84*-  ^>1n;
<.0e&$v?=@:}:&v?)1:-1lv?("Z":<v?)0:i

```

Returns 1 for true and -1 for false (I could change it to 0 but the length would stay the same, unfortunately)

As always, let me know if this doesn't work and if you have any ideas on how to golf it down. I tested it against a few test cases, but there always could be an exception.

Here's another version, one that I think is a bit more clever, but alas is ten bytes more. Truthy/falsey values this time are 1 and an error (`something smells fishy...`):

```
>i:0(?v>:"Z")?vl: 2(?v&{:@$:@=01-*2.
 < ;n1<^  -*48<f6+0.0<
 &1-:1)e*1.1*e(1:-1&
>0.0+6f>84*-  ^>1n; >
.2*-10=@:$@:}&v?)2 :lv?("Z":<v?)0:i<

```

---

## Explanation:

Here's the code without the part added to make it a palindrome. This one doesn't use the "more clever" tricks I attempted to use for the alternate version, so it's a bit easier to explain (if anyone is interested in an explanation for the "tricks," I'd be happy to give one, though).

```
i:0(?v>:"Z")?vl1-:1(?v&:{:@=?v$&e0.>
  ;n1<^  -*48<   .00~<  ;n-10<

```

**Line 1:**

```
i:0(?v>:"Z")?vl1-:1(?v&:{:@=?v$&e0.>
i:0(?v                                 #Pushes input and directs down if negative
      >:"Z")?v                         #Directs down if input is greater than "Z"
                                       #(reduces lowercase input to uppercase)
              l                        #Pushes length

                                       #Main loop begins
               1-:1(?v                 #Decrements top, and then directs down if less than 1
                      &                #Pushes top of stack onto register (length minus 1)
                       :{              #Duplicates top, shifts stack to the left
                         :@            #Duplicates top, shifts top three values of the stack to the right

                           =?v         #If top two values are equal, directs down
                              $        #Swaps top two values of the stack
                               &       #Pushes register onto stack
                                e0.    #Jumps back to the "1" after "?vl"
                                       #Main loop ends

                                   >   #Makes sure when the pointer jumps back to i it goes the right way

```

Here's how the convoluted swapping (`:{:@=?v$`) works -- I'll use a test case of this stack: `[5,1,8,1]` where the last character is the top.

`:{` The top of the stack is duplicated: `[5,1,8,1,1]`, and the stack shifted to the left: `[1,8,1,1,5]`

`:@` The top is duplicated: `[1,8,1,1,5,5]`, then the top three values are shifted to the right: `[1,8,1,5,1,5]`

`=?v` Unnecessary for this part of explanation

`$` The top value is swapped once more yielding `[1,8,1,5]`, which, if you'll note, is the original stack shifted over once (as if `{` had been the only command).

---

So what this does in English <sup>("Thank God, he's actually explaining things")</sup> is check the entire stack against the top value and move to a point in the second line if any value equals the top. This checking is done proportionate to how many values there are in the stack (`l - 1`, where `l` is the length of the stack) so that all values are checked against each other.

**Line 2:**

```
  ;n1<^  -*48<   .00~<  ;n-10<
   n1<                          #If input is less than 0 (i.e. there is none), print 1
  ;                             #and terminate

             <                  #If redirected because input is greater than "Z"
         -*48                   #Push 32, subtract (reducing lowercase to uppercase, numerically)
      ^                         #And move back to the portion that tests if input
                                #is uppercase (which it will pass now)

                     <          #If counter is less than 1 (for main loop)
                 .00~           #Pop the counter and jump to the beginning (i)

                             <  #If any two values in the stack are equal
                          -10   #Push -1 (subtract 1 from 0)
                        ;n      #Print and terminate

```
> 6 votes

# Answer
## PHP, 126 Bytes

You need to run this with the `short_tags` ini directive turned **off** in 5.4 or above.

First golf ever. Two copies, the first prints a whole bunch of garbage with the falsy/truthy result:

```
<?=var_dump(max(array_count_values(str_split(end($argv))))<2)?><?(2>((((vgra$)dne)tilps_rts)seulav_tnuoc_yarra)xam)pmud_rav=?>

```

This version will not print any jargon (162 bytes):

```
<?=var_dump(max(array_count_values(str_split(end($argv))))<2);__halt_compiler()?><?()relipmoc_tlah__;(2>((((vgra$)dne)tilps_rts)seulav_tnuoc_yarra)xam)pmud_rav=?>

```

Run from the command line with

```
php -f golf.php heterogram

```

Probably can be golfed a bit further
> 5 votes

# Answer
# 05AB1E, 9 bytes

```
lDÙQqQÙDl

```

Try it online.

\*insert something about going all the way back to my very first challenge\*

Non-competing since 05AB1E was made after this challenge.

## Explanation

```
lDÙQqQÙDl
l           Take input and lowercase it.
 DÙ         Duplicate and uniquify.
   Q        Compare the two strings.
    q       Immediately exit.
     QÙDl   The rest of the program is ignored.

```
> 2 votes

# Answer
# Brachylog, 3 bytes, language postdates challenge

```
DdD

```

Try it online!

This is one of the very few programs that works in both Brachylog 1 and Brachylog 2. The TIO link is to Brachylog 1 for old times' sake. Also unsually for Brachylog, this is a full program, not a function. (Full programs in Brachylog implicitly output booleans, which is just what we want for this question.)

The general principle here is that placing a predicate between a pair of identical uppercase letters is an assertion that the current value is invariant under that predicate. So you often see things like `AoA` for "is sorted" ("invariant under sorting"); `A↔A` would (in Brachylog 2) mean "is a palindrome" ("invariant under reversal"), and so on. This program is "invariant under removing duplicates", i.e. "doesn't contain duplicates". It's really convenient that this method of specifying invariance happens to be a palindrome.
> 2 votes

# Answer
# Brachylog, 3 bytes

```
≠ụ≠

```

Try it online!

The predicate succeeds if the input is a heterogram and fails if it is not.

```
≠      The characters of the input are all distinct,
 ụ     and when converted to upper case,
  ≠    are still all distinct.

```
> 1 votes

# Answer
# MATL, 7 bytes

```
tuX=Xut

```

Try it online!

Returns list \[1, 1\] if the input is a heterogram and \[0, 0\] if not.

Explanation:

```
t       % duplicate the input
u       % remove duplicates from the original
X=      % check the two lists are equal
Xu      % unique rows (does nothing as we now have a boolean)
t       % duplicate the result
        % (implicit) convert to string and display

```
> 0 votes

---
Tags: code-golf, string, restricted-source, decision-problem, palindrome
---


title: Superior Passtimes

text:
# Question
Title: Superior Passtimes
Sometimes, when I'm really bored I like to take the sum of an array of non-negative integers. I only take the sum of arrays of lengths that are powers of two. Unfortunately I often make mistakes. Fortunately I keep track of my work as I go along in the following way:

I add pairs of adjacent numbers until there's only one left. For example:

```
 6 + 18 + 9 + 6 + 6 + 3 + 8 + 10
=  24   +   15  +   9   +   18
=       39      +       27
=               66

```

You're job is to determine if I've made a mistake somewhere. You may either get input passed to your function or read from standard in. Output can be printed or returned.

Input: An array/list/etc. of non-negative integers, and possibly also the length of that array if your language requires it. That array will be all the numbers read left to right then top to bottom. For example the array above would become:
`[[6, 18, 9, 6, 6, 3, 8, 10], [24, 15, 9, 18], [39, 27], [66]]`
or
`[6, 18, 9, 6, 6, 3, 8, 10, 24, 15, 9, 18, 39, 27, 66]` if you prefer.

Output: a single boolean representing whether or not a mistake was made. The boolean can be represented using *any* mapping provided that all inputs where a mistake is made return/print an identical result and all input which contain no mistakes return/print an identical result. This should go without saying, but those two outputs cannot be the same.

Some Examples of Correct Summations:

```
6

5+6
=11

  3 + 2 + 4 + 5
=   5   +   9
=       14

[0, 1, 2, 3, 1, 5, 6]

[[1, 2, 4, 8], [3, 12], [15]]

```

Some Examples of Incorrect Summation:

```
5+4
=8

4 + 4 + 4 + 4
= 9   +   7
=     16

[[1, 2, 3, 4], [7, 3], [10]]

[3, 4, 5, 6, 7, 8, 9]

```

Keep in mind that I can make mistakes and still get the right answer. If I do make a mistake it'll never result in an extra number or a missing number in the final array, only a wrong number.

Standard loopholes are forbidden. Shortest answer in each language is a winner. The older answer will win in the case of a tie. I retain the right to decide what the "same language" is, but I'll say upfront a point can't be earned in both Python 2, and Python 3.

# Answer
# Jelly, 6 bytes

```
Ṗ+2/€ẇ

```

Try it online!

### How it works

```
Ṗ+2/€ẇ  Main link. Argument: A (2D array)

Ṗ       Pop; yield A without its last element. Let's call the result B.
  2/    Pairwise reduce...
    €     each array in B...
 +          by addition.
     ẇ  Window exists; test if the result appears in A as a contiguous subarray.

```
> 10 votes

# Answer
# Python 2, 51 bytes

```
lambda l:map(sum,zip(*[iter(l)]*2))==l[len(l)/2+1:]

```

Try it online! Thanks to Rod for the test cases.

Takes the whole list flat as input. Groups elements into adjacent pairs using the zip/iter trick, takes the sum of the pairs, and checks if the result equals the second half of the list.

A recursive method came close at 55 bytes:

```
f=lambda l:len(l)<2or l[0]+l[1]==l[len(l)/2+1]*f(l[2:])

```

This used that input integers are positive, which has since changed in the spec.
> 9 votes

# Answer
# Röda, 40 bytes

```
{[0]if{|x|[[x()|[_+_]]=y]if tryPeek y}_}

```

Try it online!

It's an anonymous function that returns `0` if there are no mistakes and nothing if there are mistakes.

Explanation:

```
{[0]if{|x|[[x()|[_+_]]=y]if tryPeek y}_}
{                                      } /* Anonymous function */
      {|x|                           }_  /* Loop over lists in the stream */
                         if tryPeek y    /* If there are lists left after this */
            x()                          /* Push values in list x to the stream */
               |[_+_]                    /* Sum every pair of numbers in x */
           [         ]                   /* Create a list of sums */
                      =y                 /* If the list equals to the next list */
          [             ]                /* Push the result */
    if                                   /* If all results are TRUE */
 [0]                                     /* Return 0 */
                                         /* Otherwise return nothing */

```

Here's a version that is shorter (35 bytes) but against the rules (I think):

```
{{|x|[[x()|[_+_]]=y]if tryPeek y}_}

```

Try it online!

It's an anonymous function that reads values from the stream and pushes `TRUE` or `FALSE` for each correct line.

I'm not sure if this (multiple return values) is accepted in the rules. Here's my defence: in Röda, conditions of `if` and `while` blocks are not boolean values, but streams. A "truthy" stream is either empty or contains only `TRUE`s, and a "falsy" stream contains one or more `FALSE`s. In this way, this function returns a "boolean" value. And can be used as a condition of an `if` statement without any reduce-operations, etc.
> 7 votes

# Answer
# Python 2, ~~69~~ 65 bytes

```
lambda x:reduce(lambda a,b:(b==map(sum,zip(a[::2],a[1::2])))*b,x)

```

Try it online!
Returns :
Empty List as `Falsy`
Total sum as `Truthy`
> 5 votes

# Answer
# Mathematica, 36 bytes

```
Most[Tr/@#~Partition~2&/@#]==Rest@#&

```

Pure function taking a nested list as input and returning `True` or `False`. The function `Tr/@#~Partition~2&` takes the pairwise sums of a list, which is then applied (`/@#`) to each sublist of the input list. The first, second, ... sublists in the resulting list are supposed to equal the second, third, ... sublists in the original input; `Most[...]==Rest@#` tests for this property.
> 5 votes

# Answer
# Python 2, 80 bytes

```
lambda l:all(l[i+1]==map(sum,zip(l[i][::2],l[i][1::2]))for i in range(len(l)-1))

```

Try it online!

Not quite as good as the other python answer, but I felt like posting it anyway. This just goes to show why I'm not as good at golfing in *regular* languages.
> 4 votes

# Answer
## JavaScript (ES6), 54 bytes

```
a=>!a.slice(-a.length/2).some((n,i)=>a[i+=i]+a[i+1]-n)

```

Takes a flattened array.
> 3 votes

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

```
¬svyQy2ôO}\P

```

Try it online!

**Explanation**

```
¬             # get the first element from input without popping
 sv      }    # for each element y in input
   yQ         # compare y to the top of the stack
              # leaves 1 on the stack if equal and otherwise 0
     y2ô      # split y in pieces of 2
        O     # sum each pair in the list
          \   # discard the top of the stack (the left over final element of the list)
           P  # product of stack (all the 1's and/or 0's from the comparisons)

```
> 3 votes

# Answer
# Haskell, ~~82~~ ~~79~~ 65 bytes

-14 bytes thanks to nimi!

```
p(x:y:z)=x+y:p z
f x=and.zipWith(==)(drop(length x`div`2+1)x)$p x

```

Works by comparing the sum each pair of elements to the corresponding element on the next line down. Some bytes can probably be golfed from `f`, but I can't figure out where.
> 3 votes

# Answer
## Python 3, 69 68 bytes

```
lambda v:any(x+v[i-1]-v[(len(v)+i)//2]for i,x in enumerate(v)if i%2)

```

I know there are already two other python answers... but this one's in python 3, so it's exotic.

This works on a flattened input.

**Output**:

`False` if there is no mistake,

`True` if there is a mistake.
> 2 votes

# Answer
# Ruby, 50 bytes

```
->x{a=b=0;b&&=x[a/2]==x[a]+x[a-1]while x[-a-=2];b}

```

Reversing the array, any element of the first half (position n) must be the sum of the elements in position n\*2 and n\*2+1.
> 2 votes

# Answer
# Brachylog, ~~16~~ 13 bytes

```
s₂ᵘ{{ġ₂+ᵐ}ᵈ}ᵐ

```

Try it online!

This is just dreadfully long! There has to be some way to not nest inline predicates here.

The predicate succeeds (printing `true.` as a program) if no mistakes were made and fails (printing `false.` as a program) otherwise.

```
s₂ᵘ              Every length 2 substring of the input
   {       }ᵐ    for every element satisfies the following:
    {ġ₂          the pairs of elements of the input
       +ᵐ        when each pair is summed is the output
         }ᵈ      where the input is the first item and the output is the second.

```
> 2 votes

# Answer
# Python 2, 64 bytes

```
lambda a:[map(int.__add__,x[::2],x[1::2])for x in a[:-1]]==a[1:]

```

**Try it online!**

An unnamed function that takes a list of lists (one per line of working as it were), and returns True if no mistakes were made and False otherwise.

It works by using the input without the last entry, `a[:-1]`, to form what the input without the first entry should be and checking that is what was input, `==a[1:]`.

This formation is achieved by mapping the integer type's addition function, `int.__add__`, over the pairs of numbers as yielded by two "slices", one slice being every other item starting at the 0th index, `x[::2]`, the other slice being every other item starting at the 1st index, `x[1::2]`.
> 1 votes

# Answer
# Pip, ~~20~~ 19 bytes

```
$*{{b=$+*Ya<>2}MPa}

```

This is an anonymous function that takes one argument, a list of lists (e.g. `[[1 2 3 4] [3 7] [10]]`). Verify all test cases: Try it online!

### Explanation

In a Pip function, the first two arguments are assigned to `a` and `b`.

```
  {               }  Anonymous function:
   {          }MPa    To each pair of sublists from a, map this helper function:
          a<>2         Group the 1st member of the pair into 2-item sublists
         Y             Yank that value (no-op used to override precedence order)
      $+*              Map (*) the fold ($) on addition (+) operator
    b=                 If the 2nd member of the pair is = to the result, 1; else 0
$*                   Modify the outside function by folding its return value on *
                     (makes a list containing all 1's into 1 and any 0's into 0)

```

For example:

```
a
[[1 2 3 4] [7 3] [10]]

{...}MP
a:[1 2 3 4] b:[7 3]
a:[7 3]     b:[10]

a<>2
[[1 2] [3 4]]
[[7 3]]

$+*
[3 7]
[10]

b=
0
1

Final result of {...}MPa
[0 1]

$*
0

```
> 1 votes

# Answer
# PHP, ~~96~~ 95 bytes:

using builtins:

```
function f($a){return!$a[1]||array_pop($a)==array_map(array_sum,array_chunk(end($a),2))&f($a);}
// or
function f($a){return!$a[1]||array_map(array_sum,array_chunk(array_shift($a),2))==$a[0]&f($a);}

```

recursive functions return `true` or `false`.

**breakdown** for first function:

```
function f($a){
    return!$a[1]||      // true if array has no two rows ... or
    array_pop($a)==     // remove last row, true if equal to
    array_map(array_sum,    // 3. sum up every chunk
        array_chunk(        // 2. split to chunks of 2
            end($a)         // 1. new last row
        ,2))
    &f($a);             // and recursion returns true
}

```

**older solutions** (96 bytes each) using loops:

```
function f($a){foreach($a[0]as$k=>$v)$b[$k/2]+=$v;return$b==$a[1]&&!$a[2]|f(array_slice($a,1));}
//or
function f($a,$y=0){foreach($a[$y]as$k=>$v)$b[$k/2]+=$v;return$b==$a[++$y]&&!$a[$y+1]|f($a,$y);}

```

**breakdown** for last function:

```
function f($a,$y=0){
    foreach($a[$y]as$k=>$v)$b[$k/2]+=$v;    // build $b with correct sums from current row
    return$b==$a[++$y]                      // true if $b equals next row
    &&!$a[$y+1]                             // and (finished
        |f($a,$y);                          //      or recursion returns true)
}

```

**iterative snippets, 81 bytes**

```
for(;$a[1];)if(array_pop($a)!=array_map(array_sum,array_chunk(end($a),2)))die(1);
for(;$a[1];)if(array_map(array_sum,array_chunk(array_shift($a),2))!=$a[0])die(1);
for(;$a[++$y];$b=[]){foreach($a[$y-1]as$k=>$v)$b[$k/2]+=$v;if($a[$y]!=$b)die(1);}

```

assume array predefined in `$a`; exits with error if it is incorrect.
> 1 votes

# Answer
# R, ~~92~~ 77 bytes

Anonymous function which takes a flat sequence of numbers as input. Returns `TRUE` or `FALSE` as appropriate. Uses the same approach conceptually as xnor's python answer.

```
function(x,l=sum(1|x)/2)all(rowSums(cbind(x[1:l*2-1],x[1:l*2]))==tail(x,l-1))

```

Previous solution, using the `rollapply` function from the `zoo` package, and taking input as a list, e.g. `list(c(6, 18, 9, 6, 6, 3, 8, 10), c(24, 15, 9, 18), c(39, 27), c(66))`:

```
function(l,T=1){for(i in 2:length(l))T=T&all(zoo::rollapply(l[[i-1]],2,sum,by=2)==l[[i]]);T}

```
> 1 votes

# Answer
# C, 54 bytes:

```
f(int*s,int*e){return e-s>1?*s+s[1]-*e||f(s+2,e+1):0;}

```

Ungolfed:

```
int f(int*s,int*e) {
    if(e-s>1) {
        return *s+s[1] != *e || f(s+2,e+1);
    } else {
        return 0;
    }
}

```

Test with

```
#include <assert.h>
int main() {
    int input1[15] = {6, 18, 9, 6, 6, 3, 8, 10, 24, 15, 9, 18, 39, 27, 66};
    assert(!f(input1, input1+8));

    int input2[7] = {3, 4, 5, 6, 7, 8, 9};
    assert(f(input2, input2+4));
}

```

As you see, `f()` returns true for invalid inputs and false (= 0) for valid ones.

As always, recursion is less bytes than iteration, so `f()` is recursive, even though it takes two iterators as arguments. It works by repeatedly comparing the sum of two integers at `s` to one integer at `e`, ignoring the level boundaries, and carrying on until the two iterators meet. I have also used some boolean zen together with the fact that any non-zero integer value is considered true in C to further shorten the code.
> 1 votes

# Answer
## JavaScript (ES6), ~~46~~ 44 bytes

Takes input as a flattened array. Returns `NaN` for valid or `0` for invalid.

```
f=([a,b,...c])=>a+b==c[c.length>>1]?f(c):b-b

```

### Test

```
f=([a,b,...c])=>a+b==c[c.length>>1]?f(c):b-b

console.log(f([6, 18, 9, 6, 6, 3, 8, 10, 24, 15, 9, 18, 39, 27, 66])) // NaN
console.log(f([0, 1, 2, 3, 1, 5, 6]))                                 // NaN
console.log(f([1, 2, 4, 8, 3, 12, 15]))                               // NaN
console.log(f([1, 2, 3, 4, 7, 3, 10]))                                // 0
console.log(f([3, 4, 5, 6, 7, 8, 9]))                                 // 0
```
> 1 votes

# Answer
# PHP, 102 Bytes

input als url parameter in this format `?0=[1,2,3]&1=[3,3]&2=[6]` use this input `[[int,int],[int]]`

```
<?$r=[$_GET[0]];for(;count(end($r))>1;)$r[]=array_map(array_sum,array_chunk(end($r),2));echo$r==$_GET;

```

## Breakdown

```
$r=[$_GET[0]]; # Set the first item of the input in the result array
for(;count(end($r))>1;) # till the last item in the result array has only one int
$r[]=array_map(array_sum,array_chunk(end($r),2));# add the next item to the result array
echo$r==$_GET; # compare the input array with the result array

```
> 0 votes

# Answer
# Japt, 10 bytes

Takes input as a 2-D array.

```
äÏeXò mxÃe

```

Try it

```
äÏeXò mxÃe     :Implicit input of 2-D array
ä              :Reduce each consecutive pair of sub-arrays
 Ï             :By passing them through the following function as X & Y, respectively
  e            :  Test Y for equality with
   Xò          :    Split X on every 2nd element
      m        :    Map
       x       :      Reduce by addition
        Ã      :End function
         e     :All true?

```
> 0 votes

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


# Question
Title: Write a function to decrypt Feynman Challenge Cipher #1
The Feynman Challenge Cipher #1 is as follows:

```
MEOTAIHSIBRTEWDGLGKNLANEAINOEEPEYST
NPEUOOEHRONLTIROSDHEOTNPHGAAETOHSZO
TTENTKEPADLYPHEODOWCFORRRNLCUEEEEOP
GMRLHNNDFTOENEALKEHHEATTHNMESCNSHIR
AETDAHLHEMTETRFSWEDOEOENEGFHETAEDGH
RLNNGOAAEOCMTURRSLTDIDOREHNHEHNAYVT
IERHEENECTRNVIOUOEHOTRNWSAYIFSNSHOE
MRTRREUAUUHOHOOHCDCHTEEISEVRLSKLIHI
IAPCHRHSIHPSNWTOIISISHHNWEMTIEYAFEL
NRENLEERYIPHBEROTEVPHNTYATIERTIHEEA
WTWVHTASETHHSDNGEIEAYNHHHNNHTW

```

The solution is described as:

> It is a simple transposition cipher: split the text into 5-column pieces, then read from lower right upward. What results are the opening lines of Chaucer's Canterbury Tales in Middle English.

Which is:

```
WHANTHATAPRILLEWITHHISSHOURESSOOTET
HEDROGHTEOFMARCHHATHPERCEDTOTHEROOT
EANDBATHEDEVERYVEYNEINSWICHLICOUROF
WHICHVERTUENGENDREDISTHEFLOURWHANZE
PHIRUSEEKWITHHISSWEETEBREFTHINSPIRE
DHATHINEVERYHOLTANDHEETHTHETENDRECR
OPPESANDTHEYONGESONNEHATHINTHERAMHI
SHALVECOURSYRONNEANDSMALEFOWELESMAK
ENMELODYETHATSLEPENALTHENYGHTWITHOP
ENYESOPRIKETHHEMNATUREINHIRCORAGEST
HANNELONGENFOLKTOGOONONPILGRIM

```

## The Challenge:

Write a function to decrypt the cipher.

The output does not need line breaks or spaces.

Input is has no line breaks or spaces.

Shortest solution wins.

(Bonus points if you can solve the other 2 ciphers :P)

---

### My attempt (PHP ~~77~~ 70):

```
$b=strrev($a);for($i=0;$i<5;$i++)for($j=0;$j<381;$j++)$r.=$b[$i+$j*5];

```

http://codepad.org/PFj9tGb1

# Answer
> 7 votes
### Golfscript, 10 chars

```
n--1%5/zip

```

Takes input from stdin. It may be separated by newlines, as in the question presentation, or not, as many answers assume. (Stripping the newlines is necessary anyway given that it's likely to arrive with one on the end, which messes up the blocks of 5). If we assume that the input arrives with precisely one newline, being the last character, we can shave one character to

```
)!(%5/zip

```

# Answer
> 3 votes
### Mathematica, 51

Mathematica is quite verbose here, but it is also easy to guess what it's doing.

```
Thread[Characters@#~Partition~5]~Reverse~{1,2}<>""&

```

# Answer
> 3 votes
## , 13 characters

```
|.@(/:5|i.@#)

```

# Answer
> 2 votes
# Haskell, 52

```
f s=[s!!(x-i)|x<-[length s],j<-[1..5],i<-[j,j+5..x]]

```

# Answer
> 2 votes
# Japt -P, ~~4~~ 3 bytes

```
Ôó5

```

Try it online!

I feel like that was too easy? On a positive note, this can't possibly be golfed too much assuming I am getting the correct result :)

**EDIT** -1 byte thanks to @Shaggy!

```
Ôó5    # full program
Ô      # reverse input string
 ó5    # create a 5-element array by repeatedly
       # picking every 5th character.
       # -P flag concatenates array on output!

```

# Answer
> 1 votes
## Python - 56 chars

```
s=raw_input()
print"".join(s[-1-x::-5]for x in range(5))

```

# Answer
> 1 votes
## Scala, 62 characters

```
print((for(x<-0 to 4;y<-379-x to 0 by -5)yield s(y)).mkString)

```

Making the assumption that the string is already in a variable `s` as hammar and stevether do.
Taking the input from stdin is a bit uglier (92 chars):

```
var s=io.Source.stdin.mkString
print((for(x<-0 to 4;y<-379-x to 0 by -5)yield s(y)).mkString)

```

and it only works if there are no newlines in the input.

# Answer
> 1 votes
## Perl, 58 characters

```
perl -lne'$c[$c++%5].=$_ for split//}END{$"=$,,print$_=reverse"@c"'

```

# Answer
> 1 votes
### Scala 63 chars:

```
(1 to 5).map(n=>s.reverse.drop(n)).map(_.sliding(1,5).mkString)

```

Assuming the input is in s.

# Answer
> 1 votes
# K, 34

```
{a::(5*!76)_x;1'{a[;x]@|!#a}@'|!5}

```

# Answer
> 1 votes
# ECMAScript 6 - 48 Characters

```
for(c='',i=5;i--;)c+=(x=>s[x]?f(x+5)+s[x]:'')(i)

```

Assumes that the variable `s` contains the input string (without any white space characters) and creates the variable `c` containing the output.

# Answer
> 0 votes
# Python 3.6, 48 bytes

Recursion + f-Strings

```
f=lambda a:a and f'{a[::-5]+f(a[:-1])}'[:len(a)]

```

Try it online!

---
Tags: code-golf
---


title: 2-Dimensional Bubble Sort

text:
# Question
Title: 2-Dimensional Bubble Sort
Sorting makes no sense for a 2-dimensional array... or does it?

Your task is to take an input grid and apply a bubble-sort-like algorithm to it until all values in the grid are non-decreasing from left to right and top to bottom along every row and column.

The algorithm works as follows:

* Each pass goes row by row, top to bottom, comparing/swapping each cell with its right and below neighbors.
    + if the cell is greater than only one of its right and below neighbors, swap with the one that it is greater than
    + if the cell is greater than both its right and below neighbors, swap with the smaller neighbor
    + if the cell is greater than both its right and below neighbors, which are the same value, then swap with the below neighbor.
    + if the cell is not greater than either of its right and below neighbors, do nothing
* Continue this until no swaps are made throughout the entire pass. This will be when every row and column are in order, left to right and top to bottom.

## Example

```
4 2 1
3 3 5
7 2 1

```

The first row of the pass will swap the 4 and the 2, then the 4 with the 1.

```
2 1 4
3 3 5
7 2 1

```

When we get the the middle 3, it will be swapped with the 2 below

```
2 1 4
3 2 5
7 3 1

```

Then the 5 gets swapped with the 1 below

```
2 1 4
3 2 1
7 3 5

```

The last row of the first pass moves the 7 all the way to the right

```
2 1 4
3 2 1
3 5 7

```

Then we go back to the top row again

```
1 2 1
3 2 4
3 5 7

```

And continue row by row...

```
1 2 1
2 3 4
3 5 7

```

... until the grid is "sorted"

```
1 1 2
2 3 4
3 5 7

```

## Another Example

```
3 1 1
1 1 1
1 8 9

```

becomes

```
1 1 1
1 1 1
3 8 9

```

rather than

```
1 1 1
1 1 3
1 8 9

```

because the downward swap takes priority when both the right and below neighbors of a cell are equal.

A step-by-step reference implementation can be found here.

## Test cases

```
5 3 2 6 7 3 1 0
3 2 1 9 9 8 3 0
3 2 2 8 9 8 7 6

```

becomes

```
0 0 1 1 2 2 3 6
2 2 3 3 6 7 8 8
3 3 5 7 8 9 9 9

```

---

```
2 1 2 7 8 2 1 0
2 2 2 2 3 2 1 0
1 2 3 4 5 4 3 2
9 8 7 6 5 4 3 6
6 5 4 3 2 2 1 0

```

becomes

```
0 0 0 1 1 1 2 2
1 1 2 2 2 2 2 2
2 2 2 2 3 3 3 3
3 4 4 4 4 5 6 6
5 5 6 7 7 8 8 9

```

## Rules

* You can take the input grid in any convenient format
* You may assume the grid values are all non-negative integers in the unsigned 16-bit range (0-65535).
* You may assume the grid is a perfect rectangle and not a jagged array. The grid will be at least 2x2.
* If you use another algorithm of sorting, you must supply a proof that it will *always* produce the same resulting order as this particular brand of 2D bubble sorting, no matter what the input is. I expect this to be a non-trivial proof, so you're probably better off using the described algorithm.

Happy Golfing!

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

```
a=>[...a+''].map(t=>a.map((l,y)=>l.map((v,x)=>(L=a[y+1]||[],d=L[X=x],r=l[x+1],v>r?r>=d||(L=l,X++):v>d||(L=l),l[x]=L[X],L[X]=v))))

```

Try it online!
> 3 votes

# Answer
# APL (Dyalog Unicode), 75 bytesSBCS

Thanks to @Adám for saving 11 bytes.

```
{m⊣{d r←⍵∘(s⌊+)¨↓∘.=⍨⍳2⋄∨/c>a c b←m[r⍵d]:m⊢←⌽@⍵(d r⊃⍨1+b>a)⊢m⋄⍬}¨⍳s←⍴m←⍵}⍣≡

```

Try it online!
> 2 votes

# Answer
# Wolfram Language (Mathematica), 183 bytes

```
(R=#;{a,b}=Dimensions@R;e=1;g:=If[Subtract@@#>0,e++;Reverse@#,#]&;While[e>0,e=0;Do[If[j<b,c=R[[i,j;;j+1]];R[[i,j;;j+1]]=g@c]If[i<a,c=R[[i;;i+1,j]];R[[i;;i+1,j]]=g@c],{i,a},{j,b}]];R)&

```

Try it online!

I'm not a Mathematica expert, I'm sure it can be done shorter. Particularly I think that the double if statement could be shortened using `Transpose` but I don't know how.
> 1 votes

# Answer
# , ~~169~~ ~~165~~ ~~144~~ 132 bytes

```
function(m,n=t(m)){while(any(F-(F=n)))for(i in 1:sum(1|n)){j=(j=i+c(0,r<-nrow(n),!!i%%r))[order(n[j])[1]];n[c(i,j)]=n[c(j,i)]};t(n)}

```

Try it online!
> 1 votes

# Answer
# Clean, 240 bytes

```
import StdEnv
$l=limit(iterate?l)
?[]=[]
?l#[a:b]= @l
=[a: ?b]
@[[a,b:c]:t]#(t,[u:v])=case t of[[p:q]:t]=([q:t],if(a>p&&b>=p)[b,p,a]if(a>b)[a,b,p][b,a,p]);_=(t,sortBy(>)[a,b])
=[v%(i,i)++j\\i<-[0..]&j<- @[[u:c]:t]]
@l=sort(take 2l)++drop 2l

```

Try it online!

Implements the algorithm exactly as described.

Link includes input parsing to take the format in the question.
> 0 votes

# Answer
# Python 2, ~~215~~ 208 bytes

```
m=input()
h=len(m);w=len(m[0])
while 1:
 M=eval(`m`)
 for k in range(h*w):i,j=k/w,k%w;v,b,a=min([(M[x][y],y,x)for x,y in(i,j),(i+(i<h-1),j),(i,j+(j<w-1))]);M[i][j],M[a][b]=M[a][b],M[i][j]
 M!=m or exit(M);m=M

```

Try it online!

-7 bytes, thanks to ovs
> 0 votes

# Answer
# C# (.NET Core), 310 bytes

Without LINQ. Uses using System.Collections.Generic only for formatting the output after the function is returned. Thing is stupid huge. Looking forward to the golfs!

```
a=>{int x=a.GetLength(0),y=a.GetLength(1);bool u,o;int j=0,k,l,t,z;for(;j<x*y;j++)for(k=0;k<x;k++)for(l=0;l<y;){o=l>y-2?0>1:a[k,l+1]<a[k,l];u=k>x-2?0>1:a[k+1,l]<a[k,l];z=t=a[k,l];if((u&!o)|((u&o)&&(a[k,l+1]>=a[k+1,l]))){t=a[k+1,l];a[k+1,l]=z;}else if((!u&o)|(u&o)){t=a[k,l+1];a[k,l+1]=z;}a[k,l++]=t;}return a;}

```

Try it online!
> 0 votes

# Answer
# Python 2, 198 bytes

```
G=input()
O=e=enumerate
while O!=G:
 O=eval(`G`)
 for i,k in e(G):
	for j,l in e(k):v,x,y=min((G[i+x/2][j+x%2],x&1,x/2)for x in(0,1,2)if i+x/2<len(G)and j+x%2<len(k));G[i][j],G[i+y][j+x]=v,l
print G

```

Try it online!

Developed independently from TFeld's answer, has some differences.
> 0 votes

# Answer
# Charcoal, 118 bytes

```
≔Ｉ9.e999η≧⁻ηηＦθ⊞ιη⊞θ⟦η⟧ＦΣＥθＬι«ＦＬθ«≔§θκιＦＬι«≔§ιλζ≔§ι⊕λε≔§§θ⊕κλδ¿››ζδ›δε«§≔§θ⊕κλζ§≔ιλδ»¿›ζε«§≔ι⊕λζ§≔ιλε»»»»¿⊟θ¿Ｅθ⊟ιＥθ⪫ι

```

Try it online! Link is to verbose version of code. I've also spent a few bytes on some prettier formatting. Explanation:

```
≔Ｉ9.e999η≧⁻ηηＦθ⊞ιη⊞θ⟦η⟧

```

JavaScript has the convenient property that `a[i]>a[i+1]` is false if `i` is the last element of the array. To emulate that in Charcoal, I calculate a `nan` by casting `9.e999` to float and then subtracting it from itself. (Charcoal doesn't support exponential float constants.) I then pad the original array on the right with the `nan` and also add an additional row containing just the `nan`. (Charcoal's cyclic indexing means that I only need one element in that row.)

```
ＦΣＥθＬι«

```

Loop for each element in the array. This should be more than enough loops to get the job done, as I'm including all the extra `nan`s too.

```
ＦＬθ«≔§θκι

```

Loop over each row index and get the row at that index. (Charcoal can do both with an expression but not with a command.) This includes the dummy row but that's not a problem because all of the comparisons will fail.

```
ＦＬι«≔§ιλζ

```

Loop over each column index and get the value at that index. Again, this will loop over the dummy values but the comparisons will just fail again.

```
≔§ι⊕λε≔§§θ⊕κλδ

```

Also get the values to the right and below.

```
¿››ζδ›δε«§≔§θ⊕κλζ§≔ιλδ»

```

If the cell is greater than the value below and it's not true that the value below is greater than the value to the right then swap the cell with the value below.

```
¿›ζε«§≔ι⊕λζ§≔ιλε»»»»

```

Otherwise if the cell is greater than the value to the right then swap them.

```
¿⊟θ¿Ｅθ⊟ιＥθ⪫ι

```

Remove the `nan` values and format the array for implicit output.
> 0 votes

# Answer
# Kotlin, 325 bytes

```
{m:Array<Array<Int>>->val v={r:Int,c:Int->if(r<m.size&&c<m[r].size)m[r][c]
else 65536}
do{var s=0>1
for(r in m.indices)for(c in m[r].indices)when{v(r,c)>v(r+1,c)&&v(r+1,c)<=v(r,c+1)->m[r][c]=m[r+1][c].also{m[r+1][c]=m[r][c]
s=0<1}
v(r,c)>v(r,c+1)&&v(r,c+1)<v(r+1,c)->m[r][c]=m[r][c+1].also{m[r][c+1]=m[r][c]
s=0<1}}}while(s)}

```

Try it online!
> 0 votes

---
Tags: code-golf, grid
---


title: Jumping Numbers

text:
# Question
Title: Jumping Numbers
A jumping number is defined as a positive number n which all pairs of consecutive decimal digits differ by 1. Also, all single digit numbers are considered jumping numbers. eg. 3, 45676, 212 are jumping numbers but 414 and 13 are not. The difference between 9 and 0 is not considered as 1

**The challenge** Create a program that output one of the following results:

* Given an input `n` output the first `n` jumping numbers.
* Given an input `n` output the `n`th term of the sequence.

**Note**

* Any valid I/O format is allowed
* 1-index or 0-index is allowed (please specify)

Here are some jumping numbers:

```
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 21, 23, 32, 34, 43, 45, 54, 56, 65, 67, 76, 78, 87, 89, 98, 101, 121, 123, 210, 212, 232, 234, 321, 323, 343, 345, 432, 434, 454, 456, 543, 545, 565, 567, 654, 656, 676, 678, 765, 767, 787, 789, 876, ...

```

This is also A033075

# Answer
> 8 votes
# Haskell, 57 bytes

```
(l!!)
l=[1..9]++[x*10+t|x<-l,t<-[0..9],(mod x 10-t)^2==1]

```

Try it online!

# Answer
> 6 votes
# Jelly, 8 bytes

```
1DI*`ƑƊ#

```

A full program accepting an integer, `n`, from STDIN which prints a list of the first `n` positive jumping numbers.

**Try it online!**

### How?

Acceptable incremental differences between digits are `1` and `-1` while others from `[-9,-2]+[2,9]` are not. This lines up with integers which are invariant when raised to themselves. i.e. \\$x^x=x\\$ since:

$$0^0=1$$ $$1^1=1$$ $$2^2=4$$ $$\cdots$$ $$-1^{-1}=-1$$ $$-2^{-2}=-\frac{1}{4}$$ $$\cdots$$

```
1DI*`ƑƊ# - Main Link: no arguments (accepts a line of input from STDIN)
       # - count up keeping the first (input) n matches...
1        - ...start with n equal to: 1
      Ɗ  - ...match function: last three links as a monad:  e.g. 245       777      7656
 D       -   convert to a list of decimal digits                 [2,4,5]   [7,7,7]  [7,6,5,6]
  I      -   incremental differences                             [2,1]     [0,0]    [-1,-1,1]
     Ƒ   -   invariant under?:
    `    -     using left argument as both inputs of:
   *     -       exponentiation (vectorises)                     [4,1]     [1,1]    [-1,-1,1]
         -                                            --so we:   discard   discard  keep
         - implicitly print the list of collected values of n

```

# Answer
> 6 votes
# 05AB1E (legacy), 5 bytes

The input is 1-indexed.

### Code:

```
µN¥ÄP

```

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

### Explanation

```
µ          # Get the nth number, starting from 0, such that...
   Ä       #   The absolute values
 N¥        #   Of the delta's of N
    P      #   Are all 1 (product function, basically acts as a reduce by AND)

```

# Answer
> 5 votes
# Python 2, ~~79~~ 75 bytes

*-4 bytes by xnor*

```
f=lambda n,i=1:n and-~f(n-g(i),i+1)
g=lambda i:i<10or i%100%11%9==g(i/10)>0

```

Try it online!

Derived from Chas Brown's answer. The helper function `g(i)` returns whether `i` is a jumping number. Iff the last two digits of a number `n` have absolute difference 1, then `n%100%11` will be either 1 or 10, so `n%100%11%9` will be 1.

# Answer
> 4 votes
# APL (Dyalog Unicode), 36 bytesSBCS

1-indexed. Thanks to dzaima for their help with golfing this.

Edit: -15 bytes from ngn.

```
1+⍣{∧/1=|2-/⍎¨⍕⍺}⍣⎕⊢0

```

Try it online!

**Explanation**

We have `f⍣g⍣h`, where, as  is an operator, APL translates this to `(f⍣g)⍣h`. (In contrast with functions where `2×3+1` is translated `2×(3+1)`)

```
1+⍣{...}⍣⎕⊢0  This is equivalent to
               "do {check} we find the n-th integer that fulfils {check}"

1+⍣{...}   ⊢0  Start with 0 and keep adding 1s until the dfn
               (our jumping number check in {}) returns true.
        ⍣⎕    We take input n (⎕) and repeat (⍣) the above n times
               to get the n-th jumping number.

{∧/1=|2-/⍎¨⍕⍺}  The dfn that checks for jumping numbers.

         ⍎¨⍕⍺   We take the base-10 digits of our left argument
                 by evaluating each character of the string representation of ⍺.
     |2-/        Then we take the absolute value of the pairwise differences of the digits
 ∧/1=            and check if all of the differences are equal to 1.

```

# Answer
> 3 votes
# C (gcc), 90 bytes

```
f(n,K,b,k){for(K=0;n;b&&printf("%d,",K,n--))for(b=k=++K;k/10;)b*=abs(k%10-(k/=10)%10)==1;}

```

Try it online!

# Answer
> 3 votes
# Japt, 14 bytes

Outputs the first `n`th term, 1-indexed.

```
_ì äa dÉ ªU´}f

```

Try it

(I know, I know, I'm supposed to be taking a break but I'm in golf withdrawal!)

# Answer
> 3 votes
# Haskell, 69 bytes

* Thanks to Joseph Sible for enforcing the challenge rules and saving three bytes.
* Saved two bytes thanks to nimi.

```
(filter(all((==1).abs).(zipWith(-)<*>tail).map fromEnum.show)[1..]!!)

```

Try it online!

# Answer
> 3 votes
# Python 2, ~~88~~ 87 bytes

```
f=lambda n,i=2:n and f(n-g(i),i+1)or~-i
g=lambda i:i<10or abs(i/10%10-i%10)==1==g(i/10)

```

Try it online!

Returns the 0-indexed jumping number (i.e., f(0) =\> 1, etc).

# Answer
> 2 votes
# Jelly, 9 bytes

*-1 by Jonathan Allan*

```
1DạƝ=1ẠƲ#

```

Try it online!

1-indexed.

# Answer
> 2 votes
# JavaScript (ES7), 60 bytes

Returns the \\$n\\$th term of the sequence (1-indexed).

```
f=(n,k)=>[...k+''].some(p=x=>(p-(p=x))**2-1)||n--?f(n,-~k):k

```

Try it online!

# Answer
> 1 votes
# Swift, 228 bytes

```
func j(n:Int){
var r:[Int]=[]
for x in 0...n{
if x<=10{r.append(x)}else{
let t=String(x).compactMap{Int(String($0))}
var b=true
for i in 1...t.count-1{if abs(t[i-1]-t[i]) != 1{b=false}}
if b{r.append(x)}
}
}
print(r)
}
j(n:1000)

```

Try it online!

# Answer
> 1 votes
# Python 3, ~~122~~ 121 bytes

```
g=lambda s:len(s)==1or 1==abs(ord(s[0])-ord(s[1]))and g(s[1:])
def f(n,i=1):
	while n:
		if g(str(i)):n-=1;yield i
		i+=1

```

Try it online!

-1 byte by changing `f` from printing, to a generator function.

`g` is a recursive helper function which determines if a string `s` is a "jumping string" (this works since the character codes for 0 to 9 are in order and contiguous).

`f` is a generator function that takes in `n` and yields the first `n` jumping numbers.

# Answer
> 1 votes
# , 85 bytes

```
i=scan();j=0;while(i)if((j=j+1)<10|all(abs(diff(j%/%10^(0:log10(j))%%10))==1))i=i-1;j

```

Try it online!

Suspect this can be golfed more. Reads the number using `scan()` and outputs the appropriate jumping number.

# Answer
> 1 votes
# Perl 5, 56 bytes

```
map{1while++$n=~s|.(?=(.))|abs$&-$1!=1|ger>9}1..<>;say$n

```

Try it online!

1-indexed, outputs the nth jumping number

# Answer
> 1 votes
# Wolfram Language (Mathematica), 85 bytes

```
If[#<10,#,t=n=1;While[t<=#,{-1,1}~SubsetQ~Differences@IntegerDigits@n++~If~t++];n-1]&

```

Try it online!

returns the n-th number

# Answer
> 1 votes
# Factor, 129 bytes

```
: f ( x -- ) 1 [ [ dup 10 >base >array differences [ abs 1 = ] all? ] [ 1 + ] until
dup . 1 + [ 1 - ] dip over 0 > ] loop 2drop ;

```

Try it online!

Outputs the first `n` jumping numbers

# Answer
> 1 votes
# Catholicon, 5 bytes

```
ρHṘḃǰ

```

Try it online!

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